ILIAS  Release_4_1_x_branch Revision 61804
 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  include_once './classes/class.ilHTTPS.php';
1981 
1982  //if($_SERVER['HTTPS'])
1983  if( ilHTTPS::getInstance()->isDetected() )
1984  {
1985  // Added different handling for IE and HTTPS => send pragma after content informations
1989  #header("Pragma: ");
1990  #header("Cache-Control: ");
1991  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1992  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1993  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1994  #header("Cache-Control: post-check=0, pre-check=0", false);
1995  }
1996  else if ($disposition == "attachment")
1997  {
1998  header("Cache-control: private");
1999  }
2000  else
2001  {
2002  header("Cache-Control: no-cache, must-revalidate");
2003  header("Pragma: no-cache");
2004  }
2005 
2006  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2007 
2008  if (strlen($charset))
2009  {
2010  $charset = "; charset=$charset";
2011  }
2012  header("Content-Type: $mime$charset");
2013  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2014  header("Content-Description: ".$ascii_filename);
2015  header("Content-Length: ".(string)(strlen($a_data)));
2016 
2017  //if($_SERVER['HTTPS'])
2018  if( ilHTTPS::getInstance()->isDetected() )
2019  {
2020  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2021  header('Pragma: public');
2022  }
2023 
2024  header("Connection: close");
2025  echo $a_data;
2026  exit;
2027  }
2028 
2029  // BEGIN WebDAV: Show file in browser or provide it as attachment
2035  function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false)
2036  {
2037  // should we fail silently?
2038  if(!file_exists($a_file))
2039  {
2040  return false;
2041  }
2042 
2043  if ($isInline) {
2044  $disposition = "inline"; // "inline" to view file in browser
2045  } else {
2046  $disposition = "attachment"; // "attachment" to download to hard disk
2047  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2048  }
2049  // END WebDAV: Show file in browser or provide it as attachment
2050 
2051  if(strlen($a_mime))
2052  {
2053  $mime = $a_mime;
2054  }
2055  else
2056  {
2057  $mime = "application/octet-stream"; // or whatever the mime type is
2058  }
2059  // BEGIN WebDAV: Removed broken HTTPS code.
2060  // END WebDAV: Removed broken HTTPS code.
2061  if ($disposition == "attachment")
2062  {
2063  header("Cache-control: private");
2064  }
2065  else
2066  {
2067  header("Cache-Control: no-cache, must-revalidate");
2068  header("Pragma: no-cache");
2069  }
2070 
2071  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2072 
2073  header("Content-Type: $mime");
2074  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2075  header("Content-Description: ".$ascii_filename);
2076 
2077  // #7271: if notice gets thrown download will fail in IE
2078  $filesize = @filesize($a_file);
2079  if ($filesize)
2080  {
2081  header("Content-Length: ".(string)$filesize);
2082  }
2083 
2084  include_once './classes/class.ilHTTPS.php';
2085  #if($_SERVER['HTTPS'])
2086  if(ilHTTPS::getInstance()->isDetected())
2087  {
2088  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2089  header('Pragma: public');
2090  }
2091 
2092  header("Connection: close");
2093  ilUtil::readFile( $a_file );
2094  if ($removeAfterDelivery)
2095  {
2096  unlink ($a_file);
2097  }
2098  exit;
2099  }
2100 
2101 
2108  function readFile($a_file)
2109  {
2110  $chunksize = 1*(1024*1024); // how many bytes per chunk
2111  $buffer = '';
2112  $handle = fopen($a_file, 'rb');
2113  if ($handle === false)
2114  {
2115  return false;
2116  }
2117  while (!feof($handle))
2118  {
2119  $buffer = fread($handle, $chunksize);
2120  print $buffer;
2121  }
2122  return fclose($handle);
2123  }
2124 
2130  function getASCIIFilename($a_filename)
2131  {
2132  // The filename must be converted to ASCII, as of RFC 2183,
2133  // section 2.3.
2134 
2146 
2149 
2150  $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2151  $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2152  $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2153 
2154  // OS do not allow the following characters in filenames: \/:*?"<>|
2155  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2156 
2157  return $ascii_filename;
2158  }
2159 
2160  /*
2161  * Encodes HTML entities outside of HTML tags
2162  */
2163  function htmlentitiesOutsideHTMLTags($htmlText)
2164  {
2165  $matches = Array();
2166  $sep = '###HTMLTAG###';
2167 
2168  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2169  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2170  $tmp = explode($sep, $tmp);
2171 
2172  for ($i=0; $i<count($tmp); $i++)
2173  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2174 
2175  $tmp = join($sep, $tmp);
2176 
2177  for ($i=0; $i<count($matches[0]); $i++)
2178  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2179 
2180  return $tmp;
2181  }
2182 
2186  function getJavaPath()
2187  {
2188  return PATH_TO_JAVA;
2189  //global $ilias;
2190 
2191  //return $ilias->getSetting("java_path");
2192  }
2193 
2198  function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2199  {
2200  $amp = $xml_style
2201  ? "&amp;"
2202  : "&";
2203 
2204  $url = (is_int(strpos($a_url, "?")))
2205  ? $a_url.$amp.$a_par
2206  : $a_url."?".$a_par;
2207 
2208  return $url;
2209  }
2210 
2225  function makeDir($a_dir)
2226  {
2227  $a_dir = trim($a_dir);
2228 
2229  // remove trailing slash (bugfix for php 4.2.x)
2230  if (substr($a_dir,-1) == "/")
2231  {
2232  $a_dir = substr($a_dir,0,-1);
2233  }
2234 
2235  // check if a_dir comes with a path
2236  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2237  {
2238  $path = ".";
2239  }
2240 
2241  // create directory with file permissions of parent directory
2242  umask(0000);
2243  return @mkdir($a_dir,fileperms($path));
2244  }
2245 
2246 
2259  public static function makeDirParents($a_dir)
2260  {
2261  $dirs = array($a_dir);
2262  $a_dir = dirname($a_dir);
2263  $last_dirname = '';
2264 
2265  while($last_dirname != $a_dir)
2266  {
2267  array_unshift($dirs, $a_dir);
2268  $last_dirname = $a_dir;
2269  $a_dir = dirname($a_dir);
2270  }
2271 
2272  // find the first existing dir
2273  $reverse_paths = array_reverse($dirs, TRUE);
2274  $found_index = -1;
2275  foreach ($reverse_paths as $key => $value)
2276  {
2277  if ($found_index == -1)
2278  {
2279  if (is_dir($value))
2280  {
2281  $found_index = $key;
2282  }
2283  }
2284  }
2285 
2286  umask(0000);
2287  foreach ($dirs as $dirindex => $dir)
2288  {
2289  // starting with the longest existing path
2290  if ($dirindex >= $found_index)
2291  {
2292  if (! file_exists($dir))
2293  {
2294  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2295  {
2296  // on some systems there is an error when there is a slash
2297  // at the end of a directory in mkdir, see Mantis #2554
2298  $dir = substr($dir,0,strlen($dir)-1);
2299  }
2300  if (! mkdir($dir, $umask))
2301  {
2302  error_log("Can't make directory: $dir");
2303  return false;
2304  }
2305  }
2306  elseif (! is_dir($dir))
2307  {
2308  error_log("$dir is not a directory");
2309  return false;
2310  }
2311  else
2312  {
2313  // get umask of the last existing parent directory
2314  $umask = fileperms($dir);
2315  }
2316  }
2317  }
2318  return true;
2319  }
2320 
2328  public static function delDir($a_dir, $a_clean_only = false)
2329  {
2330  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2331  {
2332  return;
2333  }
2334 
2335  $current_dir = opendir($a_dir);
2336 
2337  $files = array();
2338 
2339  // this extra loop has been necessary because of a strange bug
2340  // at least on MacOS X. A looped readdir() didn't work
2341  // correctly with larger directories
2342  // when an unlink happened inside the loop. Getting all files
2343  // into the memory first solved the problem.
2344  while($entryname = readdir($current_dir))
2345  {
2346  $files[] = $entryname;
2347  }
2348 
2349  foreach($files as $file)
2350  {
2351  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2352  {
2353  ilUtil::delDir(${a_dir}."/".${file});
2354  }
2355  elseif ($file != "." and $file != "..")
2356  {
2357  unlink(${a_dir}."/".${file});
2358  }
2359  }
2360 
2361  closedir($current_dir);
2362  if (!$a_clean_only)
2363  {
2364  @rmdir(${a_dir});
2365  }
2366  }
2367 
2368 
2372  function getDir($a_dir)
2373  {
2374  $current_dir = opendir($a_dir);
2375 
2376  $dirs = array();
2377  $files = array();
2378  while($entry = readdir($current_dir))
2379  {
2380  if(is_dir($a_dir."/".$entry))
2381  {
2382  $dirs[$entry] = array("type" => "dir", "entry" => $entry);
2383  }
2384  else
2385  {
2386  if ($entry != "." && $entry != "..")
2387  {
2388  $size = filesize($a_dir."/".$entry);
2389  $files[$entry] = array("type" => "file", "entry" => $entry,
2390  "size" => $size);
2391  }
2392  }
2393  }
2394  ksort($dirs);
2395  ksort($files);
2396 
2397  return array_merge($dirs, $files);
2398  }
2399 
2403  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2404  {
2405  if (is_array($a_arr))
2406  {
2407  foreach ($a_arr as $k => $v)
2408  {
2409  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2410  }
2411  }
2412 
2413  return $a_arr;
2414  }
2415 
2419  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2420  {
2421  if (is_array($a_data))
2422  {
2423  foreach ($a_data as $k => $v)
2424  {
2425  if (is_array($v))
2426  {
2427  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2428  }
2429  else
2430  {
2431  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2432  }
2433  }
2434  }
2435  else
2436  {
2437  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2438  }
2439 
2440  return $a_data;
2441  }
2442 
2448  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2449  {
2450  if (ini_get("magic_quotes_gpc"))
2451  {
2452  $a_str = stripslashes($a_str);
2453  }
2454 
2455  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2456  }
2457 
2463  function stripOnlySlashes($a_str)
2464  {
2465  if (ini_get("magic_quotes_gpc"))
2466  {
2467  $a_str = stripslashes($a_str);
2468  }
2469 
2470  return $a_str;
2471  }
2472 
2476  function secureString($a_str, $a_strip_html = true, $a_allow = "")
2477  {
2478  // check whether all allowed tags can be made secure
2479  $only_secure = true;
2480  $allow_tags = explode(">", $a_allow);
2481  $sec_tags = ilUtil::getSecureTags();
2482  $allow_array = array();
2483  foreach($allow_tags as $allow)
2484  {
2485  if ($allow != "")
2486  {
2487  $allow = str_replace("<", "", $allow);
2488 
2489  if (!in_array($allow, $sec_tags))
2490  {
2491  $only_secure = false;
2492  }
2493  $allow_array[] = $allow;
2494  }
2495  }
2496 
2497  // default behaviour: allow only secure tags 1:1
2498  if (($only_secure || $a_allow == "") && $a_strip_html)
2499  {
2500  if ($a_allow == "")
2501  {
2502  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2503  "gap", "sub", "sup", "pre", "strike");
2504  }
2505 
2506  // this currently removes parts of strings like "a <= b"
2507  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2508  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2509  $a_str = strip_tags($a_str); // strip all other tags
2510  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2511 
2512  // a possible solution could be something like:
2513  // $a_str = str_replace("<", "&lt;", $a_str);
2514  // $a_str = str_replace(">", "&gt;", $a_str);
2515  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2516  //
2517  // output would be ok then, but input fields would show
2518  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2519  }
2520  else
2521  {
2522  // only for scripts, that need to allow more/other tags and parameters
2523  if ($a_strip_html)
2524  {
2525  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2526  }
2527  }
2528 
2529  return $a_str;
2530  }
2531 
2532  function getSecureTags()
2533  {
2534  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2535  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2536  }
2537 
2538  function maskSecureTags($a_str, $allow_array)
2539  {
2540  foreach ($allow_array as $t)
2541  {
2542  switch($t)
2543  {
2544  case "a":
2545  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2546  break;
2547 
2548  case "img":
2549  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2550  break;
2551 
2552  case "p":
2553  case "div":
2554  $a_str = ilUtil::maskTag($a_str, $t, array(
2555  array("param" => "align", "value" => "left"),
2556  array("param" => "align", "value" => "center"),
2557  array("param" => "align", "value" => "justify"),
2558  array("param" => "align", "value" => "right")
2559  ));
2560  break;
2561 
2562  default:
2563  $a_str = ilUtil::maskTag($a_str, $t);
2564  break;
2565  }
2566  }
2567 
2568  return $a_str;
2569  }
2570 
2571  function unmaskSecureTags($a_str, $allow_array)
2572  {
2573  foreach ($allow_array as $t)
2574  {
2575  switch($t)
2576  {
2577  case "a":
2578  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2579  break;
2580 
2581  case "img":
2582  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2583  break;
2584 
2585  case "p":
2586  case "div":
2587  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2588  array("param" => "align", "value" => "left"),
2589  array("param" => "align", "value" => "center"),
2590  array("param" => "align", "value" => "justify"),
2591  array("param" => "align", "value" => "right")
2592  ));
2593  break;
2594 
2595  default:
2596  $a_str = ilUtil::unmaskTag($a_str, $t);
2597  break;
2598  }
2599  }
2600 
2601  return $a_str;
2602  }
2603 
2608  function securePlainString($a_str)
2609  {
2610  if (ini_get("magic_quotes_gpc"))
2611  {
2612  return stripslashes($a_str);
2613  }
2614  else
2615  {
2616  return $a_str;
2617  }
2618  }
2633  function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2634  {
2635  $encoded = "";
2636 
2637  if ($a_make_links_clickable)
2638  {
2639  // Find text sequences in the plain text string which match
2640  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2641  // Encode all other text sequences in the plain text string using
2642  // htmlspecialchars and nl2br.
2643  // The following expressions matches URI's as specified in RFC 2396.
2644  //
2645  // The expression matches URI's, which start with some well known
2646  // schemes, like "http:", or with "www.". This must be followed
2647  // by at least one of the following RFC 2396 expressions:
2648  // - alphanum: [a-zA-Z0-9]
2649  // - reserved: [;\/?:|&=+$,]
2650  // - mark: [\\-_.!~*\'()]
2651  // - escaped: %[0-9a-fA-F]{2}
2652  // - fragment delimiter: #
2653  // - uric_no_slash: [;?:@&=+$,]
2654  $matches = array();
2655  $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);
2656  $pos1 = 0;
2657  $encoded = "";
2658  foreach ($matches as $match)
2659  {
2660  }
2661  foreach ($matches[0] as $match)
2662  {
2663  $matched_text = $match[0];
2664  $pos2 = $match[1];
2665  if ($matched_offset != previous_offset)
2666  {
2667  // encode plain text
2668  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2669  }
2670  // encode URI
2671  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2672 
2673 
2674  $pos1 = $pos2 + strlen($matched_text);
2675  }
2676  if ($pos1 < strlen($a_str))
2677  {
2678  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2679  }
2680  }
2681  else
2682  {
2683  $encoded = nl2br(htmlspecialchars($a_str));
2684  }
2685  return $encoded;
2686  }
2687 
2688 
2689  function maskAttributeTag($a_str, $tag, $tag_att)
2690  {
2691  global $ilLog;
2692 
2693  $ws = "[ \t\r\f\v\n]*";
2694  $att = $ws."[^>]*".$ws;
2695 
2696  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2697  $a_str, $found))
2698  {
2699  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2700  $esc = array();
2701  foreach($un as $v)
2702  {
2703  $esc[] = "\\".$v;
2704  }
2705  $ff = str_replace($un, $esc, $found[1]);
2706 
2707  $old_str = $a_str;
2708  $a_str = eregi_replace("<".$ff.">",
2709  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2710  if ($old_str == $a_str)
2711  {
2712  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2713  htmlentities($a_str));
2714  return $a_str;
2715  }
2716  }
2717  $a_str = str_ireplace("</$tag>",
2718  "&lt;/$tag&gt;", $a_str);
2719  return $a_str;
2720  }
2721 
2722  function unmaskAttributeTag($a_str, $tag, $tag_att)
2723  {
2724  global $ilLog;
2725 
2726  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2727  $a_str, $found))
2728  {
2729  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2730  $esc = array();
2731  foreach($un as $v)
2732  {
2733  $esc[] = "\\".$v;
2734  }
2735  $ff = str_replace($un, $esc, $found[1]);
2736 
2737  $old_str = $a_str;
2738  $a_str = eregi_replace("&lt;".$ff."&gt;",
2739  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2740  if ($old_str == $a_str)
2741  {
2742  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2743  htmlentities($a_str));
2744  return $a_str;
2745  }
2746  }
2747  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2748  return $a_str;
2749  }
2750 
2751  function maskTag($a_str, $t, $fix_param = "")
2752  {
2753  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2754  "&lt;".$t."&gt;", $a_str);
2755  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2756  "&lt;/".$t."&gt;", $a_str);
2757 
2758  if (is_array($fix_param))
2759  {
2760  foreach ($fix_param as $p)
2761  {
2762  $k = $p["param"];
2763  $v = $p["value"];
2764  $a_str = str_replace("<$t $k=\"$v\">",
2765  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2766  }
2767  }
2768 
2769  return $a_str;
2770  }
2771 
2772  function unmaskTag($a_str, $t, $fix_param = "")
2773  {
2774  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2775  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2776 
2777  if (is_array($fix_param))
2778  {
2779  foreach ($fix_param as $p)
2780  {
2781  $k = $p["param"];
2782  $v = $p["value"];
2783  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2784  "<"."$t $k=\"$v\"".">", $a_str);
2785  }
2786  }
2787  return $a_str;
2788  }
2789 
2790  function secureLink($a_str)
2791  {
2792  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2793  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2794  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2795  return $a_str;
2796  }
2797 
2809  function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2810  {
2811  //$a_str = strip_tags($a_str, $a_allow);
2812 
2813  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
2814  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
2815  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
2816  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
2817  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
2818  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
2819  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
2820  "title,tr,tt,u,ul,var";
2821  $a_allow = strtolower ($a_allow);
2822  $negatives = explode(",",$negativestr);
2823  $outer_old_str = "";
2824  while($outer_old_str != $a_str)
2825  {
2826  $outer_old_str = $a_str;
2827  foreach ($negatives as $item)
2828  {
2829  $pos = strpos($a_allow, "<$item>");
2830 
2831  // remove complete tag, if not allowed
2832  if ($pos === false)
2833  {
2834  $old_str = "";
2835  while($old_str != $a_str)
2836  {
2837  $old_str = $a_str;
2838  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2839  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2840  }
2841  }
2842  }
2843  }
2844 
2845  if ($a_rm_js)
2846  {
2847  // remove all attributes if an "on..." attribute is given
2848  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2849 
2850  // remove all attributes if a "javascript" is within tag
2851  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2852 
2853  // remove all attributes if an "expression" is within tag
2854  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2855  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2856  }
2857 
2858  return $a_str;
2859  }
2860 
2861 
2867  function addSlashes($a_str)
2868  {
2869  if (ini_get("magic_quotes_gpc"))
2870  {
2871  return $a_str;
2872  }
2873  else
2874  {
2875  return addslashes($a_str);
2876  }
2877  }
2878 
2888  function prepareFormOutput($a_str, $a_strip = false)
2889  {
2890  if($a_strip)
2891  {
2892  $a_str = ilUtil::stripSlashes($a_str);
2893  }
2894  $a_str = htmlspecialchars($a_str);
2895  // Added replacement of curly brackets to prevent
2896  // problems with PEAR templates, because {xyz} will
2897  // be removed as unused template variable
2898  $a_str = str_replace("{", "&#123;", $a_str);
2899  $a_str = str_replace("}", "&#125;", $a_str);
2900  // needed for LaTeX conversion \\ in LaTeX is a line break
2901  // but without this replacement, php changes \\ to \
2902  $a_str = str_replace("\\", "&#92;", $a_str);
2903  return $a_str;
2904  }
2905 
2906 
2914  function prepareDBString($a_str)
2915  {
2916  return addslashes($a_str);
2917  }
2918 
2919 
2926  function removeItemFromDesktops($a_id)
2927  {
2928  return ilObjUser::_removeItemFromDesktops($a_id);
2929  }
2930 
2931 
2939  function extractParameterString($a_parstr)
2940  {
2941  // parse parameters in array
2942  $par = array();
2943  $ok=true;
2944  while(($spos=strpos($a_parstr,"=")) && $ok)
2945  {
2946  // extract parameter
2947  $cpar = substr($a_parstr,0,$spos);
2948  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
2949  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
2950  $cpar = substr($cpar,1,strlen($cpar)-1);
2951  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
2952  $cpar = substr($cpar,0,strlen($cpar)-1);
2953 
2954  // parameter name should only
2955  $cpar_old = "";
2956  while($cpar != $cpar_old)
2957  {
2958  $cpar_old = $cpar;
2959  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
2960  }
2961 
2962  // extract value
2963  if ($cpar != "")
2964  {
2965  if($spos=strpos($a_parstr,"\""))
2966  {
2967  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
2968  $spos=strpos($a_parstr,"\"");
2969  if(is_int($spos))
2970  {
2971  $cval = substr($a_parstr,0,$spos);
2972  $par[$cpar]=$cval;
2973  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
2974  }
2975  else
2976  $ok=false;
2977  }
2978  else
2979  $ok=false;
2980  }
2981  }
2982 
2983  if($ok) return $par; else return false;
2984  }
2985 
2986  function assembleParameterString($a_par_arr)
2987  {
2988  if (is_array($a_par_arr))
2989  {
2990  $target_arr = array();
2991  foreach ($a_par_arr as $par => $val)
2992  {
2993  $target_arr[] = "$par=\"$val\"";
2994  }
2995  $target_str = implode(", ", $target_arr);
2996  }
2997 
2998  return $target_str;
2999  }
3000 
3004  function dumpString($a_str)
3005  {
3006  $ret = $a_str.": ";
3007  for($i=0; $i<strlen($a_str); $i++)
3008  {
3009  $ret.= ord(substr($a_str,$i,1))." ";
3010  }
3011  return $ret;
3012  }
3013 
3014 
3018  function yn2tf($a_yn)
3019  {
3020  if(strtolower($a_yn) == "y")
3021  {
3022  return true;
3023  }
3024  else
3025  {
3026  return false;
3027  }
3028  }
3029 
3033  function tf2yn($a_tf)
3034  {
3035  if($a_tf)
3036  {
3037  return "y";
3038  }
3039  else
3040  {
3041  return "n";
3042  }
3043  }
3044 
3053  function sort_func ($a, $b)
3054  {
3055  global $array_sortby,$array_sortorder;
3056 
3057  // this comparison should give optimal results if
3058  // locale is provided and mb string functions are supported
3059  if ($array_sortorder == "asc")
3060  {
3061  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3062  }
3063 
3064  if ($array_sortorder == "desc")
3065  {
3066  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3067  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3068  }
3069  }
3070 
3079  function sort_func_numeric ($a, $b)
3080  {
3081  global $array_sortby,$array_sortorder;
3082 
3083  if ($array_sortorder == "asc")
3084  {
3085  return $a["$array_sortby"] > $b["$array_sortby"];
3086  }
3087 
3088  if ($array_sortorder == "desc")
3089  {
3090  return $a["$array_sortby"] < $b["$array_sortby"];
3091  }
3092  }
3103  public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3104  $a_keep_keys = false)
3105  {
3106  include_once("./Services/Utilities/classes/class.ilStr.php");
3107 
3108  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3109  if (! $a_keep_keys) {
3110  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3111  }
3112  // END WebDAV Provide a 'stable' sort algorithm
3113 
3114  global $array_sortby,$array_sortorder;
3115 
3116  $array_sortby = $a_array_sortby;
3117 
3118  if ($a_array_sortorder == "desc")
3119  {
3120  $array_sortorder = "desc";
3121  }
3122  else
3123  {
3124  $array_sortorder = "asc";
3125  }
3126  if($a_numeric)
3127  {
3128  if ($a_keep_keys)
3129  {
3130  uasort($array, array("ilUtil", "sort_func_numeric"));
3131  }
3132  else
3133  {
3134  usort($array, array("ilUtil", "sort_func_numeric"));
3135  }
3136  }
3137  else
3138  {
3139  if ($a_keep_keys)
3140  {
3141  uasort($array, array("ilUtil", "sort_func"));
3142  }
3143  else
3144  {
3145  usort($array, array("ilUtil", "sort_func"));
3146  }
3147  }
3148  //usort($array,"ilUtil::sort_func");
3149 
3150  return $array;
3151  }
3152  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3165  function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3166  {
3167  global $array_sortby,$array_sortorder;
3168 
3169  $array_sortby = $a_array_sortby;
3170 
3171  if ($a_array_sortorder == "desc")
3172  {
3173  $array_sortorder = "desc";
3174  }
3175  else
3176  {
3177  $array_sortorder = "asc";
3178  }
3179 
3180  // Create a copy of the array values for sorting
3181  $sort_array = array_values($array);
3182 
3183  if($a_numeric)
3184  {
3185  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3186  }
3187  else
3188  {
3189  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3190  }
3191 
3192  return $sort_array;
3193  }
3194  function mergesort(&$array, $cmp_function = 'strcmp') {
3195  // Arrays of size < 2 require no action.
3196  if (count($array) < 2) return;
3197 
3198  // Split the array in half
3199  $halfway = count($array) / 2;
3200  $array1 = array_slice($array, 0, $halfway);
3201  $array2 = array_slice($array, $halfway);
3202 
3203  // Recurse to sort the two halves
3204  ilUtil::mergesort($array1, $cmp_function);
3205  ilUtil::mergesort($array2, $cmp_function);
3206 
3207  // If all of $array1 is <= all of $array2, just append them.
3208  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3209  $array = array_merge($array1, $array2);
3210  return;
3211  }
3212 
3213  // Merge the two sorted arrays into a single sorted array
3214  $array = array();
3215  $ptr1 = $ptr2 = 0;
3216  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3217  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3218  $array[] = $array1[$ptr1++];
3219  }
3220  else {
3221  $array[] = $array2[$ptr2++];
3222  }
3223  }
3224 
3225  // Merge the remainder
3226  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3227  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3228 
3229  return;
3230  }
3231  // END WebDAV: Provide a 'stable' sort algorithm
3232 
3242  function unique_multi_array($array, $sub_key)
3243  {
3244  $target = array();
3245  $existing_sub_key_values = array();
3246 
3247  foreach ($array as $key=>$sub_array)
3248  {
3249  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3250  {
3251  $existing_sub_key_values[] = $sub_array[$sub_key];
3252  $target[$key] = $sub_array;
3253  }
3254  }
3255 
3256  return $target;
3257  }
3258 
3259 
3267  function getGDSupportedImageType($a_desired_type)
3268  {
3269  $a_desired_type = strtolower($a_desired_type);
3270  // get supported Image Types
3271  $im_types = ImageTypes();
3272 
3273  switch($a_desired_type)
3274  {
3275  case "jpg":
3276  if ($im_types & IMG_JPG) return "jpg";
3277  if ($im_types & IMG_GIF) return "gif";
3278  if ($im_types & IMG_PNG) return "png";
3279  break;
3280 
3281  case "gif":
3282  if ($im_types & IMG_GIF) return "gif";
3283  if ($im_types & IMG_JPG) return "jpg";
3284  if ($im_types & IMG_PNG) return "png";
3285  break;
3286 
3287  case "png":
3288  if ($im_types & IMG_PNG) return "png";
3289  if ($im_types & IMG_JPG) return "jpg";
3290  if ($im_types & IMG_GIF) return "gif";
3291  break;
3292  }
3293 
3294  return "";
3295  }
3296 
3304  function deducibleSize($a_mime)
3305  {
3306  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3307  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3308  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3309  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3310  {
3311  return true;
3312  }
3313  else
3314  {
3315  return false;
3316  }
3317  }
3318 
3319 
3325  function redirect($a_script)
3326  {
3327  global $log, $PHP_SELF;
3328 
3329 //echo "<br>".$a_script;
3330  if (!is_int(strpos($a_script, "://")))
3331  {
3332  if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3333  {
3334  if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3335  {
3336  $a_script = "setup/".$a_script;
3337  }
3338  $a_script = ILIAS_HTTP_PATH."/".$a_script;
3339  }
3340  }
3341 //echo "<br>".$a_script; exit;
3342  header("Location: ".$a_script);
3343  exit();
3344  }
3345 
3351  function insertInstIntoID($a_value)
3352  {
3353  if (substr($a_value, 0, 4) == "il__")
3354  {
3355  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3356  }
3357 
3358  return $a_value;
3359  }
3360 
3369  function groupNameExists($a_group_name,$a_id = 0)
3370  {
3371  global $ilDB,$ilErr;
3372 
3373  if (empty($a_group_name))
3374  {
3375  $message = get_class($this)."::_NameExists(): No groupname given!";
3376  $ilErr->raiseError($message,$ilErr->WARNING);
3377  }
3378 
3379  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3380 
3381  $q = "SELECT obj_id FROM object_data ".
3382  "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3383  "AND type = ".$ilDB->quote("grp", "text").
3384  $clause;
3385 
3386  $r = $ilDB->query($q);
3387 
3388  if ($r->numRows())
3389  {
3390  return true;
3391  }
3392  else
3393  {
3394  return false;
3395  }
3396  }
3397 
3398  /*
3399  * get the user_ids which correspond a search string
3400  * static function
3401  * @param string search string
3402  * @access public
3403  */
3404  function searchGroups($a_search_str)
3405  {
3406  global $ilDB;
3407 
3408  $q = "SELECT * ".
3409  "FROM object_data ,object_reference ".
3410  "WHERE (".$ilDB->like("object_data.title", "text", "%".$a_search_str."%")." ".
3411  "OR ".$ilDB->like("object_data.description", "text", "%".$a_search_str."%").") ".
3412  "AND object_data.type = 'grp' ".
3413  "AND object_data.obj_id = object_reference.obj_id ".
3414  "ORDER BY title ";
3415 
3416  $res = $ilDB->query($q);
3417 
3418  while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3419  {
3420  // STORE DATA IN ARRAY WITH KEY obj_id
3421  // SO DUPLICATE ENTRIES ( LINKED OBJECTS ) ARE UNIQUE
3422  $ids[$row->obj_id] = array(
3423  "ref_id" => $row->ref_id,
3424  "title" => $row->title,
3425  "description" => $row->description);
3426  }
3427 
3428  return $ids ? $ids : array();
3429  }
3430 
3434  function getMemString()
3435  {
3436  $my_pid = getmypid();
3437  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3438  }
3439 
3443  function isWindows()
3444  {
3445  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3446  {
3447  return true;
3448  }
3449  return false;
3450  }
3451 
3452 
3453  function escapeShellArg($a_arg)
3454  {
3455  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3456  // see also ilias bug 5630
3457  return escapeshellarg($a_arg);
3458  }
3459 
3467  public function escapeShellCmd($a_arg)
3468  {
3469  if(ini_get('safe_mode') == 1)
3470  {
3471  return $a_arg;
3472  }
3473  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3474  return escapeshellcmd($a_arg);
3475  }
3476 
3484  public static function execQuoted($cmd, $args = NULL)
3485  {
3486  if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3487  {
3488  // cmd won't work without quotes
3489  $cmd = '"'.$cmd.'"';
3490  if($args)
3491  {
3492  // args are also quoted, workaround is to quote the whole command AGAIN
3493  // was fixed in php 5.2 (see php bug #25361)
3494  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3495  {
3496  $cmd = '"'.$cmd." ".$args.'"';
3497  }
3498  // args are not quoted or php is fixed, just append
3499  else
3500  {
3501  $cmd .= " ".$args;
3502  }
3503  }
3504  }
3505  // nothing todo, just append args
3506  else if($args)
3507  {
3508  $cmd .= " ".$args;
3509  }
3510  exec($cmd, $arr);
3511  return $arr;
3512  }
3513 
3514  /*
3515  * Calculates a Microsoft Excel date/time value
3516  *
3517  * Calculates a Microsoft Excel date/time value (nr of days after 1900/1/1 0:00) for
3518  * a given date and time. The function only accepts dates after 1970/1/1, because the
3519  * unix timestamp functions used in the function are starting with that date.
3520  * If you don't enter parameters the date/time value for the actual date/time
3521  * will be calculated.
3522  *
3523  * static function
3524  *
3525  * @param integer $year Year
3526  * @param integer $month Month
3527  * @param integer $day Day
3528  * @param integer $hour Hour
3529  * @param integer $minute Minute
3530  * @param integer $second Second
3531  * @return float The Microsoft Excel date/time value
3532  * @access public
3533  */
3534  function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3535  {
3536  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3537  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3538  {
3539  $target_time = time();
3540  }
3541  else
3542  {
3543  if ($year < 1970)
3544  {
3545  return 0;
3546  }
3547  }
3548  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3549  $difference = $target_time - $starting_time;
3550  $days = (($difference - ($difference % 86400)) / 86400);
3551  $difference = $difference - ($days * 86400) + 3600;
3552  return ($days + 25570 + ($difference / 86400));
3553  }
3554 
3558  function renameExecutables($a_dir)
3559  {
3560  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3561  foreach ($def_arr as $def)
3562  {
3563  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3564  }
3565 
3566  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3567  foreach ($def_arr as $def)
3568  {
3569  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3570  }
3571  }
3572 
3583  function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3584  {
3585  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3586  || trim($a_old_suffix) == "")
3587  {
3588  return false;
3589  }
3590 
3591  // check if argument is directory
3592  if (!@is_dir($a_dir))
3593  {
3594  return false;
3595  }
3596 
3597  // read a_dir
3598  $dir = opendir($a_dir);
3599 
3600  while($file = readdir($dir))
3601  {
3602  if ($file != "." and
3603  $file != "..")
3604  {
3605  // directories
3606  if (@is_dir($a_dir."/".$file))
3607  {
3608  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3609  }
3610 
3611  // files
3612  if (@is_file($a_dir."/".$file))
3613  {
3614  // first check for files with trailing dot
3615  if(strrpos($file,'.') == (strlen($file) - 1))
3616  {
3617  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3618  $file = substr($file,0,-1);
3619  }
3620 
3621  $path_info = pathinfo($a_dir."/".$file);
3622 
3623  if (strtolower($path_info["extension"]) ==
3624  strtolower($a_old_suffix))
3625  {
3626  $pos = strrpos($a_dir."/".$file, ".");
3627  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3628  rename($a_dir."/".$file, $new_name);
3629  }
3630  }
3631  }
3632  }
3633  return true;
3634  }
3635 
3636  function isAPICall () {
3637  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3638  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3639  }
3640 
3641  function KT_replaceParam($qstring, $paramName, $paramValue) {
3642  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3643  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3644  } else {
3645  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3646  }
3647  }
3648 
3649  function replaceUrlParameterString ($url, $parametersArray) {
3650 
3651  foreach ($parametersArray as $paramName => $paramValue ) {
3652  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3653  }
3654  return $url;
3655  }
3656 
3660  function generatePasswords ($a_number)
3661  {
3662  $ret = array();
3663  srand((double) microtime()*1000000);
3664 
3665  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3666  $security = ilSecuritySettings::_getInstance();
3667 
3668  for ($i=1; $i<=$a_number; $i++)
3669  {
3670  $min = ($security->getPasswordMinLength() > 0)
3671  ? $security->getPasswordMinLength()
3672  : 6;
3673  $max = ($security->getPasswordMaxLength() > 0)
3674  ? $security->getPasswordMaxLength()
3675  : 10;
3676  if ($min > $max)
3677  {
3678  $max = $max + 1;
3679  }
3680  $length = rand($min,$max);
3681  $next = rand(1,2);
3682  $vowels = "aeiou";
3683  $consonants = "bcdfghjklmnpqrstvwxyz";
3684  $numbers = "1234567890";
3685  $special = "_.+?#-*@!$%~";
3686  $pw = "";
3687 
3688  // position for number
3689  if ($security->isPasswordCharsAndNumbersEnabled())
3690  {
3691  $num_pos = rand(0, $length - 1);
3692  }
3693 
3694  // position for special character
3695  if ($security->isPasswordSpecialCharsEnabled())
3696  {
3697  $spec_pos = rand(0, $length - 1);
3698  if ($security->isPasswordCharsAndNumbersEnabled())
3699  {
3700  if ($num_pos == $spec_pos) // not same position for number/special
3701  {
3702  if ($spec_pos > 0)
3703  {
3704  $spec_pos -= 1;
3705  }
3706  else
3707  {
3708  $spec_pos += 1;
3709  }
3710  }
3711  }
3712  }
3713  for ($j=0; $j < $length; $j++)
3714  {
3715  if ($security->isPasswordCharsAndNumbersEnabled() && $num_pos == $j)
3716  {
3717  $pw.= $numbers[rand(0,strlen($numbers)-1)];
3718  }
3719  else if ($security->isPasswordSpecialCharsEnabled() && $spec_pos == $j)
3720  {
3721  $pw.= $special[rand(0,strlen($special)-1)];
3722  }
3723  else
3724  {
3725  switch ($next)
3726  {
3727  case 1:
3728  $pw.= $consonants[rand(0,strlen($consonants)-1)];
3729  $next = 2;
3730  break;
3731 
3732  case 2:
3733  $pw.= $vowels[rand(0,strlen($vowels)-1)];
3734  $next = 1;
3735  break;
3736  }
3737  }
3738  }
3739 
3740  $ret[] = $pw;
3741  }
3742  return $ret;
3743  }
3744 
3746  {
3747  $path = preg_replace("/[\/\\\]+$/", "", $path);
3748  return $path;
3749  }
3750 
3760  {
3761  if (empty($data))
3762  {
3763  $data = array();
3764  }
3765 
3766  foreach($data as $k=>$datum)
3767  {
3768  if(is_null($datum)) $data[$k] = 'null';
3769  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
3770  if(is_array($datum)) $data[$k] = array_php2js($datum);
3771  }
3772 
3773  return "[" . implode(', ', $data) . "]";
3774  }
3775 
3780  function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3781  {
3782  global $lng;
3783 
3784  if (IL_VIRUS_SCANNER != "None")
3785  {
3786  require_once("classes/class.ilVirusScannerFactory.php");
3788  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3789  {
3790  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
3791  {
3792  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3793  if ($vs->fileCleaned())
3794  {
3795  $vs_txt.= "<br />".$lng->txt("cleaned_file").
3796  "<br />".$clean_txt;
3797  $vs_txt.= "<br />".$lng->txt("repeat_scan");
3798  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3799  {
3800  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
3801  "<br />".nl2br($vs2_txt));
3802  }
3803  else
3804  {
3805  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
3806  }
3807  }
3808  else
3809  {
3810  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
3811  }
3812  }
3813  else
3814  {
3815  return array(false, nl2br($vs_txt));
3816  }
3817  }
3818  }
3819 
3820  return array(true,"");
3821  }
3822 
3823 
3827  function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true)
3828  {
3829  global $lng, $ilias;
3830 //echo "<br>ilUtli::moveuploadedFile($a_name)";
3831 
3832  if (!is_file($a_file))
3833  {
3834  if ($a_raise_errors)
3835  {
3836  $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
3837  }
3838  else
3839  {
3840  ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
3841  }
3842  return false;
3843  }
3844 
3845  // virus handling
3846  $vir = ilUtil::virusHandling($a_file, $a_name);
3847  if (!$vir[0])
3848  {
3849  unlink($a_file);
3850  if ($a_raise_errors)
3851  {
3852  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
3853  $vir[1],
3854  $ilias->error_obj->MESSAGE);
3855  }
3856  else
3857  {
3858  ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
3859  $vir[1], true);
3860  }
3861  return false;
3862  }
3863  else
3864  {
3865  if ($vir[1] != "")
3866  {
3867  ilUtil::sendInfo($vir[1], true);
3868  }
3869  return move_uploaded_file($a_file, $a_target);
3870  }
3871  }
3872 
3873 
3877  function date_mysql2time($mysql_date_time) {
3878  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
3879  list($jahr, $monat, $tag) = explode("-", $datum);
3880  list($std, $min, $sec) = explode(":", $uhrzeit);
3881  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3882  }
3883 
3887  function now()
3888  {
3889  return date("Y-m-d H:i:s");
3890  }
3891 
3905  function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
3906  {
3907  $resultarray = array();
3908  foreach ($row as $rowindex => $entry)
3909  {
3910  $surround = FALSE;
3911  if ($quoteAll)
3912  {
3913  $surround = TRUE;
3914  }
3915  if (strpos($entry, "\"") !== FALSE)
3916  {
3917  $entry = str_replace("\"", "\"\"", $entry);
3918  $surround = TRUE;
3919  }
3920  if (strpos($entry, $separator) !== FALSE)
3921  {
3922  $surround = TRUE;
3923  }
3924  if ($compatibleWithMSExcel)
3925  {
3926  // replace all CR LF with LF (for Excel for Windows compatibility
3927  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
3928  }
3929  if ($surround)
3930  {
3931  if ($outUTF8)
3932  {
3933  $resultarray[$rowindex] = "\"" . $entry . "\"";
3934  }
3935  else
3936  {
3937  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3938  }
3939  }
3940  else
3941  {
3942  if ($outUTF8)
3943  {
3944  $resultarray[$rowindex] = $entry;
3945  }
3946  else
3947  {
3948  $resultarray[$rowindex] = utf8_decode($entry);
3949  }
3950  }
3951  }
3952  return $resultarray;
3953  }
3954 
3955  // validates a domain name (example: www.ilias.de)
3956  function isDN($a_str)
3957  {
3958  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
3959  }
3960 
3961  // validates an IP address (example: 192.168.1.1)
3962  function isIPv4($a_str)
3963  {
3964  return(preg_match("/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.".
3965  "(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/",$a_str));
3966  }
3967 
3968 
3995  function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
3996  {
3997  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
3998 
3999  if(!is_array($a_obj_type))
4000  {
4001  $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4002  }
4003  else
4004  {
4005  $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4006  }
4007 
4008  // limit number of results default is search result limit
4009  if(!$limit)
4010  {
4011  $limit = $ilias->getSetting('search_max_hits',100);
4012  }
4013  if($limit == -1)
4014  {
4015  $limit = 10000;
4016  }
4017 
4018  // default to logged in usr
4019  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4020  $a_roles = $rbacreview->assignedRoles($a_usr_id);
4021 
4022  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4023  // is assigned to the system role
4024  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4025  {
4026  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4027  "LEFT JOIN tree ON obr.ref_id = tree.child ".
4028  $where.
4029  "AND tree = 1";
4030 
4031  $res = $ilDB->query($query);
4032  $counter = 0;
4033  while($row = $ilDB->fetchObject($res))
4034  {
4035  // Filter recovery folder
4036  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4037  {
4038  continue;
4039  }
4040 
4041  if($counter++ >= $limit)
4042  {
4043  break;
4044  }
4045 
4046  $ref_ids[] = $row->ref_id;
4047  }
4048  return $ref_ids ? $ref_ids : array();
4049  } // End Administrators
4050 
4051  // Check ownership if it is not asked for edit_permission or a create permission
4052  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4053  {
4054  $check_owner = ") ";
4055  }
4056  else
4057  {
4058  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4059  }
4060 
4061  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4062  $ops_id = $ops_ids[0];
4063 
4064  $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4065 
4066  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4067  "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4068  "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4069  $where.
4070  $and.
4071  "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4072  "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4073  $check_owner;
4074 
4075  $res = $ilDB->query($query);
4076  $counter = 0;
4077  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4078  {
4079  if($counter >= $limit)
4080  {
4081  break;
4082  }
4083 
4084  // Filter objects in recovery folder
4085  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4086  {
4087  continue;
4088  }
4089 
4090  // Check deleted, hierarchical access ...
4091  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4092  {
4093  $counter++;
4094  $ref_ids[] = $row->ref_id;
4095  }
4096  }
4097  return $ref_ids ? $ref_ids : array();
4098  }
4099 
4106  function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4107  {
4108  global $tpl, $lng, $ilUser;
4109 
4110  // - take care of html exports (-> see buildLatexImages)
4111  include_once "./Services/Administration/classes/class.ilSetting.php";
4112  $jsMathSetting = new ilSetting("jsMath");
4113  $use_jsmath =
4114  $jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault"))));
4115 
4116  if ($use_jsmath)
4117  {
4118  $info = "";
4119  if (!$tpl->out_jsmath_info)
4120  {
4121  include_once "./classes/class.ilTemplate.php";
4122  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4123  $lng->loadLanguageModule("jsmath");
4124  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4125  $info = $template->get();
4126  $tpl->out_jsmath_info = TRUE;
4127  }
4128  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4129  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4130  }
4131 
4132  // this is a fix for bug5362
4133  $cpos = 0;
4134  $o_start = $a_start;
4135  $o_end = $a_end;
4136  $a_start = str_replace("\\", "", $a_start);
4137  $a_end = str_replace("\\", "", $a_end);
4138  /*$a_start = str_replace("\]", "]", $a_start);
4139  $a_start = str_replace("\[", "[", $a_start);
4140  $a_end = str_replace("\]", "]", $a_end);
4141  $a_end = str_replace("\[", "[", $a_end);
4142  $a_end = str_replace("\/", "/", $a_end);*/
4143 
4144  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4145  {
4146  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4147  {
4148  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4149 
4150  // replace, if tags do not go across div borders
4151  if (!is_int(strpos($tex, "</div>")))
4152  {
4153  if (!$use_jsmath)
4154  {
4155  $a_text = substr($a_text, 0, $spos).
4156  "<img alt=\"".htmlentities($tex)."\" src=\"".$a_cgi."?".
4157  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4158  " />".
4159  substr($a_text, $epos + strlen($a_end));
4160  }
4161  else
4162  {
4163  $tex = $a_start.$tex.$a_end;
4164 //echo "<br>1:".$tex;
4165  $replacement =
4166  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4167  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $tex);
4168  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4169 //echo "<br>2:".htmlentities($replacement);
4170  $a_text = substr($a_text, 0, $spos).
4171  $replacement.
4172  substr($a_text, $epos + strlen($a_end));
4173  }
4174  }
4175  }
4176  $cpos = $spos + 1;
4177  }
4178 
4179  if ($use_jsmath)
4180  {
4181  $a_text = str_replace("[[info]]", $info, $a_text);
4182  }
4183 
4184  $result_text = $a_text;
4185 
4186 // $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4187 // "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4188 // " />'", $a_text);
4189 
4190 //echo htmlentities($a_text);
4191 
4192  return $result_text;
4193  }
4194 
4201  function __insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4202  {
4203  global $tpl, $lng, $ilUser;
4204 
4205 //echo "<br><br>".htmlentities($a_text);
4206 //echo "<br>-".htmlentities($a_start)."-".htmlentities($a_end)."-";
4207 
4208  // - take care of html exports (-> see buildLatexImages)
4209  include_once "./Services/Administration/classes/class.ilSetting.php";
4210  $jsMathSetting = new ilSetting("jsMath");
4211  if ($jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault")))))
4212  {
4213  $info = "";
4214  if (!$tpl->out_jsmath_info)
4215  {
4216  include_once "./classes/class.ilTemplate.php";
4217  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4218  $lng->loadLanguageModule("jsmath");
4219  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4220  $info = $template->get();
4221  $tpl->out_jsmath_info = TRUE;
4222  }
4223  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4224  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4225  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $a_text);
4226  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4227  $result_text = str_replace("[[info]]", $info, $result_text);
4228  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4229  }
4230  else
4231  {
4232  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4233  "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4234  " />'", $a_text);
4235  }
4236 
4237  return $result_text;
4238  }
4239 
4246  function buildLatexImages($a_text, $a_dir ,$a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4247  {
4248  $result_text = $a_text;
4249 
4250  if ($a_cgi != "")
4251  {
4252  while (preg_match('/' . $a_start . '(.*?)' . $a_end . '/ie', $result_text, $found))
4253  {
4254  $cnt = (int) $GLOBALS["teximgcnt"]++;
4255  // get image from cgi and write it to file
4256  $fpr = @fopen($a_cgi."?".rawurlencode($found[1]), "r");
4257  $lcnt = 0;
4258  if ($fpr)
4259  {
4260  while(!feof($fpr))
4261  {
4262  $buf = fread($fpr, 1024);
4263  if ($lcnt == 0)
4264  {
4265  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4266  {
4267  $suffix = "gif";
4268  }
4269  else
4270  {
4271  $suffix = "png";
4272  }
4273  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4274  }
4275  $lcnt++;
4276  fwrite($fpw, $buf);
4277  }
4278  fclose($fpw);
4279  fclose($fpr);
4280  }
4281 
4282  // replace tex-tag
4283  $img_str = "./teximg/img".$cnt.".".$suffix;
4284  $result_text = str_replace($found[0],
4285  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4286  }
4287  }
4288 
4289  return $result_text;
4290  }
4291 
4299  function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE)
4300  {
4301  $result = $txt_output;
4302  $is_html = $this->isHTML($result);
4303  if ($prepare_for_latex_output)
4304  {
4305  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>", URL_TO_LATEX);
4306  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]", URL_TO_LATEX);
4307  }
4308 
4309  // removed: did not work with magic_quotes_gpc = On
4310  if (!$is_html)
4311  {
4312  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4313  $result = preg_replace("/[\n]/", "<br />", $result);
4314  }
4315  else
4316  {
4317  // patch for problems with the <pre> tags in tinyMCE
4318  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4319  {
4320  foreach ($matches[0] as $found)
4321  {
4322  $replacement = "";
4323  if (strpos("\n", $found) === FALSE)
4324  {
4325  $replacement = "\n";
4326  }
4327  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4328  $result = str_replace($found, $removed, $result);
4329  }
4330  }
4331  }
4332  if ($prepare_for_latex_output)
4333  {
4334  // replace special characters to prevent problems with the ILIAS template system
4335  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4336  $result = str_replace("{", "&#123;", $result);
4337  $result = str_replace("}", "&#125;", $result);
4338  $result = str_replace("\\", "&#92;", $result);
4339  }
4340  return $result;
4341  }
4342 
4343 
4350  function int2array ($seconds, $periods = null)
4351  {
4352  // Define time periods
4353  if (!is_array($periods))
4354  {
4355  $periods = array (
4356  'years' => 31536000,
4357  'months' => 2592000,
4358  'days' => 86400,
4359  'hours' => 3600,
4360  'minutes' => 60,
4361  'seconds' => 1
4362  );
4363  }
4364 
4365  // Loop
4366  $seconds = (float) $seconds;
4367  foreach ($periods as $period => $value)
4368  {
4369  $count = floor($seconds / $value);
4370 
4371  if ($count == 0)
4372  {
4373  continue;
4374  }
4375 
4376  $values[$period] = $count;
4377  $seconds = $seconds % $value;
4378  }
4379  // Return
4380  if (empty($values))
4381  {
4382  $values = null;
4383  }
4384 
4385  return $values;
4386  }
4387 
4394  function timearray2string ($duration)
4395  {
4396  global $lng;
4397 
4398  if (!is_array($duration))
4399  {
4400  return false;
4401  }
4402 
4403  foreach ($duration as $key => $value) {
4404 
4405  // Plural
4406  if ($value > 1)
4407  {
4408  $segment_name = $key;
4409  $segment_name = $lng->txt($segment_name);
4410  $segment = $value . ' ' . $segment_name;
4411  }
4412  else
4413  {
4414  $segment_name = substr($key, 0, -1);
4415  $segment_name = $lng->txt($segment_name);
4416  $segment = $value . ' ' . $segment_name;
4417  }
4418 
4419  $array[] = $segment;
4420  }
4421  $len = count($array);
4422 
4423  if ($len>3)
4424  {
4425  $array=array_slice($array,0,(3-$len));
4426  }
4427 
4428  $str = implode(', ', $array);
4429 
4430  return $str;
4431  }
4432 
4433  function getFileSizeInfo()
4434  {
4435  global $lng;
4436 
4437  // get the value for the maximal uploadable filesize from the php.ini (if available)
4438  $umf=get_cfg_var("upload_max_filesize");
4439  // get the value for the maximal post data from the php.ini (if available)
4440  $pms=get_cfg_var("post_max_size");
4441 
4442  // use the smaller one as limit
4443  $max_filesize=min($umf, $pms);
4444  if (!$max_filesize) $max_filesize=max($umf, $pms);
4445 
4446  return $lng->txt("file_notice")." $max_filesize.";
4447  }
4448 
4455  function __extractRefId($role_title)
4456  {
4457 
4458  $test_str = explode('_',$role_title);
4459 
4460  if ($test_str[0] == 'il')
4461  {
4462  $test2 = (int) $test_str[3];
4463  return is_numeric ($test2) ? (int) $test2 : false;
4464  }
4465  return false;
4466  }
4467 
4477  function __extractId($ilias_id, $inst_id)
4478  {
4479 
4480  $test_str = explode('_',$ilias_id);
4481 
4482  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4483  {
4484  $test2 = (int) $test_str[3];
4485  return is_numeric ($test2) ? (int) $test2 : false;
4486  }
4487  return false;
4488  }
4489 
4502  function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4503  {
4504  global $ilDB;
4505 
4506  if(!$a_ids)
4507  {
4508  return array();
4509  }
4510 
4511  // use database to sort user array
4512  $where = "WHERE ".$a_id_name." IN (";
4513  $where .= implode(",", ilUtil::quoteArray($a_ids));
4514  $where .= ") ";
4515 
4516  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4517  $where.
4518  "ORDER BY ".$a_field;
4519 
4520  $res = $ilDB->query($query);
4521  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4522  {
4523  $ids[] = $row->$a_id_name;
4524  }
4525  return $ids ? $ids : array();
4526  }
4527 
4535  function getMySQLTimestamp($a_ts)
4536  {
4537  global $ilDB;
4538 
4539  return $a_ts;
4540  }
4541 
4545  function quoteArray($a_array)
4546  {
4547  global $ilDB;
4548 
4549 
4550  if(!is_array($a_array) or !count($a_array))
4551  {
4552  return array("''");
4553  }
4554 
4555  foreach($a_array as $k => $item)
4556  {
4557  $a_array[$k] = $ilDB->quote($item);
4558  }
4559 
4560  return $a_array;
4561  }
4562 
4569  public static function sendInfo($a_info = "",$a_keep = false)
4570  {
4571  global $tpl;
4572  $tpl->setMessage("info", $a_info, $a_keep);
4573  }
4574 
4581  public static function sendFailure($a_info = "",$a_keep = false)
4582  {
4583  global $tpl;
4584  $tpl->setMessage("failure", $a_info, $a_keep);
4585  }
4586 
4593  public static function sendQuestion($a_info = "",$a_keep = false)
4594  {
4595  global $tpl;
4596  $tpl->setMessage("question", $a_info, $a_keep);
4597  }
4598 
4605  public static function sendSuccess($a_info = "",$a_keep = false)
4606  {
4607  global $tpl;
4608  $tpl->setMessage("success", $a_info, $a_keep);
4609  }
4610 
4611  function infoPanel($a_keep = true)
4612  {
4613  global $tpl,$ilias,$lng;
4614 
4615  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4616  {
4617  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html");
4618  $tpl->setCurrentBlock("infopanel");
4619 
4620  if (!empty($_SESSION["infopanel"]["text"]))
4621  {
4622  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4623  ilFrameTargetInfo::_getFrame("MainContent").
4624  "\">";
4625  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4626  $link .= "</a>";
4627  }
4628 
4629  // deactivated
4630  if (!empty($_SESSION["infopanel"]["img"]))
4631  {
4632  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4633  ilFrameTargetInfo::_getFrame("MainContent").
4634  "\">";
4635  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4636  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4637  $link .= "</a></td>";
4638  }
4639 
4640  $tpl->setVariable("INFO_ICONS",$link);
4641  $tpl->parseCurrentBlock();
4642  }
4643 
4644  //if (!$a_keep)
4645  //{
4646  //session_unregister("infopanel"); // deprecated
4647  unset($_SESSION["infopanel"]);
4648  //}
4649  }
4650 
4651 
4658  function dirsize($directory)
4659  {
4660  $size = 0;
4661  if (!is_dir($directory))
4662  {
4663  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4664  // dirsize of non-existing directory
4665  $size = @filesize($directory);
4666  // END DiskQuota Suppress PHP warning.
4667  return ($size === false) ? -1 : $size;
4668  }
4669  if ($DIR = opendir($directory))
4670  {
4671  while (($dirfile = readdir($DIR)) !== false)
4672  {
4673  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4674  continue;
4675  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4676  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4677  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
4678  {
4679  // BEGIN DiskQuota: dirsize is not a global function anymore
4680  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4681  // END DiskQuota: dirsize is not a global function anymore
4682  if ($dirSize >= 0)
4683  $size += $dirSize;
4684  else return -1;
4685  }
4686  }
4687  closedir($DIR);
4688  }
4689  return $size;
4690  }
4691 
4692  function randomhash()
4693  {
4694  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
4695  }
4696 
4697  public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4698  {
4699  /*
4700  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4701  else $expire = time() - (365*24*60*60);
4702  */
4703  // Temporary fix for feed.php
4704  if(!(bool)$a_set_cookie_invalid) $expire = 0;
4705  else $expire = time() - (365*24*60*60);
4706 
4707  // setcookie() supports 5th parameter
4708  // only for php version 5.2.0 and above
4709  if( version_compare(PHP_VERSION, '5.2.0', '>=') )
4710  {
4711  // PHP version >= 5.2.0
4712  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4713  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
4714  );
4715  }
4716  else
4717  {
4718  // PHP version < 5.2.0
4719  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4720  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE
4721  );
4722  }
4723 
4724  if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
4725  }
4726 
4727  public static function _sanitizeFilemame($a_filename)
4728  {
4729  return strip_tags(self::stripSlashes($a_filename));
4730  }
4731 
4732  public static function _getHttpPath()
4733  {
4734  global $ilIliasIniFile;
4735 
4736  if($_SERVER['SHELL'])
4737  {
4738  return $ilIliasIniFile->readVariable('server', 'http_path');
4739  }
4740  else
4741  {
4742  return ILIAS_HTTP_PATH;
4743  }
4744  }
4745 } // END class.ilUtil
4746 
4747 
4748 ?>