ILIAS  eassessment Revision 61809
 All Data Structures Namespaces Files Functions Variables Groups 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 {
27  function getImageTagByType($a_type, $a_path, $a_big = false)
28  {
29  global $lng;
30 
31  if ($a_big)
32  {
33  $big = "_b";
34  }
35  $filename = "icon_".$a_type."$big.gif";
36 
37  return "<img src=\"".ilUtil::getImagePath($filename)."\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
38  //return "<img src=\"".$a_path."/images/"."icon_".$a_type."$big.gif\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
39  }
40 
52  public function getTypeIconPath($a_type,$a_obj_id,$a_size = 'small')
53  {
54  global $ilSetting;
55 
56  if($ilSetting->get("custom_icons"))
57  {
58  switch($a_type)
59  {
60  case 'cat':
61  case 'crs':
62  case 'grp':
63  include_once('./Services/Container/classes/class.ilContainer.php');
64  if(strlen($path = ilContainer::_lookupIconPath($a_obj_id,$a_size)))
65  {
66  return $path;
67  }
68  }
69  }
70 
71  switch($a_size)
72  {
73  case 'tiny':
74  $postfix = '_s.gif';
75  break;
76  case 'big':
77  $postfix = '_b.gif';
78  break;
79  default:
80  $postfix = '.gif';
81  break;
82  }
83  return ilUtil::getImagePath('icon_'.$a_type.$postfix);
84  }
85 
94  function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
95  {
96  global $ilias, $styleDefinition, $ilCtrl, $ilUser;
97 
98  if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php")))
99  {
100  $module_path = "..";
101  }
102  if ($module_path != "")
103  {
104  $module_path = "/".$module_path;
105  }
106 
107  // default image
108  $default_img = ".".$module_path."/templates/default/images/".$img;
109 
110  if (is_object($styleDefinition))
111  {
112  $image_dir = $styleDefinition->getImageDirectory($ilias->account->prefs["style"]);
113  }
114  if ($ilUser->skin == "default")
115  {
116  $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
117  $skin_img = ".".$module_path."/templates/default/images/".$img;
118  }
119  else if (is_object($styleDefinition) && $ilUser->skin != "default")
120  {
121  $user_img = "./Customizing/global/skin/".
122  $ilias->account->skin.$module_path."/".$image_dir."/".$img;
123  $skin_img = "./Customizing/global/skin/".
124  $ilias->account->skin.$module_path."/images/".$img;
125  }
126 
127  if ($offline)
128  {
129  return "./images/".$img;
130  }
131  else if (@file_exists($user_img) && $image_dir != "")
132  {
133  return $user_img; // found image for skin and style
134  }
135  else if (file_exists($skin_img))
136  {
137  return $skin_img; // found image in skin/images
138  }
139 
140  return $default_img; // take image in default
141  }
142 
151  function getHtmlPath($relative_path)
152  {
153  if (substr($relative_path, 0, 2) == './')
154  {
155  $relative_path = (substr($relative_path, 1));
156  }
157  if (substr($relative_path, 0, 1) != '/')
158  {
159  $relative_path = '/' . $relative_path;
160  }
161  $htmlpath = ILIAS_HTTP_PATH . $relative_path;
162  return $htmlpath;
163  }
164 
175  function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
176  {
177  global $ilias;
178 
179  // add version as parameter to force reload for new releases
180  $stylesheet_name = (strlen($a_css_name)) ? $a_css_name : $ilias->account->prefs["style"].".css";
181  if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0)) $a_css_location = $a_css_location . "/";
182 
183  $filename = "";
184  if ($ilias->account->skin != "default")
185  {
186  $filename = "./Customizing/global/skin/".$ilias->account->skin."/".$a_css_location.$stylesheet_name;
187  }
188  if (strlen($filename) == 0 || !file_exists($filename))
189  {
190  $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
191  }
192  $vers = "";
193  if ($mode != "filesystem")
194  {
195  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
196  $vers = "?vers=".str_replace(".", "-", $vers);
197  }
198  return $filename . $vers;
199  }
200 
209  function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
210  {
211  global $ilias;
212 
213  // add version as parameter to force reload for new releases
214  $js_name = $a_js_name;
215  if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
216 
217  $filename = "";
218  if ($ilias->account->skin != "default")
219  {
220  $filename = "./Customizing/global/skin/".$ilias->account->skin."/".$a_js_location.$js_name;
221  }
222  if (strlen($filename) == 0 || !file_exists($filename))
223  {
224  $filename = "./" . $a_js_location . "templates/default/".$js_name;
225  }
226  $vers = "";
227  if ($add_version)
228  {
229  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
230  $vers = "?vers=".str_replace(".", "-", $vers);
231  }
232  return $filename . $vers;
233  }
234 
240  function getP3PLocation()
241  {
242  global $ilias;
243 
244  if (defined("ILIAS_MODULE"))
245  {
246  $base = '';
247  for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
248  {
249  $base .= "../Services/Privacy/";
250  }
251  }
252  else
253  {
254  $base = "./Services/Privacy/";
255  }
256 
257  if (is_file($base."w3c/p3p.xml"))
258  {
259  return ILIAS_HTTP_PATH."w3c/p3p.xml";
260  }
261  else
262  {
263  return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
264  }
265  }
266 
272  function getNewContentStyleSheetLocation($mode = "output")
273  {
274  global $ilias;
275 
276  // add version as parameter to force reload for new releases
277  if ($mode != "filesystem")
278  {
279  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
280  $vers = "?vers=".str_replace(".", "-", $vers);
281  }
282 
283  if ($ilias->account->skin == "default")
284  {
285  $in_style = "./templates/".$ilias->account->skin."/".$ilias->account->prefs["style"]."_cont.css";
286  }
287  else
288  {
289  $in_style = "./Customizing/global/skin/".$ilias->account->skin."/".$ilias->account->prefs["style"]."_cont.css";
290  }
291 
292  if (is_file("./".$in_style))
293  {
294  return $in_style.$vers;
295  }
296  else
297  {
298  return "templates/default/delos_cont.css".$vers;
299  }
300  }
301 
318  public static function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
319  $style_class = "", $attribs = "",$disabled = false)
320  {
321  global $lng;
322 
323  if ($multiple == true)
324  {
325  $multiple = " multiple=\"multiple\"";
326  }
327  else
328  {
329  $multiple = "";
330  $size = 0;
331  }
332 
333  if ($style_class != "")
334  {
335  $class = " class=\"".$style_class."\"";
336  }
337  else
338  {
339  $class = "";
340  }
341  $attributes = "";
342  if (is_array($attribs))
343  {
344  foreach ($attribs as $key => $val)
345  {
346  $attributes .= " ".$key."=\"".$val."\"";
347  }
348  }
349  if($disabled)
350  {
351  $disabled = ' disabled=\"disabled\"';
352  }
353 
354  $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
355 
356  foreach ($options as $key => $val)
357  {
358  $style = "";
359  if (is_array($val))
360  {
361  $style = $val["style"];
362  $val = $val["text"]; // mus be last line, since we overwrite
363  }
364 
365  $sty = ($style != "")
366  ? ' style="'.$style.'" '
367  : "";
368 
369  if ($direct_text)
370  {
371  $str .= " <option $sty value=\"".$key."\"";
372  }
373  else
374  {
375  $str .= " <option $sty value=\"".$val."\"";
376  }
377  if (is_array($selected) )
378  {
379  if (in_array($key,$selected))
380  {
381  $str .= " selected=\"selected\"";
382  }
383  }
384  else if ($selected == $key)
385  {
386  $str .= " selected=\"selected\"";
387  }
388 
389  if ($direct_text)
390  {
391  $str .= ">".$val."</option>\n";
392  }
393  else
394  {
395  $str .= ">".$lng->txt($val)."</option>\n";
396  }
397  }
398 
399  $str .= "</select>\n";
400 
401  return $str;
402  }
403 
411  function getSelectName ($selected,$values)
412  {
413  return($values[$selected]);
414  }
415 
425  public static function formCheckbox ($checked,$varname,$value,$disabled = false)
426  {
427  $str = "<input type=\"checkbox\" name=\"".$varname."\"";
428 
429  if ($checked == 1)
430  {
431  $str .= " checked=\"checked\"";
432  }
433 
434  if ($disabled)
435  {
436  $str .= " disabled=\"disabled\"";
437  }
438 
439  $array_var = false;
440 
441  if (substr($varname,-2) == "[]")
442  {
443  $array_var = true;
444  }
445 
446  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
447  if ($array_var)
448  {
449  $varname_id = substr($varname,0,-2)."_".$value;
450  }
451  else
452  {
453  $varname_id = $varname;
454  }
455 
456  // dirty removal of other "[]" in string
457  $varname_id = ereg_replace("\[","_",$varname_id);
458  $varname_id = ereg_replace("\]","",$varname_id);
459 
460  $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
461 
462  return $str;
463  }
464 
474  function formDisabledRadioButton($checked,$varname,$value,$disabled)
475  {
476  if ($disabled) {
477  $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
478  }
479  else {
480  $str = "<input type=\"radio\" name=\"".$varname."\"";
481  }
482  if ($checked == 1)
483  {
484  $str .= " checked=\"checked\"";
485  }
486 
487  $str .= " value=\"".$value."\"";
488  $str .= " id=\"".$value."\" />\n";
489 
490  return $str;
491 
492  }
493 
494 
503  function formRadioButton($checked,$varname,$value)
504  {
505  $str = "<input type=\"radio\" name=\"".$varname."\"";
506  if ($checked == 1)
507  {
508  $str .= " checked=\"checked\"";
509  }
510 
511  $str .= " value=\"".$value."\"";
512 
513  $str .= " id=\"".$value."\" />\n";
514 
515  return $str;
516  }
517 
518 
527  function formInput($varname,$value,$disabled = false)
528  {
529 
530  $str = "<input type=\"input\" name=\"".$varname."\"";
531  if ($disabled)
532  {
533  $str .= " disabled";
534  }
535 
536  $str .= " value=\"".$value."\"";
537 
538  $str .= " id=\"".$value."\" />\n";
539 
540  return $str;
541  }
542 
543 
548  function checkInput ($vars)
549  {
550  // TO DO:
551  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
552  }
553 
559  function setPathStr ($a_path)
560  {
561  if ("" != $a_path && "/" != substr($a_path, -1))
562  {
563  $a_path .= "/";
564  //$a_path = substr($a_path,1);
565  }
566 
567  //return getcwd().$a_path;
568  return $a_path;
569  }
570 
581  function switchColor ($a_num,$a_css1,$a_css2)
582  {
583  if (!($a_num % 2))
584  {
585  return $a_css1;
586  }
587  else
588  {
589  return $a_css2;
590  }
591  }
592 
602  function showTabs($a_hl, $a_o)
603  {
604  global $lng;
605 
606  $tpltab = new ilTemplate("tpl.tabs.html", true, true);
607 
608  for ($i=1; $i<=4; $i++)
609  {
610  $tpltab->setCurrentBlock("tab");
611  if ($a_hl == $i)
612  {
613  $tabtype = "tabactive";
614  $tab = $tabtype;
615  }
616  else
617  {
618  $tabtype = "tabinactive";
619  $tab = "tab";
620  }
621 
622  switch ($i)
623  {
624  case 1:
625  $txt = $lng->txt("view_content");
626  break;
627  case 2:
628  $txt = $lng->txt("edit_properties");
629  break;
630  case 3:
631  $txt = $lng->txt("perm_settings");
632  break;
633  case 4:
634  $txt = $lng->txt("show_owner");
635  break;
636  } // switch
637  $tpltab->setVariable("CONTENT", $txt);
638  $tpltab->setVariable("TABTYPE", $tabtype);
639  $tpltab->setVariable("TAB", $tab);
640  $tpltab->setVariable("LINK", $a_o["LINK".$i]);
641  $tpltab->parseCurrentBlock();
642  }
643 
644  return $tpltab->get();
645  }
646 
647 
648 
655  function checkFormEmpty ($emptyFields)
656  {
657 
658  $feedback = "";
659 
660  foreach ($emptyFields as $key => $val)
661  {
662  if ($val == "") {
663  if ($feedback != "") $feedback .= ", ";
664  $feedback .= $key;
665  }
666  }
667 
668  return $feedback;
669  }
670 
693  function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
694  {
695  $LinkBar = "";
696 
697  $layout_link = "";
698  $layout_prev = "&lt;&lt;";
699  $layout_next = "&gt;&gt;";
700 
701  // layout options
702  if (count($ALayout > 0))
703  {
704  if ($ALayout["link"])
705  {
706  $layout_link = " class=\"".$ALayout["link"]."\"";
707  }
708 
709  if ($ALayout["prev"])
710  {
711  $layout_prev = $ALayout["prev"];
712  }
713 
714  if ($ALayout["next"])
715  {
716  $layout_next = $ALayout["next"];
717  }
718  }
719 
720  // show links, if hits greater limit
721  // or offset > 0 (can be > 0 due to former setting)
722  if ($AHits > $ALimit || $AOffset > 0)
723  {
724  if (!empty($AParams))
725  {
726  foreach ($AParams as $key => $value)
727  {
728  $params.= $key."=".$value."&";
729  }
730  }
731  // if ($params) $params = substr($params,0,-1);
732  if(strpos($AScript,'&'))
733  {
734  $link = $AScript."&".$params.$prefix."offset=";
735  }
736  else
737  {
738  $link = $AScript."?".$params.$prefix."offset=";
739  }
740 
741  // ?bergehe "zurck"-link, wenn offset 0 ist.
742  if ($AOffset >= 1)
743  {
744  $prevoffset = $AOffset - $ALimit;
745  if ($prevoffset < 0) $prevoffset = 0;
746  $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
747  }
748 
749  // Ben?tigte Seitenzahl kalkulieren
750  $pages=intval($AHits/$ALimit);
751 
752  // Wenn ein Rest bleibt, addiere eine Seite
753  if (($AHits % $ALimit))
754  $pages++;
755 
756  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
757  // if ($AOffset != 0) {
758 
759  // ansonsten zeige Links zu den anderen Seiten an
760  for ($i = 1 ;$i <= $pages ; $i++)
761  {
762  $newoffset=$ALimit*($i-1);
763 
764  if ($newoffset == $AOffset)
765  {
766  $LinkBar .= "[".$i."] ";
767  }
768  else
769  {
770  $LinkBar .= '<a '.$layout_link.' href="'.
771  $link.$newoffset.'">['.$i.']</a> ';
772  }
773  }
774  // }
775 
776  // Checken, ob letze Seite erreicht ist
777  // Wenn nicht, gebe einen "Weiter"-Link aus
778  if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
779  {
780  $newoffset=$AOffset+$ALimit;
781  $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
782  }
783 
784  return $LinkBar;
785  }
786  else
787  {
788  return false;
789  }
790  }
791 
801  public static function makeClickable($a_text, $detectGotoLinks = false)
802  {
803  // New code, uses MediaWiki Sanitizer
804  $ret = $a_text;
805 
806  // www-URL ohne ://-Angabe
807  $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
808  "\\1http://\\2\\3", $ret);
809 
810  // ftp-URL ohne ://-Angabe
811  $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
812  "\\1ftp://\\2\\3", $ret);
813 
814  // E-Mail (this does not work as expected, users must add mailto: manually)
815  //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
816  // "mailto:\\1", $ret);
817 
818  // mask existing image tags
819  $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
820 
821  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
822  $parser = new ilMWParserAdapter();
823  $ret = $parser->replaceFreeExternalLinks($ret);
824 
825  // unmask existing image tags
826  $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
827 
828  // Should be Safe
829 
830  if ($detectGotoLinks)
831  // replace target blank with self and text with object title.
832  {
833  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
834 // echo htmlentities($regExp);
835  $ret = preg_replace_callback(
836  "/".$regExp."/i",
837  array("ilUtil", "replaceLinkProperties"),
838  $ret);
839 
840  // Static links
841  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
842 // echo htmlentities($regExp);
843  $ret = preg_replace_callback(
844  "/".$regExp."/i",
845  array("ilUtil", "replaceLinkProperties"),
846  $ret);
847  }
848 
849  return($ret);
850  }
851 
863  function replaceLinkProperties ($matches)
864  {
865  $link = $matches[0];
866  $ref_id = $matches[2];
867 
868  if ($ref_id > 0)
869  {
870  $obj_id = ilObject::_lookupObjId($ref_id);
871  if ($obj_id > 0)
872  {
873  $title = ilObject::_lookupTitle($obj_id);
874  $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
875  }
876  }
877  return $link;
878  }
879 
896  function StopWatch($begin = -1)
897  {
898  $m = explode(" ",microtime());
899  $m = $m[0] + $m[1];
900 
901  if ($begin != -1)
902  {
903  $m = $m - $begin;
904  }
905 
906  return($m);
907  }
908 
925  function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
926  {
927  global $lng;
928 
929  $disabled = '';
930  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
931  {
932  $disabled = 'disabled="disabled" ';
933  }
934 
935  $now = getdate();
936  if (!$emptyoption)
937  {
938  if (!strlen($year)) $year = $now["year"];
939  if (!strlen($month)) $month = $now["mon"];
940  if (!strlen($day)) $day = $now["mday"];
941  }
942 
943  $year = (int) $year;
944  $month = (int) $month;
945  $day = (int) $day;
946 
947  // build day select
948 
949  $sel_day .= '<select ';
950  if(isset($a_further_options['select_attributes']))
951  {
952  foreach($a_further_options['select_attributes'] as $name => $value)
953  {
954  $sel_day .= ($name.'="'.$value.'" ');
955  }
956  }
957 
958  $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
959 
960  if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
961  for ($i = 1; $i <= 31; $i++)
962  {
963  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
964  }
965  $sel_day .= "</select>\n";
966  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
967 
968  // build month select
969  $sel_month = '<select ';
970  if(isset($a_further_options['select_attributes']))
971  {
972  foreach($a_further_options['select_attributes'] as $name => $value)
973  {
974  $sel_month .= ($name.'="'.$value.'" ');
975  }
976  }
977  $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
978 
979  if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
980  for ($i = 1; $i <= 12; $i++)
981  {
982  if($a_long_month)
983  {
984  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
985  }
986  else
987  {
988  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
989  }
990  }
991  $sel_month .= "</select>\n";
992  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
993 
994  // build year select
995  $sel_year = '<select ';
996  if(isset($a_further_options['select_attributes']))
997  {
998  foreach($a_further_options['select_attributes'] as $name => $value)
999  {
1000  $sel_year .= ($name.'="'.$value.'" ');
1001  }
1002  }
1003  $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
1004  if ((strlen($startyear) == 0) || ($startyear > $year))
1005  {
1006  if (!$emptyoption || $year != 0) $startyear = $year - 5;
1007  }
1008 
1009  if(($year + 5) < (date('Y',time()) + 5))
1010  {
1011  $end_year = date('Y',time()) + 5;
1012  }
1013  else
1014  {
1015  $end_year = $year + 5;
1016  }
1017 
1018  if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
1019  for ($i = $startyear; $i <= $end_year; $i++)
1020  {
1021  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
1022  }
1023  $sel_year .= "</select>\n";
1024  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
1025 
1026  //$dateformat = $lng->text["lang_dateformat"];
1027  $dateformat = "d-m-Y";
1028  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1029  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1030  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1031  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1032  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1033  return $dateformat;
1034  }
1035 
1052  function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1053  {
1054  global $lng, $ilUser;
1055 
1056  $minute_steps = 1;
1057  $disabled = '';
1058  if(count($a_further_options))
1059  {
1060  if(isset($a_further_options['minute_steps']))
1061  {
1062  $minute_steps = $a_further_options['minute_steps'];
1063  }
1064  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1065  {
1066  $disabled = 'disabled="disabled" ';
1067  }
1068  }
1069 
1070  if ($a_use_default and !strlen("$hour$minute$second")) {
1071  $now = localtime();
1072  $hour = $now[2];
1073  $minute = $now[1];
1074  $second = $now[0];
1075  } else {
1076  $hour = (int)$hour;
1077  $minute = (int)$minute;
1078  $second = (int)$second;
1079  }
1080  // build hour select
1081  $sel_hour = '<select ';
1082  if(isset($a_further_options['select_attributes']))
1083  {
1084  foreach($a_further_options['select_attributes'] as $name => $value)
1085  {
1086  $sel_hour .= $name.'='.$value.' ';
1087  }
1088  }
1089  $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\">\n";
1090 
1091  $format = $ilUser->getTimeFormat();
1092  for ($i = 0; $i <= 23; $i++)
1093  {
1094  if($format == ilCalendarSettings::TIME_FORMAT_24)
1095  {
1096  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1097  }
1098  else
1099  {
1100  $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1101  }
1102  }
1103  $sel_hour .= "</select>\n";
1104  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1105 
1106  // build minutes select
1107  $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
1108 
1109  for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1110  {
1111  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1112  }
1113  $sel_minute .= "</select>\n";
1114  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1115 
1116  if (!$short) {
1117  // build seconds select
1118  $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\">\n";
1119 
1120  for ($i = 0; $i <= 59; $i++)
1121  {
1122  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1123  }
1124  $sel_second .= "</select>\n";
1125  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1126  }
1127  $timeformat = $lng->text["lang_timeformat"];
1128  if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1129  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1130  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1131  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1132  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1133  if ($short) {
1134  $timeformat = preg_replace("/%%s/", "", $timeformat);
1135  } else {
1136  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1137  }
1138  return $timeformat;
1139  }
1140 
1141  /*
1142  * This preg-based function checks whether an e-mail address is formally valid.
1143  * It works with all top level domains including the new ones (.biz, .info, .museum etc.)
1144  * and the special ones (.arpa, .int etc.)
1145  * as well as with e-mail addresses based on IPs (e.g. webmaster@123.45.123.45)
1146  * Valid top level domains: http://data.iana.org/TLD/tlds-alpha-by-domain.txt
1147  * @author Unknown <mail@philipp-louis.de> (source: http://www.php.net/preg_match)
1148  * @access public
1149  * @param string email address
1150  * @return boolean true if valid
1151  */
1152  function is_email($a_email)
1153  {
1154  // BEGIN Mail: If possible, use PearMail to validate e-mail address
1155  global $ilErr, $ilias;
1156 
1157  // Note the use of @include_once here. We need this, because
1158  // inclusion fails when the function is_email is called from setup.php.
1159  $successfulInclude = @include_once ('Services/Mail/classes/class.ilMail.php');
1160 
1161  // additional checks for include and ilias object are needed,
1162  // otherwise setup will fail with this if branch
1163  if ($successfulInclude && is_object($ilias) && ilMail::_usePearMail())
1164  {
1165  require_once 'Mail/RFC822.php';
1166  $parser = &new Mail_RFC822();
1168  try {
1169  $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1170  if (! is_a($addresses, 'PEAR_Error') &&
1171  count($addresses) == 1 && $addresses[0]->host != 'ilias')
1172  {
1173  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1174  return true;
1175  }
1176  } catch (Exception $e) {
1177  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1178  return false;
1179  }
1180  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1181  return false;
1182  }
1183  else
1184  {
1185  $tlds = strtolower(
1186  "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|".
1187  "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|".
1188  "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|".
1189  "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|".
1190  "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|".
1191  "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|".
1192  "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|".
1193  "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|".
1194  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1195 
1196  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));
1197  }
1198  // END Mail: If possible, use PearMail to validate e-mail address
1199  }
1200 
1201  /*
1202  * validates a password
1203  * @access public
1204  * @param string password
1205  * @return boolean true if valid
1206  */
1207  function isPassword($a_passwd, &$customError = null)
1208  {
1209  global $lng;
1210 
1211  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1212  $security = ilSecuritySettings::_getInstance();
1213 
1214  if( $security->getAccountSecurityMode() != ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1215  {
1217 
1218  $customError = null;
1219 
1220  switch( true )
1221  {
1222  // no empty password
1223  case empty($a_passwd):
1224 
1225  // min password length is 6
1226  case strlen($a_passwd) < 6:
1227 
1228  // valid chars for password
1229  case !preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~]+$/", $a_passwd):
1230 
1231  return false;
1232 
1233  default:
1234 
1235  return true;
1236  }
1237  }
1238 
1240 
1241  // check if password is empty
1242  if( empty($a_passwd) )
1243  {
1244  $customError = $lng->txt('password_empty');
1245  return false;
1246  }
1247 
1248  $isPassword = true;
1249  $errors = array();
1250 
1251  // check if password to short
1252  if( $security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength() )
1253  {
1254  $errors[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1255  $isPassword = false;
1256  }
1257 
1258  // check if password not to long
1259  if( $security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength() )
1260  {
1261  $errors[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1262  $isPassword = false;
1263  }
1264 
1265  // if password must contains Chars and Numbers
1266  if( $security->isPasswordCharsAndNumbersEnabled() )
1267  {
1268  $hasCharsAndNumbers = true;
1269  // check password for existing chars
1270  if( !preg_match('/[A-Za-z]+/',$a_passwd) )
1271  {
1272  $hasCharsAndNumbers = false;
1273  }
1274 
1275  // check password for existing numbers
1276  if( !preg_match('/[0-9]+/',$a_passwd) )
1277  {
1278  $hasCharsAndNumbers = false;
1279  }
1280 
1281  if( !$hasCharsAndNumbers )
1282  {
1283  $errors[] = $lng->txt('password_must_chars_and_numbers');
1284  $isPassword = false;
1285  }
1286  }
1287 
1288  // if password must contains Special-Chars
1289  if( $security->isPasswordSpecialCharsEnabled() )
1290  {
1291  $specialCharsReg = '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1292 
1293  // check password for existing special-chars
1294  if( !preg_match($specialCharsReg, $a_passwd) )
1295  {
1296  $errors[] = $lng->txt('password_must_special_chars');
1297  $isPassword = false;
1298  }
1299  }
1300 
1301  // ensure password matches the positive list of chars/special-chars
1302  if( !preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/", $a_passwd) )
1303  {
1304  $errors[] = $lng->txt('password_contains_invalid_chars');
1305  $isPassword = false;
1306  }
1307 
1308  // build custom error message
1309  if( count($errors) == 1 )
1310  {
1311  $customError = $errors[0];
1312  }
1313  elseif( count($errors) > 1 )
1314  {
1315  $customError = $lng->txt('password_multiple_errors');
1316  $customError .= '<br />'.implode('<br />', $errors);
1317  }
1318 
1319  return $isPassword;
1320  }
1321 
1329  {
1330  global $lng;
1331 
1332  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1333  $security = ilSecuritySettings::_getInstance();
1334 
1335  if( $security->getAccountSecurityMode() == ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1336  {
1337  $validPasswordChars = 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1338  }
1339  else
1340  {
1341  $validPasswordChars = 'A-Z a-z 0-9 _.+?#-*@!$%~';
1342  }
1343 
1344  return sprintf($lng->txt('password_allow_chars'), $validPasswordChars);
1345  }
1346 
1347  /*
1348  * validates a login
1349  * @access public
1350  * @param string login
1351  * @return boolean true if valid
1352  */
1353  function isLogin($a_login)
1354  {
1355  if (empty($a_login))
1356  {
1357  return false;
1358  }
1359 
1360  if (strlen($a_login) < 3)
1361  {
1362  return false;
1363  }
1364 
1365  // FIXME - If ILIAS is configured to use RFC 822
1366  // compliant mail addresses we should not
1367  // allow the @ character.
1368  if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1369  {
1370  return false;
1371  }
1372 
1373  return true;
1374  }
1375 
1387  public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1388  $a_keep_extension = false)
1389  {
1390  include_once("./Services/Utilities/classes/class.ilStr.php");
1391  if (ilStr::strLen($a_str) > $a_len)
1392  {
1393  if ($a_next_blank)
1394  {
1395  $len = ilStr::strPos($a_str, " ", $a_len);
1396  }
1397  else
1398  {
1399  $len = $a_len;
1400  }
1401  // BEGIN WebDAV
1402  // - Shorten names in the middle, before the filename extension
1403  // Workaround for Windows WebDAV Client:
1404  // Use the unicode ellipsis symbol for shortening instead of
1405  // three full stop characters.
1406  if ($a_keep_extension)
1407  {
1408  $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1409  }
1410  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1411  {
1412  $a_str = ilStr::subStr($a_str,0,$len);
1413  if ($a_dots)
1414  {
1415  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1416  }
1417  }
1418  else
1419  {
1420  if ($a_dots)
1421  {
1422  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1423  }
1424  else
1425  {
1426  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1427  }
1428  }
1429  }
1430 
1431  return $a_str;
1432  }
1433 
1442  function shortenWords($a_str, $a_len = 30, $a_dots = true)
1443  {
1444  include_once("./Services/Utilities/classes/class.ilStr.php");
1445  $str_arr = explode(" ", $a_str);
1446 
1447  for ($i = 0; $i < count($str_arr); $i++)
1448  {
1449  if (ilStr::strLen($str_arr[$i]) > $a_len)
1450  {
1451  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1452  if ($a_dots)
1453  {
1454  $str_arr[$i].= "...";
1455  }
1456  }
1457  }
1458 
1459  return implode($str_arr, " ");
1460  }
1461 
1469  function attribsToArray($a_str)
1470  {
1471  $attribs = array();
1472  while (is_int(strpos($a_str, "=")))
1473  {
1474  $eq_pos = strpos($a_str, "=");
1475  $qu1_pos = strpos($a_str, "\"");
1476  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1477  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1478  {
1479  $var = trim(substr($a_str, 0, $eq_pos));
1480  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1481  $attribs[$var] = $val;
1482  $a_str = substr($a_str, $qu2_pos + 1);
1483  }
1484  else
1485  {
1486  $a_str = "";
1487  }
1488  }
1489  return $attribs;
1490  }
1491 
1501  function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1502  {
1503  // check if arguments are directories
1504  if (!@is_dir($a_sdir) or
1505  !@is_dir($a_tdir))
1506  {
1507  return FALSE;
1508  }
1509 
1510  // read a_sdir, copy files and copy directories recursively
1511  $dir = opendir($a_sdir);
1512 
1513  while($file = readdir($dir))
1514  {
1515  if ($file != "." and
1516  $file != "..")
1517  {
1518  // directories
1519  if (@is_dir($a_sdir."/".$file))
1520  {
1521  if (!@is_dir($a_tdir."/".$file))
1522  {
1523  if (!ilUtil::makeDir($a_tdir."/".$file))
1524  return FALSE;
1525 
1526  //chmod($a_tdir."/".$file, 0775);
1527  }
1528 
1529  if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1530  {
1531  return FALSE;
1532  }
1533  }
1534 
1535  // files
1536  if (@is_file($a_sdir."/".$file))
1537  {
1538  if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1539  {
1540  return FALSE;
1541  }
1542  if ($preserveTimeAttributes)
1543  touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1544  }
1545  }
1546  }
1547  return TRUE;
1548  }
1549 
1557  function getWebspaceDir($mode = "filesystem")
1558  {
1559  global $ilias;
1560 
1561  if ($mode == "filesystem")
1562  {
1563  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1564  }
1565  else
1566  {
1567  if (defined("ILIAS_MODULE"))
1568  {
1569  return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1570  }
1571  else
1572  {
1573  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1574  }
1575  }
1576 
1577  //return $ilias->ini->readVariable("server","webspace_dir");
1578  }
1579 
1583  function getDataDir()
1584  {
1585  return CLIENT_DATA_DIR;
1586  //global $ilias;
1587 
1588  //return $ilias->ini->readVariable("server", "data_dir");
1589  }
1590 
1598  function getUsersOnline($a_user_id = 0)
1599  {
1600  include_once("./Services/User/classes/class.ilObjUser.php");
1601  return ilObjUser::_getUsersOnline($a_user_id);
1602  }
1603 
1612  function getAssociatedUsersOnline($a_user_id)
1613  {
1614  include_once("./Services/User/classes/class.ilObjUser.php");
1615  return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1616  }
1617 
1623  function ilTempnam()
1624  {
1625  $temp_path = ilUtil::getDataDir() . "/temp";
1626  if (!is_dir($temp_path))
1627  {
1628  ilUtil::createDirectory($temp_path);
1629  }
1630  $temp_name = tempnam($temp_path, "tmp");
1631  // --->
1632  // added the following line because tempnam creates a backslash on some
1633  // Windows systems which leads to problems, because the "...\tmp..." can be
1634  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1635  // even under windows (Helmut Schottmüller, 2005-08-31)
1636  $temp_name = str_replace("\\", "/", $temp_name);
1637  // --->
1638  unlink($temp_name);
1639  return $temp_name;
1640  }
1641 
1647  function createDirectory($a_dir, $a_mod = 0755)
1648  {
1649  ilUtil::makeDir($a_dir);
1650  //@mkdir($a_dir);
1651  //@chmod($a_dir, $a_mod);
1652  }
1653 
1654 
1661  public static function unzip($a_file, $overwrite = false, $a_flat = false)
1662  {
1663  if (!is_file($a_file))
1664  {
1665  return;
1666  }
1667 
1668  // if flat, move file to temp directory first
1669  if ($a_flat)
1670  {
1671  $tmpdir = ilUtil::ilTempnam();
1672  ilUtil::makeDir($tmpdir);
1673  copy($a_file, $tmpdir.DIRECTORY_SEPARATOR.basename($a_file));
1674  $orig_file = $a_file;
1675  $a_file = $tmpdir.DIRECTORY_SEPARATOR.basename($a_file);
1676  $origpathinfo = pathinfo($orig_file);
1677  }
1678 
1679  $pathinfo = pathinfo($a_file);
1680  $dir = $pathinfo["dirname"];
1681  $file = $pathinfo["basename"];
1682 
1683  // unzip
1684  $cdir = getcwd();
1685  chdir($dir);
1686  $unzip = PATH_TO_UNZIP;
1687 
1688  // workaround for unzip problem (unzip of subdirectories fails, so
1689  // we create the subdirectories ourselves first)
1690  // get list
1691  $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1692  $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1693  $zdirs = array();
1694 
1695  foreach($arr as $line)
1696  {
1697  if(is_int(strpos($line, "/")))
1698  {
1699  $zdir = substr($line, 0, strrpos($line, "/"));
1700  $nr = substr_count($zdir, "/");
1701  //echo $zdir." ".$nr."<br>";
1702  while ($zdir != "")
1703  {
1704  $nr = substr_count($zdir, "/");
1705  $zdirs[$zdir] = $nr; // collect directories
1706  //echo $dir." ".$nr."<br>";
1707  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1708  }
1709  }
1710  }
1711 
1712  asort($zdirs);
1713 
1714  foreach($zdirs as $zdir => $nr) // create directories
1715  {
1716  ilUtil::createDirectory($zdir);
1717  }
1718 
1719  // real unzip
1720  if (!$overwrite)
1721  {
1722  $unzipcmd = ilUtil::escapeShellArg($file);
1723  }
1724  else
1725  {
1726  $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1727  }
1728  ilUtil::execQuoted($unzip, $unzipcmd);
1729 
1730  chdir($cdir);
1731 
1732  // if flat, get all files and move them to original directory
1733  if ($a_flat)
1734  {
1735  include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1736  $filearray = array();
1737  ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1738  if (is_array($filearray["file"]))
1739  {
1740  foreach ($filearray["file"] as $k => $f)
1741  {
1742  if (substr($f, 0, 1) != "." && $f != basename($orig_file))
1743  {
1744  copy($filearray["path"][$k].$f, $origpathinfo["dirname"].DIRECTORY_SEPARATOR.$f);
1745  }
1746  }
1747  }
1748  ilUtil::delDir($tmpdir);
1749  }
1750  }
1751 
1755  public static function zip($a_dir, $a_file, $compress_content = false)
1756  {
1757  $cdir = getcwd();
1758 
1759  if($compress_content)
1760  {
1761  $a_dir .="/*";
1762  $pathinfo = pathinfo($a_dir);
1763  chdir($pathinfo["dirname"]);
1764  }
1765 
1766  $pathinfo = pathinfo($a_file);
1767  $dir = $pathinfo["dirname"];
1768  $file = $pathinfo["basename"];
1769 
1770  if(!$compress_content)
1771  {
1772  chdir($dir);
1773  }
1774 
1775  $zip = PATH_TO_ZIP;
1776 
1777  if(!$zip)
1778  {
1779  chdir($cdir);
1780  return false;
1781  }
1782 
1783  if (is_array($a_dir))
1784  {
1785  $source = "";
1786  foreach($a_dir as $dir)
1787  {
1788  $name = basename($dir);
1789  $source.= " ".ilUtil::escapeShellArg($name);
1790  }
1791  }
1792  else
1793  {
1794  $name = basename($a_dir);
1795  if (trim($name) != "*")
1796  {
1797  $source = ilUtil::escapeShellArg($name);
1798  }
1799  else
1800  {
1801  $source = $name;
1802  }
1803  }
1804 
1805  $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1806  ilUtil::execQuoted($zip, $zipcmd);
1807  chdir($cdir);
1808  return true;
1809  }
1810 
1811  function CreateIsoFromFolder($a_dir, $a_file)
1812  {
1813  $cdir = getcwd();
1814 
1815  $pathinfo = pathinfo($a_dir);
1816  chdir($pathinfo["dirname"]);
1817 
1818  $pathinfo = pathinfo($a_file);
1819  $dir = $pathinfo["dirname"];
1820  $file = $pathinfo["basename"]; $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1821 
1822  $mkisofs = PATH_TO_MKISOFS;
1823  if(!$mkisofs)
1824  {
1825  chdir($cdir);
1826  return false;
1827  }
1828 
1829  $name = basename($a_dir);
1830  $source = ilUtil::escapeShellArg($name);
1831 
1832  $zipcmd = "-r -J -o ".$a_file." ".$source;
1833  ilUtil::execQuoted($mkisofs, $zipcmd);
1834  chdir($cdir);
1835  return true;
1836  }
1837 
1844  function getConvertCmd()
1845  {
1846  return PATH_TO_CONVERT;
1847  }
1848 
1854  public static function execConvert($args)
1855  {
1856  ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1857  }
1858 
1866  function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
1867  $a_background_color = "")
1868  {
1869  $format_str = ($a_target_format != "")
1870  ? strtoupper($a_target_format).":"
1871  : "";
1872  $geometry = ($a_geometry != "")
1873  ? " -geometry ".$a_geometry."x".$a_geometry." "
1874  : "";
1875  $bg_color = ($a_background_color != "")
1876  ? " -background color ".$a_background_color." "
1877  : "";
1878  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
1879 
1880  ilUtil::execConvert($convert_cmd);
1881  }
1882 
1891  function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
1892  {
1893  if ($a_constrain_prop)
1894  {
1895  $size = " -geometry ".$a_width."x".$a_height." ";
1896  }
1897  else
1898  {
1899  $size = " -resize ".$a_width."x".$a_height."! ";
1900  }
1901  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
1902 
1903  ilUtil::execConvert($convert_cmd);
1904  }
1905 
1909  function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0)
1910  {
1911  $img = '<img src="'.$a_src.'"';
1912  if ($a_alt != "")
1913  {
1914  $img.= ' alt="'.$a_alt.'" title="'.$a_alt.'"';
1915  }
1916  if ($a_width != "")
1917  {
1918  $img.= ' width="'.$a_width.'"';
1919  }
1920  if ($a_height != "")
1921  {
1922  $img.= ' height="'.$a_height.'"';
1923  }
1924  $img.= ' border="'.(int) $a_border.'"/>';
1925 
1926  return $img;
1927  }
1928 
1934  function html2pdf($html, $pdf_file)
1935  {
1936  $html_file = str_replace(".pdf",".html",$pdf_file);
1937 
1938  $fp = fopen( $html_file ,"wb");
1939  fwrite($fp, $html);
1940  fclose($fp);
1941 
1942  ilUtil::htmlfile2pdf($html_file,$pdf_file);
1943  }
1944 
1950  function htmlfile2pdf($html_file, $pdf_file)
1951  {
1952  $htmldoc_path = PATH_TO_HTMLDOC;
1953 
1954  $htmldoc = "--no-toc ";
1955  $htmldoc .= "--no-jpeg ";
1956  $htmldoc .= "--webpage ";
1957  $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
1958  $htmldoc .= "--bodyfont Arial ";
1959  $htmldoc .= "--charset iso-8859-15 ";
1960  $htmldoc .= "--color ";
1961  $htmldoc .= "--size A4 "; // --landscape
1962  $htmldoc .= "--format pdf ";
1963  $htmldoc .= "--footer ... ";
1964  $htmldoc .= "--header ... ";
1965  $htmldoc .= "--left 60 ";
1966  // $htmldoc .= "--right 200 ";
1967  $htmldoc .= $html_file;
1968  ilUtil::execQuoted($htmldoc_path, $htmldoc);
1969 
1970  }
1971 
1975  public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
1976  {
1977  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
1978  // $mime = "application/octet-stream"; // or whatever the mime type is
1979 
1980  if (isset($_SERVER["HTTPS"])) {
1981 
1982  // Added different handling for IE and HTTPS => send pragma after content informations
1986  #header("Pragma: ");
1987  #header("Cache-Control: ");
1988  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1989  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1990  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1991  #header("Cache-Control: post-check=0, pre-check=0", false);
1992  }
1993  else if ($disposition == "attachment")
1994  {
1995  header("Cache-control: private");
1996  }
1997  else
1998  {
1999  header("Cache-Control: no-cache, must-revalidate");
2000  header("Pragma: no-cache");
2001  }
2002 
2003  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2004 
2005  if (strlen($charset))
2006  {
2007  $charset = "; charset=$charset";
2008  }
2009  header("Content-Type: $mime$charset");
2010  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2011  header("Content-Description: ".$ascii_filename);
2012  header("Content-Length: ".(string)(strlen($a_data)));
2013 
2014  if($_SERVER['HTTPS'])
2015  {
2016  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2017  header('Pragma: public');
2018  }
2019 
2020  header("Connection: close");
2021  echo $a_data;
2022  exit;
2023  }
2024 
2025  // BEGIN WebDAV: Show file in browser or provide it as attachment
2031  function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false)
2032  {
2033  // should we fail silently?
2034  if(!file_exists($a_file))
2035  {
2036  return false;
2037  }
2038 
2039  if ($isInline) {
2040  $disposition = "inline"; // "inline" to view file in browser
2041  } else {
2042  $disposition = "attachment"; // "attachment" to download to hard disk
2043  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2044  }
2045  // END WebDAV: Show file in browser or provide it as attachment
2046 
2047  if(strlen($a_mime))
2048  {
2049  $mime = $a_mime;
2050  }
2051  else
2052  {
2053  $mime = "application/octet-stream"; // or whatever the mime type is
2054  }
2055  // BEGIN WebDAV: Removed broken HTTPS code.
2056  // END WebDAV: Removed broken HTTPS code.
2057  if ($disposition == "attachment")
2058  {
2059  header("Cache-control: private");
2060  }
2061  else
2062  {
2063  header("Cache-Control: no-cache, must-revalidate");
2064  header("Pragma: no-cache");
2065  }
2066 
2067  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2068 
2069  header("Content-Type: $mime");
2070  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2071  header("Content-Description: ".$ascii_filename);
2072 
2073  // #7271: if notice gets thrown download will fail in IE
2074  $filesize = @filesize($a_file);
2075  if ($filesize)
2076  {
2077  header("Content-Length: ".(string)$filesize);
2078  }
2079 
2080  include_once './classes/class.ilHTTPS.php';
2081  #if($_SERVER['HTTPS'])
2082  if(ilHTTPS::getInstance()->isDetected())
2083  {
2084  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2085  header('Pragma: public');
2086  }
2087 
2088  header("Connection: close");
2089  ilUtil::readFile( $a_file );
2090  if ($removeAfterDelivery)
2091  {
2092  unlink ($a_file);
2093  }
2094  exit;
2095  }
2096 
2097 
2104  function readFile($a_file)
2105  {
2106  $chunksize = 1*(1024*1024); // how many bytes per chunk
2107  $buffer = '';
2108  $handle = fopen($a_file, 'rb');
2109  if ($handle === false)
2110  {
2111  return false;
2112  }
2113  while (!feof($handle))
2114  {
2115  $buffer = fread($handle, $chunksize);
2116  print $buffer;
2117  }
2118  return fclose($handle);
2119  }
2120 
2126  function getASCIIFilename($a_filename)
2127  {
2128  // The filename must be converted to ASCII, as of RFC 2183,
2129  // section 2.3.
2130  // Despite the RFC, Internet Explorer on Windows supports
2131  // ISO 8895-1 encoding for the file name. We use this fact, to
2132  // produce a better result, if the user uses IE.
2133 
2145 
2146  $user_agent = strtolower($_SERVER["HTTP_USER_AGENT"]);
2147  if ((is_integer(strpos($user_agent, "msie"))) && is_integer(strpos($user_agent, "win")))
2148  {
2151 
2152  $ascii_filename = utf8_decode($a_filename);
2153  }
2154  else
2155  {
2158 
2159  $ascii_filename = htmlentities($a_filename,ENT_NOQUOTES,'UTF-8');
2160  $ascii_filename = preg_replace('/\&(.)[^;]*;/','\\1', $ascii_filename);
2161  $ascii_filename = preg_replace('/[\x7f-\xff]/','_', $ascii_filename);
2162  }
2163 
2164  // OS do not allow the following characters in filenames:
2165  // \/:*?"<>|
2166  //if (is_integer(strpos($user_agent, "win")))
2167  {
2168  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/','_', $ascii_filename);
2169  }
2170 
2171  return $ascii_filename;
2172  }
2173 
2174  /*
2175  * Encodes HTML entities outside of HTML tags
2176  */
2177  function htmlentitiesOutsideHTMLTags($htmlText)
2178  {
2179  $matches = Array();
2180  $sep = '###HTMLTAG###';
2181 
2182  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2183  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2184  $tmp = explode($sep, $tmp);
2185 
2186  for ($i=0; $i<count($tmp); $i++)
2187  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2188 
2189  $tmp = join($sep, $tmp);
2190 
2191  for ($i=0; $i<count($matches[0]); $i++)
2192  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2193 
2194  return $tmp;
2195  }
2196 
2200  function getJavaPath()
2201  {
2202  return PATH_TO_JAVA;
2203  //global $ilias;
2204 
2205  //return $ilias->getSetting("java_path");
2206  }
2207 
2212  function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2213  {
2214  $amp = $xml_style
2215  ? "&amp;"
2216  : "&";
2217 
2218  $url = (is_int(strpos($a_url, "?")))
2219  ? $a_url.$amp.$a_par
2220  : $a_url."?".$a_par;
2221 
2222  return $url;
2223  }
2224 
2239  function makeDir($a_dir)
2240  {
2241  $a_dir = trim($a_dir);
2242 
2243  // remove trailing slash (bugfix for php 4.2.x)
2244  if (substr($a_dir,-1) == "/")
2245  {
2246  $a_dir = substr($a_dir,0,-1);
2247  }
2248 
2249  // check if a_dir comes with a path
2250  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2251  {
2252  $path = ".";
2253  }
2254 
2255  // create directory with file permissions of parent directory
2256  umask(0000);
2257  return @mkdir($a_dir,fileperms($path));
2258  }
2259 
2260 
2273  public static function makeDirParents($a_dir)
2274  {
2275  $dirs = array($a_dir);
2276  $a_dir = dirname($a_dir);
2277  $last_dirname = '';
2278 
2279  while($last_dirname != $a_dir)
2280  {
2281  array_unshift($dirs, $a_dir);
2282  $last_dirname = $a_dir;
2283  $a_dir = dirname($a_dir);
2284  }
2285 
2286  // find the first existing dir
2287  $reverse_paths = array_reverse($dirs, TRUE);
2288  $found_index = -1;
2289  foreach ($reverse_paths as $key => $value)
2290  {
2291  if ($found_index == -1)
2292  {
2293  if (is_dir($value))
2294  {
2295  $found_index = $key;
2296  }
2297  }
2298  }
2299 
2300  umask(0000);
2301  foreach ($dirs as $dirindex => $dir)
2302  {
2303  // starting with the longest existing path
2304  if ($dirindex >= $found_index)
2305  {
2306  if (! file_exists($dir))
2307  {
2308  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2309  {
2310  // on some systems there is an error when there is a slash
2311  // at the end of a directory in mkdir, see Mantis #2554
2312  $dir = substr($dir,0,strlen($dir)-1);
2313  }
2314  if (! mkdir($dir, $umask))
2315  {
2316  error_log("Can't make directory: $dir");
2317  return false;
2318  }
2319  }
2320  elseif (! is_dir($dir))
2321  {
2322  error_log("$dir is not a directory");
2323  return false;
2324  }
2325  else
2326  {
2327  // get umask of the last existing parent directory
2328  $umask = fileperms($dir);
2329  }
2330  }
2331  }
2332  return true;
2333  }
2334 
2342  public static function delDir($a_dir, $a_clean_only = false)
2343  {
2344  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2345  {
2346  return;
2347  }
2348 
2349  $current_dir = opendir($a_dir);
2350 
2351  $files = array();
2352 
2353  // this extra loop has been necessary because of a strange bug
2354  // at least on MacOS X. A looped readdir() didn't work
2355  // correctly with larger directories
2356  // when an unlink happened inside the loop. Getting all files
2357  // into the memory first solved the problem.
2358  while($entryname = readdir($current_dir))
2359  {
2360  $files[] = $entryname;
2361  }
2362 
2363  foreach($files as $file)
2364  {
2365  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2366  {
2367  ilUtil::delDir(${a_dir}."/".${file});
2368  }
2369  elseif ($file != "." and $file != "..")
2370  {
2371  unlink(${a_dir}."/".${file});
2372  }
2373  }
2374 
2375  closedir($current_dir);
2376  if (!$a_clean_only)
2377  {
2378  @rmdir(${a_dir});
2379  }
2380  }
2381 
2382 
2386  function getDir($a_dir)
2387  {
2388  $current_dir = opendir($a_dir);
2389 
2390  $dirs = array();
2391  $files = array();
2392  while($entry = readdir($current_dir))
2393  {
2394  if(is_dir($a_dir."/".$entry))
2395  {
2396  $dirs[$entry] = array("type" => "dir", "entry" => $entry);
2397  }
2398  else
2399  {
2400  if ($entry != "." && $entry != "..")
2401  {
2402  $size = filesize($a_dir."/".$entry);
2403  $files[$entry] = array("type" => "file", "entry" => $entry,
2404  "size" => $size);
2405  }
2406  }
2407  }
2408  ksort($dirs);
2409  ksort($files);
2410 
2411  return array_merge($dirs, $files);
2412  }
2413 
2417  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2418  {
2419  if (is_array($a_arr))
2420  {
2421  foreach ($a_arr as $k => $v)
2422  {
2423  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2424  }
2425  }
2426 
2427  return $a_arr;
2428  }
2429 
2433  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2434  {
2435  if (is_array($a_data))
2436  {
2437  foreach ($a_data as $k => $v)
2438  {
2439  if (is_array($v))
2440  {
2441  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2442  }
2443  else
2444  {
2445  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2446  }
2447  }
2448  }
2449  else
2450  {
2451  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2452  }
2453 
2454  return $a_data;
2455  }
2456 
2462  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2463  {
2464  if (ini_get("magic_quotes_gpc"))
2465  {
2466  $a_str = stripslashes($a_str);
2467  }
2468 
2469  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2470  }
2471 
2477  function stripOnlySlashes($a_str)
2478  {
2479  if (ini_get("magic_quotes_gpc"))
2480  {
2481  $a_str = stripslashes($a_str);
2482  }
2483 
2484  return $a_str;
2485  }
2486 
2490  function secureString($a_str, $a_strip_html = true, $a_allow = "")
2491  {
2492  // check whether all allowed tags can be made secure
2493  $only_secure = true;
2494  $allow_tags = explode(">", $a_allow);
2495  $sec_tags = ilUtil::getSecureTags();
2496  $allow_array = array();
2497  foreach($allow_tags as $allow)
2498  {
2499  if ($allow != "")
2500  {
2501  $allow = str_replace("<", "", $allow);
2502 
2503  if (!in_array($allow, $sec_tags))
2504  {
2505  $only_secure = false;
2506  }
2507  $allow_array[] = $allow;
2508  }
2509  }
2510 
2511  // default behaviour: allow only secure tags 1:1
2512  if (($only_secure || $a_allow == "") && $a_strip_html)
2513  {
2514  if ($a_allow == "")
2515  {
2516  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2517  "gap", "sub", "sup", "pre", "strike");
2518  }
2519 
2520  // this currently removes parts of strings like "a <= b"
2521  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2522  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2523  $a_str = strip_tags($a_str); // strip all other tags
2524  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2525 
2526  // a possible solution could be something like:
2527  // $a_str = str_replace("<", "&lt;", $a_str);
2528  // $a_str = str_replace(">", "&gt;", $a_str);
2529  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2530  //
2531  // output would be ok then, but input fields would show
2532  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2533  }
2534  else
2535  {
2536  // only for scripts, that need to allow more/other tags and parameters
2537  if ($a_strip_html)
2538  {
2539  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2540  }
2541  }
2542 
2543  return $a_str;
2544  }
2545 
2546  function getSecureTags()
2547  {
2548  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2549  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2550  }
2551 
2552  function maskSecureTags($a_str, $allow_array)
2553  {
2554  foreach ($allow_array as $t)
2555  {
2556  switch($t)
2557  {
2558  case "a":
2559  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2560  break;
2561 
2562  case "img":
2563  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2564  break;
2565 
2566  case "p":
2567  case "div":
2568  $a_str = ilUtil::maskTag($a_str, $t, array(
2569  array("param" => "align", "value" => "left"),
2570  array("param" => "align", "value" => "center"),
2571  array("param" => "align", "value" => "justify"),
2572  array("param" => "align", "value" => "right")
2573  ));
2574  break;
2575 
2576  default:
2577  $a_str = ilUtil::maskTag($a_str, $t);
2578  break;
2579  }
2580  }
2581 
2582  return $a_str;
2583  }
2584 
2585  function unmaskSecureTags($a_str, $allow_array)
2586  {
2587  foreach ($allow_array as $t)
2588  {
2589  switch($t)
2590  {
2591  case "a":
2592  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2593  break;
2594 
2595  case "img":
2596  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2597  break;
2598 
2599  case "p":
2600  case "div":
2601  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2602  array("param" => "align", "value" => "left"),
2603  array("param" => "align", "value" => "center"),
2604  array("param" => "align", "value" => "justify"),
2605  array("param" => "align", "value" => "right")
2606  ));
2607  break;
2608 
2609  default:
2610  $a_str = ilUtil::unmaskTag($a_str, $t);
2611  break;
2612  }
2613  }
2614 
2615  return $a_str;
2616  }
2617 
2622  function securePlainString($a_str)
2623  {
2624  if (ini_get("magic_quotes_gpc"))
2625  {
2626  return stripslashes($a_str);
2627  }
2628  else
2629  {
2630  return $a_str;
2631  }
2632  }
2647  function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2648  {
2649  $encoded = "";
2650 
2651  if ($a_make_links_clickable)
2652  {
2653  // Find text sequences in the plain text string which match
2654  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2655  // Encode all other text sequences in the plain text string using
2656  // htmlspecialchars and nl2br.
2657  // The following expressions matches URI's as specified in RFC 2396.
2658  //
2659  // The expression matches URI's, which start with some well known
2660  // schemes, like "http:", or with "www.". This must be followed
2661  // by at least one of the following RFC 2396 expressions:
2662  // - alphanum: [a-zA-Z0-9]
2663  // - reserved: [;\/?:|&=+$,]
2664  // - mark: [\\-_.!~*\'()]
2665  // - escaped: %[0-9a-fA-F]{2}
2666  // - fragment delimiter: #
2667  // - uric_no_slash: [;?:@&=+$,]
2668  $matches = array();
2669  $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);
2670  $pos1 = 0;
2671  $encoded = "";
2672  foreach ($matches as $match)
2673  {
2674  }
2675  foreach ($matches[0] as $match)
2676  {
2677  $matched_text = $match[0];
2678  $pos2 = $match[1];
2679  if ($matched_offset != previous_offset)
2680  {
2681  // encode plain text
2682  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2683  }
2684  // encode URI
2685  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2686 
2687 
2688  $pos1 = $pos2 + strlen($matched_text);
2689  }
2690  if ($pos1 < strlen($a_str))
2691  {
2692  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2693  }
2694  }
2695  else
2696  {
2697  $encoded = nl2br(htmlspecialchars($a_str));
2698  }
2699  return $encoded;
2700  }
2701 
2702 
2703  function maskAttributeTag($a_str, $tag, $tag_att)
2704  {
2705  global $ilLog;
2706 
2707  $ws = "[ \t\r\f\v\n]*";
2708  $att = $ws."[^>]*".$ws;
2709 
2710  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2711  $a_str, $found))
2712  {
2713  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2714  $esc = array();
2715  foreach($un as $v)
2716  {
2717  $esc[] = "\\".$v;
2718  }
2719  $ff = str_replace($un, $esc, $found[1]);
2720 
2721  $old_str = $a_str;
2722  $a_str = eregi_replace("<".$ff.">",
2723  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2724  if ($old_str == $a_str)
2725  {
2726  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2727  htmlentities($a_str));
2728  return $a_str;
2729  }
2730  }
2731  $a_str = str_ireplace("</$tag>",
2732  "&lt;/$tag&gt;", $a_str);
2733  return $a_str;
2734  }
2735 
2736  function unmaskAttributeTag($a_str, $tag, $tag_att)
2737  {
2738  global $ilLog;
2739 
2740  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2741  $a_str, $found))
2742  {
2743  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2744  $esc = array();
2745  foreach($un as $v)
2746  {
2747  $esc[] = "\\".$v;
2748  }
2749  $ff = str_replace($un, $esc, $found[1]);
2750 
2751  $old_str = $a_str;
2752  $a_str = eregi_replace("&lt;".$ff."&gt;",
2753  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2754  if ($old_str == $a_str)
2755  {
2756  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2757  htmlentities($a_str));
2758  return $a_str;
2759  }
2760  }
2761  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2762  return $a_str;
2763  }
2764 
2765  function maskTag($a_str, $t, $fix_param = "")
2766  {
2767  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2768  "&lt;".$t."&gt;", $a_str);
2769  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2770  "&lt;/".$t."&gt;", $a_str);
2771 
2772  if (is_array($fix_param))
2773  {
2774  foreach ($fix_param as $p)
2775  {
2776  $k = $p["param"];
2777  $v = $p["value"];
2778  $a_str = str_replace("<$t $k=\"$v\">",
2779  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2780  }
2781  }
2782 
2783  return $a_str;
2784  }
2785 
2786  function unmaskTag($a_str, $t, $fix_param = "")
2787  {
2788  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2789  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2790 
2791  if (is_array($fix_param))
2792  {
2793  foreach ($fix_param as $p)
2794  {
2795  $k = $p["param"];
2796  $v = $p["value"];
2797  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2798  "<"."$t $k=\"$v\"".">", $a_str);
2799  }
2800  }
2801  return $a_str;
2802  }
2803 
2804  function secureLink($a_str)
2805  {
2806  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2807  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2808  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2809  return $a_str;
2810  }
2811 
2823  function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2824  {
2825  //$a_str = strip_tags($a_str, $a_allow);
2826 
2827  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
2828  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
2829  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
2830  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
2831  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
2832  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
2833  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
2834  "title,tr,tt,u,ul,var";
2835  $a_allow = strtolower ($a_allow);
2836  $negatives = explode(",",$negativestr);
2837  $outer_old_str = "";
2838  while($outer_old_str != $a_str)
2839  {
2840  $outer_old_str = $a_str;
2841  foreach ($negatives as $item)
2842  {
2843  $pos = strpos($a_allow, "<$item>");
2844 
2845  // remove complete tag, if not allowed
2846  if ($pos === false)
2847  {
2848  $old_str = "";
2849  while($old_str != $a_str)
2850  {
2851  $old_str = $a_str;
2852  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2853  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2854  }
2855  }
2856  }
2857  }
2858 
2859  if ($a_rm_js)
2860  {
2861  // remove all attributes if an "on..." attribute is given
2862  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2863 
2864  // remove all attributes if a "javascript" is within tag
2865  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2866 
2867  // remove all attributes if an "expression" is within tag
2868  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2869  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2870  }
2871 
2872  return $a_str;
2873  }
2874 
2875 
2881  function addSlashes($a_str)
2882  {
2883  if (ini_get("magic_quotes_gpc"))
2884  {
2885  return $a_str;
2886  }
2887  else
2888  {
2889  return addslashes($a_str);
2890  }
2891  }
2892 
2902  function prepareFormOutput($a_str, $a_strip = false)
2903  {
2904  if($a_strip)
2905  {
2906  $a_str = ilUtil::stripSlashes($a_str);
2907  }
2908  $a_str = htmlspecialchars($a_str);
2909  // Added replacement of curly brackets to prevent
2910  // problems with PEAR templates, because {xyz} will
2911  // be removed as unused template variable
2912  $a_str = str_replace("{", "&#123;", $a_str);
2913  $a_str = str_replace("}", "&#125;", $a_str);
2914  // needed for LaTeX conversion \\ in LaTeX is a line break
2915  // but without this replacement, php changes \\ to \
2916  $a_str = str_replace("\\", "&#92;", $a_str);
2917  return $a_str;
2918  }
2919 
2920 
2928  function prepareDBString($a_str)
2929  {
2930  return addslashes($a_str);
2931  }
2932 
2933 
2940  function removeItemFromDesktops($a_id)
2941  {
2942  return ilObjUser::_removeItemFromDesktops($a_id);
2943  }
2944 
2945 
2953  function extractParameterString($a_parstr)
2954  {
2955  // parse parameters in array
2956  $par = array();
2957  $ok=true;
2958  while(($spos=strpos($a_parstr,"=")) && $ok)
2959  {
2960  // extract parameter
2961  $cpar = substr($a_parstr,0,$spos);
2962  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
2963  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
2964  $cpar = substr($cpar,1,strlen($cpar)-1);
2965  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
2966  $cpar = substr($cpar,0,strlen($cpar)-1);
2967 
2968  // parameter name should only
2969  $cpar_old = "";
2970  while($cpar != $cpar_old)
2971  {
2972  $cpar_old = $cpar;
2973  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
2974  }
2975 
2976  // extract value
2977  if ($cpar != "")
2978  {
2979  if($spos=strpos($a_parstr,"\""))
2980  {
2981  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
2982  $spos=strpos($a_parstr,"\"");
2983  if(is_int($spos))
2984  {
2985  $cval = substr($a_parstr,0,$spos);
2986  $par[$cpar]=$cval;
2987  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
2988  }
2989  else
2990  $ok=false;
2991  }
2992  else
2993  $ok=false;
2994  }
2995  }
2996 
2997  if($ok) return $par; else return false;
2998  }
2999 
3000  function assembleParameterString($a_par_arr)
3001  {
3002  if (is_array($a_par_arr))
3003  {
3004  $target_arr = array();
3005  foreach ($a_par_arr as $par => $val)
3006  {
3007  $target_arr[] = "$par=\"$val\"";
3008  }
3009  $target_str = implode(", ", $target_arr);
3010  }
3011 
3012  return $target_str;
3013  }
3014 
3018  function dumpString($a_str)
3019  {
3020  $ret = $a_str.": ";
3021  for($i=0; $i<strlen($a_str); $i++)
3022  {
3023  $ret.= ord(substr($a_str,$i,1))." ";
3024  }
3025  return $ret;
3026  }
3027 
3028 
3032  function yn2tf($a_yn)
3033  {
3034  if(strtolower($a_yn) == "y")
3035  {
3036  return true;
3037  }
3038  else
3039  {
3040  return false;
3041  }
3042  }
3043 
3047  function tf2yn($a_tf)
3048  {
3049  if($a_tf)
3050  {
3051  return "y";
3052  }
3053  else
3054  {
3055  return "n";
3056  }
3057  }
3058 
3067  function sort_func ($a, $b)
3068  {
3069  global $array_sortby,$array_sortorder;
3070 
3071  // this comparison should give optimal results if
3072  // locale is provided and mb string functions are supported
3073  if ($array_sortorder == "asc")
3074  {
3075  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3076  }
3077 
3078  if ($array_sortorder == "desc")
3079  {
3080  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3081  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3082  }
3083  }
3084 
3093  function sort_func_numeric ($a, $b)
3094  {
3095  global $array_sortby,$array_sortorder;
3096 
3097  if ($array_sortorder == "asc")
3098  {
3099  return $a["$array_sortby"] > $b["$array_sortby"];
3100  }
3101 
3102  if ($array_sortorder == "desc")
3103  {
3104  return $a["$array_sortby"] < $b["$array_sortby"];
3105  }
3106  }
3117  public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3118  $a_keep_keys = false)
3119  {
3120  include_once("./Services/Utilities/classes/class.ilStr.php");
3121 
3122  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3123  if (! $a_keep_keys) {
3124  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3125  }
3126  // END WebDAV Provide a 'stable' sort algorithm
3127 
3128  global $array_sortby,$array_sortorder;
3129 
3130  $array_sortby = $a_array_sortby;
3131 
3132  if ($a_array_sortorder == "desc")
3133  {
3134  $array_sortorder = "desc";
3135  }
3136  else
3137  {
3138  $array_sortorder = "asc";
3139  }
3140  if($a_numeric)
3141  {
3142  if ($a_keep_keys)
3143  {
3144  uasort($array, array("ilUtil", "sort_func_numeric"));
3145  }
3146  else
3147  {
3148  usort($array, array("ilUtil", "sort_func_numeric"));
3149  }
3150  }
3151  else
3152  {
3153  if ($a_keep_keys)
3154  {
3155  uasort($array, array("ilUtil", "sort_func"));
3156  }
3157  else
3158  {
3159  usort($array, array("ilUtil", "sort_func"));
3160  }
3161  }
3162  //usort($array,"ilUtil::sort_func");
3163 
3164  return $array;
3165  }
3166  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3179  function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3180  {
3181  global $array_sortby,$array_sortorder;
3182 
3183  $array_sortby = $a_array_sortby;
3184 
3185  if ($a_array_sortorder == "desc")
3186  {
3187  $array_sortorder = "desc";
3188  }
3189  else
3190  {
3191  $array_sortorder = "asc";
3192  }
3193 
3194  // Create a copy of the array values for sorting
3195  $sort_array = array_values($array);
3196 
3197  if($a_numeric)
3198  {
3199  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3200  }
3201  else
3202  {
3203  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3204  }
3205 
3206  return $sort_array;
3207  }
3208  function mergesort(&$array, $cmp_function = 'strcmp') {
3209  // Arrays of size < 2 require no action.
3210  if (count($array) < 2) return;
3211 
3212  // Split the array in half
3213  $halfway = count($array) / 2;
3214  $array1 = array_slice($array, 0, $halfway);
3215  $array2 = array_slice($array, $halfway);
3216 
3217  // Recurse to sort the two halves
3218  ilUtil::mergesort($array1, $cmp_function);
3219  ilUtil::mergesort($array2, $cmp_function);
3220 
3221  // If all of $array1 is <= all of $array2, just append them.
3222  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3223  $array = array_merge($array1, $array2);
3224  return;
3225  }
3226 
3227  // Merge the two sorted arrays into a single sorted array
3228  $array = array();
3229  $ptr1 = $ptr2 = 0;
3230  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3231  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3232  $array[] = $array1[$ptr1++];
3233  }
3234  else {
3235  $array[] = $array2[$ptr2++];
3236  }
3237  }
3238 
3239  // Merge the remainder
3240  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3241  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3242 
3243  return;
3244  }
3245  // END WebDAV: Provide a 'stable' sort algorithm
3246 
3256  function unique_multi_array($array, $sub_key)
3257  {
3258  $target = array();
3259  $existing_sub_key_values = array();
3260 
3261  foreach ($array as $key=>$sub_array)
3262  {
3263  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3264  {
3265  $existing_sub_key_values[] = $sub_array[$sub_key];
3266  $target[$key] = $sub_array;
3267  }
3268  }
3269 
3270  return $target;
3271  }
3272 
3273 
3281  function getGDSupportedImageType($a_desired_type)
3282  {
3283  $a_desired_type = strtolower($a_desired_type);
3284  // get supported Image Types
3285  $im_types = ImageTypes();
3286 
3287  switch($a_desired_type)
3288  {
3289  case "jpg":
3290  if ($im_types & IMG_JPG) return "jpg";
3291  if ($im_types & IMG_GIF) return "gif";
3292  if ($im_types & IMG_PNG) return "png";
3293  break;
3294 
3295  case "gif":
3296  if ($im_types & IMG_GIF) return "gif";
3297  if ($im_types & IMG_JPG) return "jpg";
3298  if ($im_types & IMG_PNG) return "png";
3299  break;
3300 
3301  case "png":
3302  if ($im_types & IMG_PNG) return "png";
3303  if ($im_types & IMG_JPG) return "jpg";
3304  if ($im_types & IMG_GIF) return "gif";
3305  break;
3306  }
3307 
3308  return "";
3309  }
3310 
3318  function deducibleSize($a_mime)
3319  {
3320  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3321  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3322  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3323  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3324  {
3325  return true;
3326  }
3327  else
3328  {
3329  return false;
3330  }
3331  }
3332 
3333 
3339  function redirect($a_script)
3340  {
3341  global $log, $PHP_SELF;
3342 
3343 //echo "<br>".$a_script;
3344  if (!is_int(strpos($a_script, "://")))
3345  {
3346  if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3347  {
3348  if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3349  {
3350  $a_script = "setup/".$a_script;
3351  }
3352  $a_script = ILIAS_HTTP_PATH."/".$a_script;
3353  }
3354  }
3355 //echo "<br>".$a_script; exit;
3356  header("Location: ".$a_script);
3357  exit();
3358  }
3359 
3365  function insertInstIntoID($a_value)
3366  {
3367  if (substr($a_value, 0, 4) == "il__")
3368  {
3369  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3370  }
3371 
3372  return $a_value;
3373  }
3374 
3383  function groupNameExists($a_group_name,$a_id = 0)
3384  {
3385  global $ilDB,$ilErr;
3386 
3387  if (empty($a_group_name))
3388  {
3389  $message = get_class($this)."::_NameExists(): No groupname given!";
3390  $ilErr->raiseError($message,$ilErr->WARNING);
3391  }
3392 
3393  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3394 
3395  $q = "SELECT obj_id FROM object_data ".
3396  "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3397  "AND type = ".$ilDB->quote("grp", "text").
3398  $clause;
3399 
3400  $r = $ilDB->query($q);
3401 
3402  if ($r->numRows())
3403  {
3404  return true;
3405  }
3406  else
3407  {
3408  return false;
3409  }
3410  }
3411 
3412  /*
3413  * get the user_ids which correspond a search string
3414  * static function
3415  * @param string search string
3416  * @access public
3417  */
3418  function searchGroups($a_search_str)
3419  {
3420  global $ilDB;
3421 
3422  $q = "SELECT * ".
3423  "FROM object_data ,object_reference ".
3424  "WHERE (".$ilDB->like("object_data.title", "text", "%".$a_search_str."%")." ".
3425  "OR ".$ilDB->like("object_data.description", "text", "%".$a_search_str."%").") ".
3426  "AND object_data.type = 'grp' ".
3427  "AND object_data.obj_id = object_reference.obj_id ".
3428  "ORDER BY title ";
3429 
3430  $res = $ilDB->query($q);
3431 
3432  while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3433  {
3434  // STORE DATA IN ARRAY WITH KEY obj_id
3435  // SO DUPLICATE ENTRIES ( LINKED OBJECTS ) ARE UNIQUE
3436  $ids[$row->obj_id] = array(
3437  "ref_id" => $row->ref_id,
3438  "title" => $row->title,
3439  "description" => $row->description);
3440  }
3441 
3442  return $ids ? $ids : array();
3443  }
3444 
3448  function getMemString()
3449  {
3450  $my_pid = getmypid();
3451  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3452  }
3453 
3457  function isWindows()
3458  {
3459  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3460  {
3461  return true;
3462  }
3463  return false;
3464  }
3465 
3466 
3467  function escapeShellArg($a_arg)
3468  {
3469  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3470  // see also ilias bug 5630
3471  return escapeshellarg($a_arg);
3472  }
3473 
3481  public function escapeShellCmd($a_arg)
3482  {
3483  if(ini_get('safe_mode') == 1)
3484  {
3485  return $a_arg;
3486  }
3487  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3488  return escapeshellcmd($a_arg);
3489  }
3490 
3498  public static function execQuoted($cmd, $args = NULL)
3499  {
3500  if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3501  {
3502  // cmd won't work without quotes
3503  $cmd = '"'.$cmd.'"';
3504  if($args)
3505  {
3506  // args are also quoted, workaround is to quote the whole command AGAIN
3507  // was fixed in php 5.2 (see php bug #25361)
3508  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3509  {
3510  $cmd = '"'.$cmd." ".$args.'"';
3511  }
3512  // args are not quoted or php is fixed, just append
3513  else
3514  {
3515  $cmd .= " ".$args;
3516  }
3517  }
3518  }
3519  // nothing todo, just append args
3520  else if($args)
3521  {
3522  $cmd .= " ".$args;
3523  }
3524  exec($cmd, $arr);
3525  return $arr;
3526  }
3527 
3528  /*
3529  * Calculates a Microsoft Excel date/time value
3530  *
3531  * Calculates a Microsoft Excel date/time value (nr of days after 1900/1/1 0:00) for
3532  * a given date and time. The function only accepts dates after 1970/1/1, because the
3533  * unix timestamp functions used in the function are starting with that date.
3534  * If you don't enter parameters the date/time value for the actual date/time
3535  * will be calculated.
3536  *
3537  * static function
3538  *
3539  * @param integer $year Year
3540  * @param integer $month Month
3541  * @param integer $day Day
3542  * @param integer $hour Hour
3543  * @param integer $minute Minute
3544  * @param integer $second Second
3545  * @return float The Microsoft Excel date/time value
3546  * @access public
3547  */
3548  function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3549  {
3550  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3551  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3552  {
3553  $target_time = time();
3554  }
3555  else
3556  {
3557  if ($year < 1970)
3558  {
3559  return 0;
3560  }
3561  }
3562  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3563  $difference = $target_time - $starting_time;
3564  $days = (($difference - ($difference % 86400)) / 86400);
3565  $difference = $difference - ($days * 86400) + 3600;
3566  return ($days + 25570 + ($difference / 86400));
3567  }
3568 
3572  function renameExecutables($a_dir)
3573  {
3574  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3575  foreach ($def_arr as $def)
3576  {
3577  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3578  }
3579 
3580  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3581  foreach ($def_arr as $def)
3582  {
3583  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3584  }
3585  }
3586 
3597  function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3598  {
3599  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3600  || trim($a_old_suffix) == "")
3601  {
3602  return false;
3603  }
3604 
3605  // check if argument is directory
3606  if (!@is_dir($a_dir))
3607  {
3608  return false;
3609  }
3610 
3611  // read a_dir
3612  $dir = opendir($a_dir);
3613 
3614  while($file = readdir($dir))
3615  {
3616  if ($file != "." and
3617  $file != "..")
3618  {
3619  // directories
3620  if (@is_dir($a_dir."/".$file))
3621  {
3622  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3623  }
3624 
3625  // files
3626  if (@is_file($a_dir."/".$file))
3627  {
3628  // first check for files with trailing dot
3629  if(strrpos($file,'.') == (strlen($file) - 1))
3630  {
3631  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3632  $file = substr($file,0,-1);
3633  }
3634 
3635  $path_info = pathinfo($a_dir."/".$file);
3636 
3637  if (strtolower($path_info["extension"]) ==
3638  strtolower($a_old_suffix))
3639  {
3640  $pos = strrpos($a_dir."/".$file, ".");
3641  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3642  rename($a_dir."/".$file, $new_name);
3643  }
3644  }
3645  }
3646  }
3647  return true;
3648  }
3649 
3650  function isAPICall () {
3651  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3652  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3653  }
3654 
3655  function KT_replaceParam($qstring, $paramName, $paramValue) {
3656  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3657  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3658  } else {
3659  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3660  }
3661  }
3662 
3663  function replaceUrlParameterString ($url, $parametersArray) {
3664 
3665  foreach ($parametersArray as $paramName => $paramValue ) {
3666  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3667  }
3668  return $url;
3669  }
3670 
3674  function generatePasswords ($a_number)
3675  {
3676  $ret = array();
3677  srand((double) microtime()*1000000);
3678 
3679  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3680  $security = ilSecuritySettings::_getInstance();
3681 
3682  for ($i=1; $i<=$a_number; $i++)
3683  {
3684  $min = ($security->getPasswordMinLength() > 0)
3685  ? $security->getPasswordMinLength()
3686  : 6;
3687  $max = ($security->getPasswordMaxLength() > 0)
3688  ? $security->getPasswordMaxLength()
3689  : 10;
3690  if ($min > $max)
3691  {
3692  $max = $max + 1;
3693  }
3694  $length = rand($min,$max);
3695  $next = rand(1,2);
3696  $vowels = "aeiou";
3697  $consonants = "bcdfghjklmnpqrstvwxyz";
3698  $numbers = "1234567890";
3699  $special = "_.+?#-*@!$%~";
3700  $pw = "";
3701 
3702  // position for number
3703  if ($security->isPasswordCharsAndNumbersEnabled())
3704  {
3705  $num_pos = rand(0, $length - 1);
3706  }
3707 
3708  // position for special character
3709  if ($security->isPasswordSpecialCharsEnabled())
3710  {
3711  $spec_pos = rand(0, $length - 1);
3712  if ($security->isPasswordCharsAndNumbersEnabled())
3713  {
3714  if ($num_pos == $spec_pos) // not same position for number/special
3715  {
3716  if ($spec_pos > 0)
3717  {
3718  $spec_pos -= 1;
3719  }
3720  else
3721  {
3722  $spec_pos += 1;
3723  }
3724  }
3725  }
3726  }
3727  for ($j=0; $j < $length; $j++)
3728  {
3729  if ($security->isPasswordCharsAndNumbersEnabled() && $num_pos == $j)
3730  {
3731  $pw.= $numbers[rand(0,strlen($numbers)-1)];
3732  }
3733  else if ($security->isPasswordSpecialCharsEnabled() && $spec_pos == $j)
3734  {
3735  $pw.= $special[rand(0,strlen($special)-1)];
3736  }
3737  else
3738  {
3739  switch ($next)
3740  {
3741  case 1:
3742  $pw.= $consonants[rand(0,strlen($consonants)-1)];
3743  $next = 2;
3744  break;
3745 
3746  case 2:
3747  $pw.= $vowels[rand(0,strlen($vowels)-1)];
3748  $next = 1;
3749  break;
3750  }
3751  }
3752  }
3753 
3754  $ret[] = $pw;
3755  }
3756  return $ret;
3757  }
3758 
3760  {
3761  $path = preg_replace("/[\/\\\]+$/", "", $path);
3762  return $path;
3763  }
3764 
3774  {
3775  if (empty($data))
3776  {
3777  $data = array();
3778  }
3779 
3780  foreach($data as $k=>$datum)
3781  {
3782  if(is_null($datum)) $data[$k] = 'null';
3783  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
3784  if(is_array($datum)) $data[$k] = array_php2js($datum);
3785  }
3786 
3787  return "[" . implode(', ', $data) . "]";
3788  }
3789 
3794  function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3795  {
3796  global $lng;
3797 
3798  if (IL_VIRUS_SCANNER != "None")
3799  {
3800  require_once("classes/class.ilVirusScannerFactory.php");
3802  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3803  {
3804  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
3805  {
3806  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3807  if ($vs->fileCleaned())
3808  {
3809  $vs_txt.= "<br />".$lng->txt("cleaned_file").
3810  "<br />".$clean_txt;
3811  $vs_txt.= "<br />".$lng->txt("repeat_scan");
3812  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3813  {
3814  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
3815  "<br />".nl2br($vs2_txt));
3816  }
3817  else
3818  {
3819  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
3820  }
3821  }
3822  else
3823  {
3824  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
3825  }
3826  }
3827  else
3828  {
3829  return array(false, nl2br($vs_txt));
3830  }
3831  }
3832  }
3833 
3834  return array(true,"");
3835  }
3836 
3837 
3841  function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true)
3842  {
3843  global $lng, $ilias;
3844 //echo "<br>ilUtli::moveuploadedFile($a_name)";
3845 
3846  if (!is_file($a_file))
3847  {
3848  if ($a_raise_errors)
3849  {
3850  $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
3851  }
3852  else
3853  {
3854  ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
3855  }
3856  return false;
3857  }
3858 
3859  // virus handling
3860  $vir = ilUtil::virusHandling($a_file, $a_name);
3861  if (!$vir[0])
3862  {
3863  unlink($a_file);
3864  if ($a_raise_errors)
3865  {
3866  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
3867  $vir[1],
3868  $ilias->error_obj->MESSAGE);
3869  }
3870  else
3871  {
3872  ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
3873  $vir[1], true);
3874  }
3875  return false;
3876  }
3877  else
3878  {
3879  if ($vir[1] != "")
3880  {
3881  ilUtil::sendInfo($vir[1], true);
3882  }
3883  return move_uploaded_file($a_file, $a_target);
3884  }
3885  }
3886 
3887 
3891  function date_mysql2time($mysql_date_time) {
3892  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
3893  list($jahr, $monat, $tag) = explode("-", $datum);
3894  list($std, $min, $sec) = explode(":", $uhrzeit);
3895  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3896  }
3897 
3901  function now()
3902  {
3903  return date("Y-m-d H:i:s");
3904  }
3905 
3919  function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
3920  {
3921  $resultarray = array();
3922  foreach ($row as $rowindex => $entry)
3923  {
3924  $surround = FALSE;
3925  if ($quoteAll)
3926  {
3927  $surround = TRUE;
3928  }
3929  if (strpos($entry, "\"") !== FALSE)
3930  {
3931  $entry = str_replace("\"", "\"\"", $entry);
3932  $surround = TRUE;
3933  }
3934  if (strpos($entry, $separator) !== FALSE)
3935  {
3936  $surround = TRUE;
3937  }
3938  if ($compatibleWithMSExcel)
3939  {
3940  // replace all CR LF with LF (for Excel for Windows compatibility
3941  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
3942  }
3943  if ($surround)
3944  {
3945  if ($outUTF8)
3946  {
3947  $resultarray[$rowindex] = "\"" . $entry . "\"";
3948  }
3949  else
3950  {
3951  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3952  }
3953  }
3954  else
3955  {
3956  if ($outUTF8)
3957  {
3958  $resultarray[$rowindex] = $entry;
3959  }
3960  else
3961  {
3962  $resultarray[$rowindex] = utf8_decode($entry);
3963  }
3964  }
3965  }
3966  return $resultarray;
3967  }
3968 
3969  // validates a domain name (example: www.ilias.de)
3970  function isDN($a_str)
3971  {
3972  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
3973  }
3974 
3975  // validates an IP address (example: 192.168.1.1)
3976  function isIPv4($a_str)
3977  {
3978  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])\.".
3979  "(\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));
3980  }
3981 
3982 
4009  function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
4010  {
4011  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
4012 
4013  if(!is_array($a_obj_type))
4014  {
4015  $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4016  }
4017  else
4018  {
4019  $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4020  }
4021 
4022  // limit number of results default is search result limit
4023  if(!$limit)
4024  {
4025  $limit = $ilias->getSetting('search_max_hits',100);
4026  }
4027  if($limit == -1)
4028  {
4029  $limit = 10000;
4030  }
4031 
4032  // default to logged in usr
4033  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4034  $a_roles = $rbacreview->assignedRoles($a_usr_id);
4035 
4036  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4037  // is assigned to the system role
4038  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4039  {
4040  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4041  "LEFT JOIN tree ON obr.ref_id = tree.child ".
4042  $where.
4043  "AND tree = 1";
4044 
4045  $res = $ilDB->query($query);
4046  $counter = 0;
4047  while($row = $ilDB->fetchObject($res))
4048  {
4049  // Filter recovery folder
4050  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4051  {
4052  continue;
4053  }
4054 
4055  if($counter++ >= $limit)
4056  {
4057  break;
4058  }
4059 
4060  $ref_ids[] = $row->ref_id;
4061  }
4062  return $ref_ids ? $ref_ids : array();
4063  } // End Administrators
4064 
4065  // Check ownership if it is not asked for edit_permission or a create permission
4066  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4067  {
4068  $check_owner = ") ";
4069  }
4070  else
4071  {
4072  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4073  }
4074 
4075  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4076  $ops_id = $ops_ids[0];
4077 
4078  $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4079 
4080  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4081  "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4082  "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4083  $where.
4084  $and.
4085  "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4086  "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4087  $check_owner;
4088 
4089  $res = $ilDB->query($query);
4090  $counter = 0;
4091  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4092  {
4093  if($counter >= $limit)
4094  {
4095  break;
4096  }
4097 
4098  // Filter objects in recovery folder
4099  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4100  {
4101  continue;
4102  }
4103 
4104  // Check deleted, hierarchical access ...
4105  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4106  {
4107  $counter++;
4108  $ref_ids[] = $row->ref_id;
4109  }
4110  }
4111  return $ref_ids ? $ref_ids : array();
4112  }
4113 
4120  function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4121  {
4122  global $tpl, $lng, $ilUser;
4123 
4124  // - take care of html exports (-> see buildLatexImages)
4125  include_once "./Services/Administration/classes/class.ilSetting.php";
4126  $jsMathSetting = new ilSetting("jsMath");
4127  $use_jsmath =
4128  $jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault"))));
4129 
4130  if ($use_jsmath)
4131  {
4132  $info = "";
4133  if (!$tpl->out_jsmath_info)
4134  {
4135  include_once "./classes/class.ilTemplate.php";
4136  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4137  $lng->loadLanguageModule("jsmath");
4138  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4139  $info = $template->get();
4140  $tpl->out_jsmath_info = TRUE;
4141  }
4142  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4143  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4144  }
4145 
4146  // this is a fix for bug5362
4147  $cpos = 0;
4148  $o_start = $a_start;
4149  $o_end = $a_end;
4150  $a_start = str_replace("\\", "", $a_start);
4151  $a_end = str_replace("\\", "", $a_end);
4152  /*$a_start = str_replace("\]", "]", $a_start);
4153  $a_start = str_replace("\[", "[", $a_start);
4154  $a_end = str_replace("\]", "]", $a_end);
4155  $a_end = str_replace("\[", "[", $a_end);
4156  $a_end = str_replace("\/", "/", $a_end);*/
4157 
4158  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4159  {
4160  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4161  {
4162  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4163 
4164  // replace, if tags do not go across div borders
4165  if (!is_int(strpos($tex, "</div>")))
4166  {
4167  if (!$use_jsmath)
4168  {
4169  $a_text = substr($a_text, 0, $spos).
4170  "<img alt=\"".htmlentities($tex)."\" src=\"".$a_cgi."?".
4171  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4172  " />".
4173  substr($a_text, $epos + strlen($a_end));
4174  }
4175  else
4176  {
4177  $tex = $a_start.$tex.$a_end;
4178 //echo "<br>1:".$tex;
4179  $replacement =
4180  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4181  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $tex);
4182  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4183 //echo "<br>2:".htmlentities($replacement);
4184  $a_text = substr($a_text, 0, $spos).
4185  $replacement.
4186  substr($a_text, $epos + strlen($a_end));
4187  }
4188  }
4189  }
4190  $cpos = $spos + 1;
4191  }
4192 
4193  if ($use_jsmath)
4194  {
4195  $a_text = str_replace("[[info]]", $info, $a_text);
4196  }
4197 
4198  $result_text = $a_text;
4199 
4200 // $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4201 // "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4202 // " />'", $a_text);
4203 
4204 //echo htmlentities($a_text);
4205 
4206  return $result_text;
4207  }
4208 
4215  function __insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4216  {
4217  global $tpl, $lng, $ilUser;
4218 
4219 //echo "<br><br>".htmlentities($a_text);
4220 //echo "<br>-".htmlentities($a_start)."-".htmlentities($a_end)."-";
4221 
4222  // - take care of html exports (-> see buildLatexImages)
4223  include_once "./Services/Administration/classes/class.ilSetting.php";
4224  $jsMathSetting = new ilSetting("jsMath");
4225  if ($jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault")))))
4226  {
4227  $info = "";
4228  if (!$tpl->out_jsmath_info)
4229  {
4230  include_once "./classes/class.ilTemplate.php";
4231  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4232  $lng->loadLanguageModule("jsmath");
4233  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4234  $info = $template->get();
4235  $tpl->out_jsmath_info = TRUE;
4236  }
4237  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4238  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4239  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $a_text);
4240  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4241  $result_text = str_replace("[[info]]", $info, $result_text);
4242  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4243  }
4244  else
4245  {
4246  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4247  "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4248  " />'", $a_text);
4249  }
4250 
4251  return $result_text;
4252  }
4253 
4260  function buildLatexImages($a_text, $a_dir ,$a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4261  {
4262  $result_text = $a_text;
4263 
4264  if ($a_cgi != "")
4265  {
4266  while (preg_match('/' . $a_start . '(.*?)' . $a_end . '/ie', $result_text, $found))
4267  {
4268  $cnt = (int) $GLOBALS["teximgcnt"]++;
4269  // get image from cgi and write it to file
4270  $fpr = @fopen($a_cgi."?".rawurlencode($found[1]), "r");
4271  $lcnt = 0;
4272  if ($fpr)
4273  {
4274  while(!feof($fpr))
4275  {
4276  $buf = fread($fpr, 1024);
4277  if ($lcnt == 0)
4278  {
4279  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4280  {
4281  $suffix = "gif";
4282  }
4283  else
4284  {
4285  $suffix = "png";
4286  }
4287  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4288  }
4289  $lcnt++;
4290  fwrite($fpw, $buf);
4291  }
4292  fclose($fpw);
4293  fclose($fpr);
4294  }
4295 
4296  // replace tex-tag
4297  $img_str = "./teximg/img".$cnt.".".$suffix;
4298  $result_text = str_replace($found[0],
4299  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4300  }
4301  }
4302 
4303  return $result_text;
4304  }
4305 
4313  function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE)
4314  {
4315  $result = $txt_output;
4316  $is_html = $this->isHTML($result);
4317  if ($prepare_for_latex_output)
4318  {
4319  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>", URL_TO_LATEX);
4320  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]", URL_TO_LATEX);
4321  }
4322 
4323  // removed: did not work with magic_quotes_gpc = On
4324  if (!$is_html)
4325  {
4326  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4327  $result = preg_replace("/[\n]/", "<br />", $result);
4328  }
4329  else
4330  {
4331  // patch for problems with the <pre> tags in tinyMCE
4332  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4333  {
4334  foreach ($matches[0] as $found)
4335  {
4336  $replacement = "";
4337  if (strpos("\n", $found) === FALSE)
4338  {
4339  $replacement = "\n";
4340  }
4341  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4342  $result = str_replace($found, $removed, $result);
4343  }
4344  }
4345  }
4346  if ($prepare_for_latex_output)
4347  {
4348  // replace special characters to prevent problems with the ILIAS template system
4349  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4350  $result = str_replace("{", "&#123;", $result);
4351  $result = str_replace("}", "&#125;", $result);
4352  $result = str_replace("\\", "&#92;", $result);
4353  }
4354  return $result;
4355  }
4356 
4357 
4364  function int2array ($seconds, $periods = null)
4365  {
4366  // Define time periods
4367  if (!is_array($periods))
4368  {
4369  $periods = array (
4370  'years' => 31536000,
4371  'months' => 2592000,
4372  'days' => 86400,
4373  'hours' => 3600,
4374  'minutes' => 60,
4375  'seconds' => 1
4376  );
4377  }
4378 
4379  // Loop
4380  $seconds = (float) $seconds;
4381  foreach ($periods as $period => $value)
4382  {
4383  $count = floor($seconds / $value);
4384 
4385  if ($count == 0)
4386  {
4387  continue;
4388  }
4389 
4390  $values[$period] = $count;
4391  $seconds = $seconds % $value;
4392  }
4393  // Return
4394  if (empty($values))
4395  {
4396  $values = null;
4397  }
4398 
4399  return $values;
4400  }
4401 
4408  function timearray2string ($duration)
4409  {
4410  global $lng;
4411 
4412  if (!is_array($duration))
4413  {
4414  return false;
4415  }
4416 
4417  foreach ($duration as $key => $value) {
4418 
4419  // Plural
4420  if ($value > 1)
4421  {
4422  $segment_name = $key;
4423  $segment_name = $lng->txt($segment_name);
4424  $segment = $value . ' ' . $segment_name;
4425  }
4426  else
4427  {
4428  $segment_name = substr($key, 0, -1);
4429  $segment_name = $lng->txt($segment_name);
4430  $segment = $value . ' ' . $segment_name;
4431  }
4432 
4433  $array[] = $segment;
4434  }
4435  $len = count($array);
4436 
4437  if ($len>3)
4438  {
4439  $array=array_slice($array,0,(3-$len));
4440  }
4441 
4442  $str = implode(', ', $array);
4443 
4444  return $str;
4445  }
4446 
4447  function getFileSizeInfo()
4448  {
4449  global $lng;
4450 
4451  // get the value for the maximal uploadable filesize from the php.ini (if available)
4452  $umf=get_cfg_var("upload_max_filesize");
4453  // get the value for the maximal post data from the php.ini (if available)
4454  $pms=get_cfg_var("post_max_size");
4455 
4456  // use the smaller one as limit
4457  $max_filesize=min($umf, $pms);
4458  if (!$max_filesize) $max_filesize=max($umf, $pms);
4459 
4460  return $lng->txt("file_notice")." $max_filesize.";
4461  }
4462 
4469  function __extractRefId($role_title)
4470  {
4471 
4472  $test_str = explode('_',$role_title);
4473 
4474  if ($test_str[0] == 'il')
4475  {
4476  $test2 = (int) $test_str[3];
4477  return is_numeric ($test2) ? (int) $test2 : false;
4478  }
4479  return false;
4480  }
4481 
4491  function __extractId($ilias_id, $inst_id)
4492  {
4493 
4494  $test_str = explode('_',$ilias_id);
4495 
4496  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4497  {
4498  $test2 = (int) $test_str[3];
4499  return is_numeric ($test2) ? (int) $test2 : false;
4500  }
4501  return false;
4502  }
4503 
4516  function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4517  {
4518  global $ilDB;
4519 
4520  if(!$a_ids)
4521  {
4522  return array();
4523  }
4524 
4525  // use database to sort user array
4526  $where = "WHERE ".$a_id_name." IN (";
4527  $where .= implode(",", ilUtil::quoteArray($a_ids));
4528  $where .= ") ";
4529 
4530  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4531  $where.
4532  "ORDER BY ".$a_field;
4533 
4534  $res = $ilDB->query($query);
4535  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4536  {
4537  $ids[] = $row->$a_id_name;
4538  }
4539  return $ids ? $ids : array();
4540  }
4541 
4549  function getMySQLTimestamp($a_ts)
4550  {
4551  global $ilDB;
4552 
4553  return $a_ts;
4554  }
4555 
4559  function quoteArray($a_array)
4560  {
4561  global $ilDB;
4562 
4563 
4564  if(!is_array($a_array) or !count($a_array))
4565  {
4566  return array("''");
4567  }
4568 
4569  foreach($a_array as $k => $item)
4570  {
4571  $a_array[$k] = $ilDB->quote($item);
4572  }
4573 
4574  return $a_array;
4575  }
4576 
4583  public static function sendInfo($a_info = "",$a_keep = false)
4584  {
4585  global $tpl;
4586  $tpl->setMessage("info", $a_info, $a_keep);
4587  }
4588 
4595  public static function sendFailure($a_info = "",$a_keep = false)
4596  {
4597  global $tpl;
4598  $tpl->setMessage("failure", $a_info, $a_keep);
4599  }
4600 
4607  public static function sendQuestion($a_info = "",$a_keep = false)
4608  {
4609  global $tpl;
4610  $tpl->setMessage("question", $a_info, $a_keep);
4611  }
4612 
4619  public static function sendSuccess($a_info = "",$a_keep = false)
4620  {
4621  global $tpl;
4622  $tpl->setMessage("success", $a_info, $a_keep);
4623  }
4624 
4625  function infoPanel($a_keep = true)
4626  {
4627  global $tpl,$ilias,$lng;
4628 
4629  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4630  {
4631  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html");
4632  $tpl->setCurrentBlock("infopanel");
4633 
4634  if (!empty($_SESSION["infopanel"]["text"]))
4635  {
4636  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4637  ilFrameTargetInfo::_getFrame("MainContent").
4638  "\">";
4639  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4640  $link .= "</a>";
4641  }
4642 
4643  // deactivated
4644  if (!empty($_SESSION["infopanel"]["img"]))
4645  {
4646  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4647  ilFrameTargetInfo::_getFrame("MainContent").
4648  "\">";
4649  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4650  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4651  $link .= "</a></td>";
4652  }
4653 
4654  $tpl->setVariable("INFO_ICONS",$link);
4655  $tpl->parseCurrentBlock();
4656  }
4657 
4658  //if (!$a_keep)
4659  //{
4660  //session_unregister("infopanel"); // deprecated
4661  unset($_SESSION["infopanel"]);
4662  //}
4663  }
4664 
4665 
4672  function dirsize($directory)
4673  {
4674  $size = 0;
4675  if (!is_dir($directory))
4676  {
4677  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4678  // dirsize of non-existing directory
4679  $size = @filesize($directory);
4680  // END DiskQuota Suppress PHP warning.
4681  return ($size === false) ? -1 : $size;
4682  }
4683  if ($DIR = opendir($directory))
4684  {
4685  while (($dirfile = readdir($DIR)) !== false)
4686  {
4687  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4688  continue;
4689  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4690  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4691  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
4692  {
4693  // BEGIN DiskQuota: dirsize is not a global function anymore
4694  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4695  // END DiskQuota: dirsize is not a global function anymore
4696  if ($dirSize >= 0)
4697  $size += $dirSize;
4698  else return -1;
4699  }
4700  }
4701  closedir($DIR);
4702  }
4703  return $size;
4704  }
4705 
4706  function randomhash()
4707  {
4708  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
4709  }
4710 
4711  public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4712  {
4713  /*
4714  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4715  else $expire = time() - (365*24*60*60);
4716  */
4717  // Temporary fix for feed.php
4718  if(!(bool)$a_set_cookie_invalid) $expire = 0;
4719  else $expire = time() - (365*24*60*60);
4720 
4721  // setcookie() supports 5th parameter
4722  // only for php version 5.2.0 and above
4723  if( version_compare(PHP_VERSION, '5.2.0', '>=') )
4724  {
4725  // PHP version >= 5.2.0
4726  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4727  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
4728  );
4729  }
4730  else
4731  {
4732  // PHP version < 5.2.0
4733  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4734  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE
4735  );
4736  }
4737 
4738  if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
4739  }
4740 
4741  public static function _sanitizeFilemame($a_filename)
4742  {
4743  return strip_tags(self::stripSlashes($a_filename));
4744  }
4745 
4746  public static function _getHttpPath()
4747  {
4748  global $ilIliasIniFile;
4749 
4750  if($_SERVER['SHELL'])
4751  {
4752  return $ilIliasIniFile->readVariable('server', 'http_path');
4753  }
4754  else
4755  {
4756  return ILIAS_HTTP_PATH;
4757  }
4758  }
4759 } // END class.ilUtil
4760 
4761 
4762 ?>