ILIAS  Release_4_0_x_branch Revision 61816
 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;
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 $base.$in_style.$vers;
295  }
296  else
297  {
298  return $base."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 
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  if (is_array($val))
359  {
360  $style = $val["style"];
361  $val = $val["text"]; // mus be last line, since we overwrite
362  }
363 
364  $sty = ($style != "")
365  ? ' style="'.$style.'" '
366  : "";
367 
368  if ($direct_text)
369  {
370  $str .= " <option $sty value=\"".$key."\"";
371  }
372  else
373  {
374  $str .= " <option $sty value=\"".$val."\"";
375  }
376  if (is_array($selected) )
377  {
378  if (in_array($key,$selected))
379  {
380  $str .= " selected=\"selected\"";
381  }
382  }
383  else if ($selected == $key)
384  {
385  $str .= " selected=\"selected\"";
386  }
387 
388  if ($direct_text)
389  {
390  $str .= ">".$val."</option>\n";
391  }
392  else
393  {
394  $str .= ">".$lng->txt($val)."</option>\n";
395  }
396  }
397 
398  $str .= "</select>\n";
399 
400  return $str;
401  }
402 
410  function getSelectName ($selected,$values)
411  {
412  return($values[$selected]);
413  }
414 
424  public static function formCheckbox ($checked,$varname,$value,$disabled = false)
425  {
426  $str = "<input type=\"checkbox\" name=\"".$varname."\"";
427 
428  if ($checked == 1)
429  {
430  $str .= " checked=\"checked\"";
431  }
432 
433  if ($disabled)
434  {
435  $str .= " disabled=\"disabled\"";
436  }
437 
438  $array_var = false;
439 
440  if (substr($varname,-2) == "[]")
441  {
442  $array_var = true;
443  }
444 
445  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
446  if ($array_var)
447  {
448  $varname_id = substr($varname,0,-2)."_".$value;
449  }
450  else
451  {
452  $varname_id = $varname;
453  }
454 
455  // dirty removal of other "[]" in string
456  $varname_id = ereg_replace("\[","_",$varname_id);
457  $varname_id = ereg_replace("\]","",$varname_id);
458 
459  $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
460 
461  return $str;
462  }
463 
473  function formDisabledRadioButton($checked,$varname,$value,$disabled)
474  {
475  if ($disabled) {
476  $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
477  }
478  else {
479  $str = "<input type=\"radio\" name=\"".$varname."\"";
480  }
481  if ($checked == 1)
482  {
483  $str .= " checked=\"checked\"";
484  }
485 
486  $str .= " value=\"".$value."\"";
487  $str .= " id=\"".$value."\" />\n";
488 
489  return $str;
490 
491  }
492 
493 
502  function formRadioButton($checked,$varname,$value)
503  {
504  $str = "<input type=\"radio\" name=\"".$varname."\"";
505  if ($checked == 1)
506  {
507  $str .= " checked=\"checked\"";
508  }
509 
510  $str .= " value=\"".$value."\"";
511 
512  $str .= " id=\"".$value."\" />\n";
513 
514  return $str;
515  }
516 
517 
526  function formInput($varname,$value,$disabled = false)
527  {
528 
529  $str = "<input type=\"input\" name=\"".$varname."\"";
530  if ($disabled)
531  {
532  $str .= " disabled";
533  }
534 
535  $str .= " value=\"".$value."\"";
536 
537  $str .= " id=\"".$value."\" />\n";
538 
539  return $str;
540  }
541 
542 
547  function checkInput ($vars)
548  {
549  // TO DO:
550  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
551  }
552 
558  function setPathStr ($a_path)
559  {
560  if ("" != $a_path && "/" != substr($a_path, -1))
561  {
562  $a_path .= "/";
563  //$a_path = substr($a_path,1);
564  }
565 
566  //return getcwd().$a_path;
567  return $a_path;
568  }
569 
580  function switchColor ($a_num,$a_css1,$a_css2)
581  {
582  if (!($a_num % 2))
583  {
584  return $a_css1;
585  }
586  else
587  {
588  return $a_css2;
589  }
590  }
591 
601  function showTabs($a_hl, $a_o)
602  {
603  global $lng;
604 
605  $tpltab = new ilTemplate("tpl.tabs.html", true, true);
606 
607  for ($i=1; $i<=4; $i++)
608  {
609  $tpltab->setCurrentBlock("tab");
610  if ($a_hl == $i)
611  {
612  $tabtype = "tabactive";
613  $tab = $tabtype;
614  }
615  else
616  {
617  $tabtype = "tabinactive";
618  $tab = "tab";
619  }
620 
621  switch ($i)
622  {
623  case 1:
624  $txt = $lng->txt("view_content");
625  break;
626  case 2:
627  $txt = $lng->txt("edit_properties");
628  break;
629  case 3:
630  $txt = $lng->txt("perm_settings");
631  break;
632  case 4:
633  $txt = $lng->txt("show_owner");
634  break;
635  } // switch
636  $tpltab->setVariable("CONTENT", $txt);
637  $tpltab->setVariable("TABTYPE", $tabtype);
638  $tpltab->setVariable("TAB", $tab);
639  $tpltab->setVariable("LINK", $a_o["LINK".$i]);
640  $tpltab->parseCurrentBlock();
641  }
642 
643  return $tpltab->get();
644  }
645 
646 
647 
654  function checkFormEmpty ($emptyFields)
655  {
656 
657  $feedback = "";
658 
659  foreach ($emptyFields as $key => $val)
660  {
661  if ($val == "") {
662  if ($feedback != "") $feedback .= ", ";
663  $feedback .= $key;
664  }
665  }
666 
667  return $feedback;
668  }
669 
692  function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
693  {
694  $LinkBar = "";
695 
696  $layout_link = "";
697  $layout_prev = "&lt;&lt;";
698  $layout_next = "&gt;&gt;";
699 
700  // layout options
701  if (count($ALayout > 0))
702  {
703  if ($ALayout["link"])
704  {
705  $layout_link = " class=\"".$ALayout["link"]."\"";
706  }
707 
708  if ($ALayout["prev"])
709  {
710  $layout_prev = $ALayout["prev"];
711  }
712 
713  if ($ALayout["next"])
714  {
715  $layout_next = $ALayout["next"];
716  }
717  }
718 
719  // show links, if hits greater limit
720  // or offset > 0 (can be > 0 due to former setting)
721  if ($AHits > $ALimit || $AOffset > 0)
722  {
723  if (!empty($AParams))
724  {
725  foreach ($AParams as $key => $value)
726  {
727  $params.= $key."=".$value."&";
728  }
729  }
730  // if ($params) $params = substr($params,0,-1);
731  if(strpos($AScript,'&'))
732  {
733  $link = $AScript."&".$params.$prefix."offset=";
734  }
735  else
736  {
737  $link = $AScript."?".$params.$prefix."offset=";
738  }
739 
740  // ?bergehe "zurck"-link, wenn offset 0 ist.
741  if ($AOffset >= 1)
742  {
743  $prevoffset = $AOffset - $ALimit;
744  if ($prevoffset < 0) $prevoffset = 0;
745  $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
746  }
747 
748  // Ben?tigte Seitenzahl kalkulieren
749  $pages=intval($AHits/$ALimit);
750 
751  // Wenn ein Rest bleibt, addiere eine Seite
752  if (($AHits % $ALimit))
753  $pages++;
754 
755  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
756  // if ($AOffset != 0) {
757 
758  // ansonsten zeige Links zu den anderen Seiten an
759  for ($i = 1 ;$i <= $pages ; $i++)
760  {
761  $newoffset=$ALimit*($i-1);
762 
763  if ($newoffset == $AOffset)
764  {
765  $LinkBar .= "[".$i."] ";
766  }
767  else
768  {
769  $LinkBar .= '<a '.$layout_link.' href="'.
770  $link.$newoffset.'">['.$i.']</a> ';
771  }
772  }
773  // }
774 
775  // Checken, ob letze Seite erreicht ist
776  // Wenn nicht, gebe einen "Weiter"-Link aus
777  if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
778  {
779  $newoffset=$AOffset+$ALimit;
780  $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
781  }
782 
783  return $LinkBar;
784  }
785  else
786  {
787  return false;
788  }
789  }
790 
800  function makeClickable($a_text, $detectGotoLinks = false)
801  {
802  // New code, uses MediaWiki Sanitizer
803  $ret = $a_text;
804 
805  // www-URL ohne ://-Angabe
806  $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
807  "\\1http://\\2\\3", $ret);
808 
809  // ftp-URL ohne ://-Angabe
810  $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
811  "\\1ftp://\\2\\3", $ret);
812 
813  // E-Mail (this does not work as expected, users must add mailto: manually)
814  //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
815  // "mailto:\\1", $ret);
816 
817  // mask existing image tags
818  $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
819 
820  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
821  $parser = new ilMWParserAdapter();
822  $ret = $parser->replaceFreeExternalLinks($ret);
823 
824  // unmask existing image tags
825  $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
826 
827  // Should be Safe
828 
829  if ($detectGotoLinks)
830  // replace target blank with self and text with object title.
831  {
832  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
833 // echo htmlentities($regExp);
834  $ret = preg_replace_callback(
835  "/".$regExp."/i",
836  array("ilUtil", "replaceLinkProperties"),
837  $ret);
838 
839  // Static links
840  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
841 // echo htmlentities($regExp);
842  $ret = preg_replace_callback(
843  "/".$regExp."/i",
844  array("ilUtil", "replaceLinkProperties"),
845  $ret);
846  }
847 
848  return($ret);
849  }
850 
862  function replaceLinkProperties ($matches)
863  {
864  $link = $matches[0];
865  $ref_id = $matches[2];
866 
867  if ($ref_id > 0)
868  {
869  $obj_id = ilObject::_lookupObjId($ref_id);
870  if ($obj_id > 0)
871  {
872  $title = ilObject::_lookupTitle($obj_id);
873  $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
874  }
875  }
876  return $link;
877  }
878 
895  function StopWatch($begin = -1)
896  {
897  $m = explode(" ",microtime());
898  $m = $m[0] + $m[1];
899 
900  if ($begin != -1)
901  {
902  $m = $m - $begin;
903  }
904 
905  return($m);
906  }
907 
924  function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
925  {
926  global $lng;
927 
928  $disabled = '';
929  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
930  {
931  $disabled = 'disabled="disabled" ';
932  }
933 
934  $now = getdate();
935  if (!$emptyoption)
936  {
937  if (!strlen($year)) $year = $now["year"];
938  if (!strlen($month)) $month = $now["mon"];
939  if (!strlen($day)) $day = $now["mday"];
940  }
941 
942  $year = (int) $year;
943  $month = (int) $month;
944  $day = (int) $day;
945 
946  // build day select
947 
948  $sel_day .= '<select ';
949  if(isset($a_further_options['select_attributes']))
950  {
951  foreach($a_further_options['select_attributes'] as $name => $value)
952  {
953  $sel_day .= ($name.'="'.$value.'" ');
954  }
955  }
956 
957  $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
958 
959  if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
960  for ($i = 1; $i <= 31; $i++)
961  {
962  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
963  }
964  $sel_day .= "</select>\n";
965  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
966 
967  // build month select
968  $sel_month = '<select ';
969  if(isset($a_further_options['select_attributes']))
970  {
971  foreach($a_further_options['select_attributes'] as $name => $value)
972  {
973  $sel_month .= ($name.'="'.$value.'" ');
974  }
975  }
976  $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
977 
978  if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
979  for ($i = 1; $i <= 12; $i++)
980  {
981  if($a_long_month)
982  {
983  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
984  }
985  else
986  {
987  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
988  }
989  }
990  $sel_month .= "</select>\n";
991  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
992 
993  // build year select
994  $sel_year = '<select ';
995  if(isset($a_further_options['select_attributes']))
996  {
997  foreach($a_further_options['select_attributes'] as $name => $value)
998  {
999  $sel_year .= ($name.'="'.$value.'" ');
1000  }
1001  }
1002  $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
1003  if ((strlen($startyear) == 0) || ($startyear > $year))
1004  {
1005  if (!$emptyoption || $year != 0) $startyear = $year - 5;
1006  }
1007 
1008  if(($year + 5) < (date('Y',time()) + 5))
1009  {
1010  $end_year = date('Y',time()) + 5;
1011  }
1012  else
1013  {
1014  $end_year = $year + 5;
1015  }
1016 
1017  if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
1018  for ($i = $startyear; $i <= $end_year; $i++)
1019  {
1020  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
1021  }
1022  $sel_year .= "</select>\n";
1023  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
1024 
1025  //$dateformat = $lng->text["lang_dateformat"];
1026  $dateformat = "d-m-Y";
1027  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1028  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1029  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1030  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1031  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1032  return $dateformat;
1033  }
1034 
1051  function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1052  {
1053  global $lng;
1054 
1055  $minute_steps = 1;
1056  $disabled = '';
1057  if(count($a_further_options))
1058  {
1059  if(isset($a_further_options['minute_steps']))
1060  {
1061  $minute_steps = $a_further_options['minute_steps'];
1062  }
1063  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1064  {
1065  $disabled = 'disabled="disabled" ';
1066  }
1067  }
1068 
1069  if ($a_use_default and !strlen("$hour$minute$second")) {
1070  $now = localtime();
1071  $hour = $now[2];
1072  $minute = $now[1];
1073  $second = $now[0];
1074  } else {
1075  $hour = (int)$hour;
1076  $minute = (int)$minute;
1077  $second = (int)$second;
1078  }
1079  // build hour select
1080  $sel_hour = '<select ';
1081  if(isset($a_further_options['select_attributes']))
1082  {
1083  foreach($a_further_options['select_attributes'] as $name => $value)
1084  {
1085  $sel_hour .= $name.'='.$value.' ';
1086  }
1087  }
1088  $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\">\n";
1089 
1090  for ($i = 0; $i <= 23; $i++)
1091  {
1092  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1093  }
1094  $sel_hour .= "</select>\n";
1095  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1096 
1097  // build minutes select
1098  $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
1099 
1100  for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1101  {
1102  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1103  }
1104  $sel_minute .= "</select>\n";
1105  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1106 
1107  if (!$short) {
1108  // build seconds select
1109  $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\">\n";
1110 
1111  for ($i = 0; $i <= 59; $i++)
1112  {
1113  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1114  }
1115  $sel_second .= "</select>\n";
1116  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1117  }
1118  $timeformat = $lng->text["lang_timeformat"];
1119  if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1120  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1121  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1122  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1123  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1124  if ($short) {
1125  $timeformat = preg_replace("/%%s/", "", $timeformat);
1126  } else {
1127  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1128  }
1129  return $timeformat;
1130  }
1131 
1132  /*
1133  * This preg-based function checks whether an e-mail address is formally valid.
1134  * It works with all top level domains including the new ones (.biz, .info, .museum etc.)
1135  * and the special ones (.arpa, .int etc.)
1136  * as well as with e-mail addresses based on IPs (e.g. webmaster@123.45.123.45)
1137  * Valid top level domains: http://data.iana.org/TLD/tlds-alpha-by-domain.txt
1138  * @author Unknown <mail@philipp-louis.de> (source: http://www.php.net/preg_match)
1139  * @access public
1140  * @param string email address
1141  * @return boolean true if valid
1142  */
1143  function is_email($a_email)
1144  {
1145  // BEGIN Mail: If possible, use PearMail to validate e-mail address
1146  global $ilErr, $ilias;
1147 
1148  // Note the use of @include_once here. We need this, because
1149  // inclusion fails when the function is_email is called from setup.php.
1150  $successfulInclude = @include_once ('Services/Mail/classes/class.ilMail.php');
1151 
1152  // additional checks for include and ilias object are needed,
1153  // otherwise setup will fail with this if branch
1154  if ($successfulInclude && is_object($ilias) && ilMail::_usePearMail())
1155  {
1156  require_once 'Mail/RFC822.php';
1157  $parser = &new Mail_RFC822();
1159  try {
1160  $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1161  if (! is_a($addresses, 'PEAR_Error') &&
1162  count($addresses) == 1 && $addresses[0]->host != 'ilias')
1163  {
1164  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1165  return true;
1166  }
1167  } catch (Exception $e) {
1168  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1169  return false;
1170  }
1171  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1172  return false;
1173  }
1174  else
1175  {
1176  $tlds = strtolower(
1177  "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|".
1178  "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|".
1179  "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|".
1180  "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|".
1181  "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|".
1182  "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|".
1183  "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|".
1184  "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|".
1185  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1186 
1187  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));
1188  }
1189  // END Mail: If possible, use PearMail to validate e-mail address
1190  }
1191 
1192  /*
1193  * validates a password
1194  * @access public
1195  * @param string password
1196  * @return boolean true if valid
1197  */
1198  function isPassword($a_passwd,&$custom_error = null)
1199  {
1200  global $lng;
1201  $a_custom_error = '';
1202 
1203 
1204  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1205  $security = ilSecuritySettings::_getInstance();
1206 
1207  // differentiate the account security mode (ilias standard/customized)
1208  if( $security->getAccountSecurityMode() == ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1209  {
1210  // check if passwd not empty
1211  if( $a_passwd == '' )
1212  {
1213  $custom_error = $lng->txt('password_empty');
1214  return false;
1215  }
1216  // check if passwd not to short
1217  if( $security->getPasswordMinLength() > 0 &&
1218  strlen($a_passwd) < $security->getPasswordMinLength() )
1219  {
1220  $custom_error = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1221  return false;
1222  }
1223  // check if passwd not to long
1224  elseif( $security->getPasswordMaxLength() > 0 &&
1225  strlen($a_passwd) > $security->getPasswordMaxLength() )
1226  {
1227  $custom_error = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1228  return false;
1229  }
1230  else
1231  {
1232  // if passwd must contains Chars and Numbers
1233  if( $security->isPasswordCharsAndNumbersEnabled() )
1234  {
1235  $reg = '/[A-Za-z]+/';
1236  if( !preg_match($reg,$a_passwd) )
1237  {
1238  $custom_error = $lng->txt('password_must_chars_and_numbers');
1239  return false;
1240  }
1241 
1242  $reg = '/[0-9]+/';
1243  if( !preg_match($reg,$a_passwd) )
1244  {
1245  $custom_error = $lng->txt('password_must_chars_and_numbers');
1246  return false;
1247  }
1248 
1249  }
1250  else
1251  {
1252  // use ILIAS-Standard
1253  if (!preg_match("/^[A-Za-z0-9]+/", $a_passwd))
1254  {
1255  return false;
1256  }
1257 
1258  }
1259  // if passwd must contain Special-Chars
1260  if( $security->isPasswordSpecialCharsEnabled() )
1261  {
1262  #$reg = '/[_\.\+\?\#\-\*\@!\$\%\~]+/';
1263  $reg = '/[_\.\+\?\#\-\*\@!\$\%\/\:\;\~]+/';
1264 
1265  if( !preg_match($reg,$a_passwd) )
1266  {
1267  $custom_error = $lng->txt('password_must_special_chars');
1268  return false;
1269  }
1270  }
1271  else
1272  {
1273  // use ILIAS-Standard
1274  if (!preg_match("/^[_\.\+\?\#\-\*\@!\$\%\~]+/", $a_passwd))
1275  {
1276  return false;
1277  }
1278  }
1279  }
1280  }
1281  else
1282  {
1283  if (empty($a_passwd))
1284  {
1285  return false;
1286  }
1287  if (strlen($a_passwd) < 6)
1288  {
1289  return false;
1290  }
1291  // due to bug in php does not work
1292  //if (!ereg("^[A-Za-z0-9_\.\+\-\*\@!\$\%\~]+$", $a_passwd))
1293 
1294  if (!preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~]+$/", $a_passwd))
1295  {
1296  return false;
1297  }
1298  }
1299 
1300  return true;
1301  }
1302 
1310  {
1311  global $lng;
1312 
1313  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1314  $security = ilSecuritySettings::_getInstance();
1315  $ok = '';
1316  if( $security->getAccountSecurityMode() == ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1317  {
1318  if( $security->isPasswordCharsAndNumbersEnabled() )
1319  {
1320  $ok .= 'A-Za-z0-9';
1321  }
1322  else $ok .= 'A-Za-z0-9';
1323  if( $security->isPasswordSpecialCharsEnabled() )
1324  {
1325  $ok .= '_.+?#-*@!$%/:;~';
1326  }
1327  else $ok .= '_.+?#-*@!$%~';
1328  }
1329  else
1330  {
1331  $ok .= 'A-Za-z0-9_.+?#-*@!$%~';
1332  }
1333 
1334  return sprintf($lng->txt('password_allow_chars'), $ok);
1335  }
1336 
1337  /*
1338  * validates a login
1339  * @access public
1340  * @param string login
1341  * @return boolean true if valid
1342  */
1343  function isLogin($a_login)
1344  {
1345  if (empty($a_login))
1346  {
1347  return false;
1348  }
1349 
1350  if (strlen($a_login) < 3)
1351  {
1352  return false;
1353  }
1354 
1355  // FIXME - If ILIAS is configured to use RFC 822
1356  // compliant mail addresses we should not
1357  // allow the @ character.
1358  if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1359  {
1360  return false;
1361  }
1362 
1363  return true;
1364  }
1365 
1377  public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1378  $a_keep_extension = false)
1379  {
1380  include_once("./Services/Utilities/classes/class.ilStr.php");
1381  if (ilStr::strLen($a_str) > $a_len)
1382  {
1383  if ($a_next_blank)
1384  {
1385  $len = ilStr::strPos($a_str, " ", $a_len);
1386  }
1387  else
1388  {
1389  $len = $a_len;
1390  }
1391  // BEGIN WebDAV
1392  // - Shorten names in the middle, before the filename extension
1393  // Workaround for Windows WebDAV Client:
1394  // Use the unicode ellipsis symbol for shortening instead of
1395  // three full stop characters.
1396  if ($a_keep_extension)
1397  {
1398  $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1399  }
1400  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1401  {
1402  $a_str = ilStr::subStr($a_str,0,$len);
1403  if ($a_dots)
1404  {
1405  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1406  }
1407  }
1408  else
1409  {
1410  if ($a_dots)
1411  {
1412  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1413  }
1414  else
1415  {
1416  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1417  }
1418  }
1419  }
1420 
1421  return $a_str;
1422  }
1423 
1432  function shortenWords($a_str, $a_len = 30, $a_dots = true)
1433  {
1434  include_once("./Services/Utilities/classes/class.ilStr.php");
1435  $str_arr = explode(" ", $a_str);
1436 
1437  for ($i = 0; $i < count($str_arr); $i++)
1438  {
1439  if (ilStr::strLen($str_arr[$i]) > $a_len)
1440  {
1441  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1442  if ($a_dots)
1443  {
1444  $str_arr[$i].= "...";
1445  }
1446  }
1447  }
1448 
1449  return implode($str_arr, " ");
1450  }
1451 
1459  function attribsToArray($a_str)
1460  {
1461  $attribs = array();
1462  while (is_int(strpos($a_str, "=")))
1463  {
1464  $eq_pos = strpos($a_str, "=");
1465  $qu1_pos = strpos($a_str, "\"");
1466  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1467  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1468  {
1469  $var = trim(substr($a_str, 0, $eq_pos));
1470  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1471  $attribs[$var] = $val;
1472  $a_str = substr($a_str, $qu2_pos + 1);
1473  }
1474  else
1475  {
1476  $a_str = "";
1477  }
1478  }
1479  return $attribs;
1480  }
1481 
1491  function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1492  {
1493  // check if arguments are directories
1494  if (!@is_dir($a_sdir) or
1495  !@is_dir($a_tdir))
1496  {
1497  return FALSE;
1498  }
1499 
1500  // read a_sdir, copy files and copy directories recursively
1501  $dir = opendir($a_sdir);
1502 
1503  while($file = readdir($dir))
1504  {
1505  if ($file != "." and
1506  $file != "..")
1507  {
1508  // directories
1509  if (@is_dir($a_sdir."/".$file))
1510  {
1511  if (!@is_dir($a_tdir."/".$file))
1512  {
1513  if (!ilUtil::makeDir($a_tdir."/".$file))
1514  return FALSE;
1515 
1516  //chmod($a_tdir."/".$file, 0775);
1517  }
1518 
1519  if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1520  {
1521  return FALSE;
1522  }
1523  }
1524 
1525  // files
1526  if (@is_file($a_sdir."/".$file))
1527  {
1528  if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1529  {
1530  return FALSE;
1531  }
1532  if ($preserveTimeAttributes)
1533  touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1534  }
1535  }
1536  }
1537  return TRUE;
1538  }
1539 
1547  function getWebspaceDir($mode = "filesystem")
1548  {
1549  global $ilias;
1550 
1551  if ($mode == "filesystem")
1552  {
1553  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1554  }
1555  else
1556  {
1557  if (defined("ILIAS_MODULE"))
1558  {
1559  return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1560  }
1561  else
1562  {
1563  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1564  }
1565  }
1566 
1567  //return $ilias->ini->readVariable("server","webspace_dir");
1568  }
1569 
1573  function getDataDir()
1574  {
1575  return CLIENT_DATA_DIR;
1576  //global $ilias;
1577 
1578  //return $ilias->ini->readVariable("server", "data_dir");
1579  }
1580 
1588  function getUsersOnline($a_user_id = 0)
1589  {
1590  include_once("./Services/User/classes/class.ilObjUser.php");
1591  return ilObjUser::_getUsersOnline($a_user_id);
1592  }
1593 
1602  function getAssociatedUsersOnline($a_user_id)
1603  {
1604  include_once("./Services/User/classes/class.ilObjUser.php");
1605  return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1606  }
1607 
1613  function ilTempnam()
1614  {
1615  $temp_path = ilUtil::getDataDir() . "/temp";
1616  if (!is_dir($temp_path))
1617  {
1618  ilUtil::createDirectory($temp_path);
1619  }
1620  $temp_name = tempnam($temp_path, "tmp");
1621  // --->
1622  // added the following line because tempnam creates a backslash on some
1623  // Windows systems which leads to problems, because the "...\tmp..." can be
1624  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1625  // even under windows (Helmut Schottmüller, 2005-08-31)
1626  $temp_name = str_replace("\\", "/", $temp_name);
1627  // --->
1628  unlink($temp_name);
1629  return $temp_name;
1630  }
1631 
1637  function createDirectory($a_dir, $a_mod = 0755)
1638  {
1639  ilUtil::makeDir($a_dir);
1640  //@mkdir($a_dir);
1641  //@chmod($a_dir, $a_mod);
1642  }
1643 
1644 
1651  function unzip($a_file, $overwrite = false)
1652  {
1653  $pathinfo = pathinfo($a_file);
1654  $dir = $pathinfo["dirname"];
1655  $file = $pathinfo["basename"];
1656 
1657  // unzip
1658  $cdir = getcwd();
1659  chdir($dir);
1660  $unzip = PATH_TO_UNZIP;
1661 
1662  // workaround for unzip problem (unzip of subdirectories fails, so
1663  // we create the subdirectories ourselves first)
1664  // get list
1665  $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1666  $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1667  $zdirs = array();
1668 
1669  foreach($arr as $line)
1670  {
1671  if(is_int(strpos($line, "/")))
1672  {
1673  $zdir = substr($line, 0, strrpos($line, "/"));
1674  $nr = substr_count($zdir, "/");
1675  //echo $zdir." ".$nr."<br>";
1676  while ($zdir != "")
1677  {
1678  $nr = substr_count($zdir, "/");
1679  $zdirs[$zdir] = $nr; // collect directories
1680  //echo $dir." ".$nr."<br>";
1681  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1682  }
1683  }
1684  }
1685 
1686  asort($zdirs);
1687 
1688  foreach($zdirs as $zdir => $nr) // create directories
1689  {
1690  ilUtil::createDirectory($zdir);
1691  }
1692 
1693  // real unzip
1694  if (!$overwrite)
1695  {
1696  $unzipcmd = ilUtil::escapeShellArg($file);
1697  }
1698  else
1699  {
1700  $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1701  }
1702  ilUtil::execQuoted($unzip, $unzipcmd);
1703 
1704  chdir($cdir);
1705  }
1706 
1710  function zip($a_dir, $a_file, $compress_content = false)
1711  {
1712  $cdir = getcwd();
1713 
1714  if($compress_content)
1715  {
1716  $a_dir .="/*";
1717  $pathinfo = pathinfo($a_dir);
1718  chdir($pathinfo["dirname"]);
1719  }
1720 
1721  $pathinfo = pathinfo($a_file);
1722  $dir = $pathinfo["dirname"];
1723  $file = $pathinfo["basename"];
1724 
1725  if(!$compress_content)
1726  {
1727  chdir($dir);
1728  }
1729 
1730  $zip = PATH_TO_ZIP;
1731 
1732  if(!$zip)
1733  {
1734  chdir($cdir);
1735  return false;
1736  }
1737 
1738  if (is_array($a_dir))
1739  {
1740  $source = "";
1741  foreach($a_dir as $dir)
1742  {
1743  $name = basename($dir);
1744  $source.= " ".ilUtil::escapeShellArg($name);
1745  }
1746  }
1747  else
1748  {
1749  $name = basename($a_dir);
1750  if (trim($name) != "*")
1751  {
1752  $source = ilUtil::escapeShellArg($name);
1753  }
1754  else
1755  {
1756  $source = $name;
1757  }
1758  }
1759 
1760  $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1761  ilUtil::execQuoted($zip, $zipcmd);
1762  chdir($cdir);
1763  return true;
1764  }
1765 
1766  function CreateIsoFromFolder($a_dir, $a_file)
1767  {
1768  $cdir = getcwd();
1769 
1770  $pathinfo = pathinfo($a_dir);
1771  chdir($pathinfo["dirname"]);
1772 
1773  $pathinfo = pathinfo($a_file);
1774  $dir = $pathinfo["dirname"];
1775  $file = $pathinfo["basename"];
1776 
1777  $mkisofs = PATH_TO_MKISOFS;
1778  if(!$mkisofs)
1779  {
1780  chdir($cdir);
1781  return false;
1782  }
1783 
1784  $name = basename($a_dir);
1785 
1786  $source = ilUtil::escapeShellArg($name);
1787 
1788  $zipcmd = $mkisofs." -r -J -o ".$a_file." ".$source;
1789  exec($zipcmd);
1790  chdir($cdir);
1791  return true;
1792  }
1793 
1797  function getConvertCmd()
1798  {
1799  return PATH_TO_CONVERT;
1800  //global $ilias;
1801 
1802  //return $ilias->getSetting("convert_path");
1803  }
1804 
1812  function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
1813  $a_background_color = "")
1814  {
1815  global $ilUser;
1816 
1817  $format_str = ($a_target_format != "")
1818  ? strtoupper($a_target_format).":"
1819  : "";
1820  $geometry = ($a_geometry != "")
1821  ? " -geometry ".$a_geometry."x".$a_geometry." "
1822  : "";
1823  $bg_color = ($a_background_color != "")
1824  ? " -background color ".$a_background_color." "
1825  : "";
1826  $convert_cmd = ilUtil::getConvertCmd()." ".
1827  ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
1828 
1829  system($convert_cmd);
1830  }
1831 
1840  function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
1841  {
1842  if ($a_constrain_prop)
1843  {
1844  $size = " -geometry ".$a_width."x".$a_height." ";
1845  }
1846  else
1847  {
1848  $size = " -resize ".$a_width."x".$a_height."! ";
1849  }
1850  $convert_cmd = ilUtil::getConvertCmd()." ".
1851  ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
1852 
1853  system($convert_cmd);
1854  }
1855 
1859  function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0)
1860  {
1861  $img = '<img src="'.$a_src.'"';
1862  if ($a_alt != "")
1863  {
1864  $img.= ' alt="'.$a_alt.'" title="'.$a_alt.'"';
1865  }
1866  if ($a_width != "")
1867  {
1868  $img.= ' width="'.$a_width.'"';
1869  }
1870  if ($a_height != "")
1871  {
1872  $img.= ' height="'.$a_height.'"';
1873  }
1874  $img.= ' border="'.(int) $a_border.'"/>';
1875 
1876  return $img;
1877  }
1878 
1884  function html2pdf($html, $pdf_file)
1885  {
1886  $html_file = str_replace(".pdf",".html",$pdf_file);
1887 
1888  $fp = fopen( $html_file ,"wb");
1889  fwrite($fp, $html);
1890  fclose($fp);
1891 
1892  ilUtil::htmlfile2pdf($html_file,$pdf_file);
1893  }
1894 
1900  function htmlfile2pdf($html_file, $pdf_file)
1901  {
1902 
1903  $htmldoc_path = PATH_TO_HTMLDOC;
1904 
1905  $htmldoc = $htmldoc_path." ";
1906  $htmldoc .= "--no-toc ";
1907  $htmldoc .= "--no-jpeg ";
1908  $htmldoc .= "--webpage ";
1909  $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
1910  $htmldoc .= "--bodyfont Arial ";
1911  $htmldoc .= "--charset iso-8859-15 ";
1912  $htmldoc .= "--color ";
1913  $htmldoc .= "--size A4 "; // --landscape
1914  $htmldoc .= "--format pdf ";
1915  $htmldoc .= "--footer ... ";
1916  $htmldoc .= "--header ... ";
1917  $htmldoc .= "--left 60 ";
1918  // $htmldoc .= "--right 200 ";
1919  $htmldoc .= $html_file;
1920  exec($htmldoc);
1921 
1922  }
1923 
1927  public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
1928  {
1929  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
1930  // $mime = "application/octet-stream"; // or whatever the mime type is
1931 
1932  include_once './classes/class.ilHTTPS.php';
1933 
1934  //if (isset($_SERVER["HTTPS"]))
1935  if(ilHTTPS::getInstance()->isDetected())
1936  {
1937 
1938  // Added different handling for IE and HTTPS => send pragma after content informations
1942  #header("Pragma: ");
1943  #header("Cache-Control: ");
1944  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1945  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1946  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1947  #header("Cache-Control: post-check=0, pre-check=0", false);
1948  }
1949  else if ($disposition == "attachment")
1950  {
1951  header("Cache-control: private");
1952  }
1953  else
1954  {
1955  header("Cache-Control: no-cache, must-revalidate");
1956  header("Pragma: no-cache");
1957  }
1958 
1959  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
1960 
1961  if (strlen($charset))
1962  {
1963  $charset = "; charset=$charset";
1964  }
1965  header("Content-Type: $mime$charset");
1966  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
1967  header("Content-Description: ".$ascii_filename);
1968  header("Content-Length: ".(string)(strlen($a_data)));
1969 
1970  //if($_SERVER['HTTPS'])
1971  if( ilHTTPS::getInstance()->isDetected() )
1972  {
1973  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1974  header('Pragma: public');
1975  }
1976 
1977  header("Connection: close");
1978  echo $a_data;
1979  exit;
1980  }
1981 
1982  // BEGIN WebDAV: Show file in browser or provide it as attachment
1988  function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false)
1989  {
1990  if ($isInline) {
1991  $disposition = "inline"; // "inline" to view file in browser
1992  } else {
1993  $disposition = "attachment"; // "attachment" to download to hard disk
1994  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
1995  }
1996  // END WebDAV: Show file in browser or provide it as attachment
1997 
1998  if(strlen($a_mime))
1999  {
2000  $mime = $a_mime;
2001  }
2002  else
2003  {
2004  $mime = "application/octet-stream"; // or whatever the mime type is
2005  }
2006  // BEGIN WebDAV: Removed broken HTTPS code.
2007  // END WebDAV: Removed broken HTTPS code.
2008  if ($disposition == "attachment")
2009  {
2010  header("Cache-control: private");
2011  }
2012  else
2013  {
2014  header("Cache-Control: no-cache, must-revalidate");
2015  header("Pragma: no-cache");
2016  }
2017 
2018  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2019 
2020  header("Content-Type: $mime");
2021  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2022  header("Content-Description: ".$ascii_filename);
2023  header("Content-Length: ".(string)(filesize($a_file)));
2024 
2025  include_once './classes/class.ilHTTPS.php';
2026  //if($_SERVER['HTTPS'])
2027  if(ilHTTPS::getInstance()->isDetected())
2028  {
2029  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2030  header('Pragma: public');
2031  }
2032 
2033  header("Connection: close");
2034  ilUtil::readFile( $a_file );
2035  if ($removeAfterDelivery)
2036  {
2037  unlink ($a_file);
2038  }
2039  exit;
2040  }
2041 
2042 
2049  function readFile($a_file)
2050  {
2051  $chunksize = 1*(1024*1024); // how many bytes per chunk
2052  $buffer = '';
2053  $handle = fopen($a_file, 'rb');
2054  if ($handle === false)
2055  {
2056  return false;
2057  }
2058  while (!feof($handle))
2059  {
2060  $buffer = fread($handle, $chunksize);
2061  print $buffer;
2062  }
2063  return fclose($handle);
2064  }
2065 
2071  function getASCIIFilename($a_filename)
2072  {
2073  // The filename must be converted to ASCII, as of RFC 2183,
2074  // section 2.3.
2075  // Despite the RFC, Internet Explorer on Windows supports
2076  // ISO 8895-1 encoding for the file name. We use this fact, to
2077  // produce a better result, if the user uses IE.
2078 
2090 
2091  $user_agent = strtolower($_SERVER["HTTP_USER_AGENT"]);
2092  if ((is_integer(strpos($user_agent, "msie"))) && is_integer(strpos($user_agent, "win")))
2093  {
2096 
2097  $ascii_filename = utf8_decode($a_filename);
2098  }
2099  else
2100  {
2103 
2104  $ascii_filename = htmlentities($a_filename,ENT_NOQUOTES,'UTF-8');
2105  $ascii_filename = preg_replace('/\&(.)[^;]*;/','\\1', $ascii_filename);
2106  $ascii_filename = preg_replace('/[\x7f-\xff]/','_', $ascii_filename);
2107  }
2108 
2109  // OS do not allow the following characters in filenames:
2110  // \/:*?"<>|
2111  //if (is_integer(strpos($user_agent, "win")))
2112  {
2113  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/','_', $ascii_filename);
2114  }
2115 
2116  return $ascii_filename;
2117  }
2118 
2119  /*
2120  * Encodes HTML entities outside of HTML tags
2121  */
2122  function htmlentitiesOutsideHTMLTags($htmlText)
2123  {
2124  $matches = Array();
2125  $sep = '###HTMLTAG###';
2126 
2127  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2128  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2129  $tmp = explode($sep, $tmp);
2130 
2131  for ($i=0; $i<count($tmp); $i++)
2132  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2133 
2134  $tmp = join($sep, $tmp);
2135 
2136  for ($i=0; $i<count($matches[0]); $i++)
2137  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2138 
2139  return $tmp;
2140  }
2141 
2145  function getJavaPath()
2146  {
2147  return PATH_TO_JAVA;
2148  //global $ilias;
2149 
2150  //return $ilias->getSetting("java_path");
2151  }
2152 
2157  function appendUrlParameterString($a_url, $a_par)
2158  {
2159  $url = (is_int(strpos($a_url, "?")))
2160  ? $a_url."&".$a_par
2161  : $a_url."?".$a_par;
2162 
2163  return $url;
2164  }
2165 
2180  function makeDir($a_dir)
2181  {
2182  $a_dir = trim($a_dir);
2183 
2184  // remove trailing slash (bugfix for php 4.2.x)
2185  if (substr($a_dir,-1) == "/")
2186  {
2187  $a_dir = substr($a_dir,0,-1);
2188  }
2189 
2190  // check if a_dir comes with a path
2191  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2192  {
2193  $path = ".";
2194  }
2195 
2196  // create directory with file permissions of parent directory
2197  umask(0000);
2198  return @mkdir($a_dir,fileperms($path));
2199  }
2200 
2201 
2214  function makeDirParents($a_dir)
2215  {
2216  $dirs = array($a_dir);
2217  $a_dir = dirname($a_dir);
2218  $last_dirname = '';
2219  while($last_dirname != $a_dir)
2220  {
2221  array_unshift($dirs, $a_dir);
2222  $last_dirname = $a_dir;
2223  $a_dir = dirname($a_dir);
2224  }
2225 
2226  // find the first existing dir
2227  $reverse_paths = array_reverse($dirs, TRUE);
2228  $found_index = -1;
2229  foreach ($reverse_paths as $key => $value)
2230  {
2231  if ($found_index == -1)
2232  {
2233  if (is_dir($value))
2234  {
2235  $found_index = $key;
2236  }
2237  }
2238  }
2239 
2240  umask(0000);
2241  foreach ($dirs as $dirindex => $dir)
2242  {
2243  // starting with the longest existing path
2244  if ($dirindex >= $found_index)
2245  {
2246  if (! file_exists($dir))
2247  {
2248  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2249  {
2250  // on some systems there is an error when there is a slash
2251  // at the end of a directory in mkdir, see Mantis #2554
2252  $dir = substr($dir,0,strlen($dir)-1);
2253  }
2254  if (! mkdir($dir, $umask))
2255  {
2256  error_log("Can't make directory: $dir");
2257  return false;
2258  }
2259  }
2260  elseif (! is_dir($dir))
2261  {
2262  error_log("$dir is not a directory");
2263  return false;
2264  }
2265  else
2266  {
2267  // get umask of the last existing parent directory
2268  $umask = fileperms($dir);
2269  }
2270  }
2271  }
2272  return true;
2273  }
2274 
2282  function delDir($a_dir, $a_clean_only = false)
2283  {
2284  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2285  {
2286  return;
2287  }
2288 
2289  $current_dir = opendir($a_dir);
2290 
2291  $files = array();
2292 
2293  // this extra loop has been necessary because of a strange bug
2294  // at least on MacOS X. A looped readdir() didn't work
2295  // correctly with larger directories
2296  // when an unlink happened inside the loop. Getting all files
2297  // into the memory first solved the problem.
2298  while($entryname = readdir($current_dir))
2299  {
2300  $files[] = $entryname;
2301  }
2302 
2303  foreach($files as $file)
2304  {
2305  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2306  {
2307  ilUtil::delDir(${a_dir}."/".${file});
2308  }
2309  elseif ($file != "." and $file != "..")
2310  {
2311  unlink(${a_dir}."/".${file});
2312  }
2313  }
2314 
2315  closedir($current_dir);
2316  if (!$a_clean_only)
2317  {
2318  @rmdir(${a_dir});
2319  }
2320  }
2321 
2322 
2326  function getDir($a_dir)
2327  {
2328  $current_dir = opendir($a_dir);
2329 
2330  $dirs = array();
2331  $files = array();
2332  while($entry = readdir($current_dir))
2333  {
2334  if(is_dir($a_dir."/".$entry))
2335  {
2336  $dirs[$entry] = array("type" => "dir", "entry" => $entry);
2337  }
2338  else
2339  {
2340  if ($entry != "." && $entry != "..")
2341  {
2342  $size = filesize($a_dir."/".$entry);
2343  $files[$entry] = array("type" => "file", "entry" => $entry,
2344  "size" => $size);
2345  }
2346  }
2347  }
2348  ksort($dirs);
2349  ksort($files);
2350 
2351  return array_merge($dirs, $files);
2352  }
2353 
2357  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2358  {
2359  if (is_array($a_arr))
2360  {
2361  foreach ($a_arr as $k => $v)
2362  {
2363  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2364  }
2365  }
2366 
2367  return $a_arr;
2368  }
2369 
2373  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2374  {
2375  if (is_array($a_data))
2376  {
2377  foreach ($a_data as $k => $v)
2378  {
2379  if (is_array($v))
2380  {
2381  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2382  }
2383  else
2384  {
2385  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2386  }
2387  }
2388  }
2389  else
2390  {
2391  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2392  }
2393 
2394  return $a_data;
2395  }
2396 
2402  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2403  {
2404  if (ini_get("magic_quotes_gpc"))
2405  {
2406  $a_str = stripslashes($a_str);
2407  }
2408 
2409  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2410  }
2411 
2417  function stripOnlySlashes($a_str)
2418  {
2419  if (ini_get("magic_quotes_gpc"))
2420  {
2421  $a_str = stripslashes($a_str);
2422  }
2423 
2424  return $a_str;
2425  }
2426 
2430  function secureString($a_str, $a_strip_html = true, $a_allow = "")
2431  {
2432  // check whether all allowed tags can be made secure
2433  $only_secure = true;
2434  $allow_tags = explode(">", $a_allow);
2435  $sec_tags = ilUtil::getSecureTags();
2436  $allow_array = array();
2437  foreach($allow_tags as $allow)
2438  {
2439  if ($allow != "")
2440  {
2441  $allow = str_replace("<", "", $allow);
2442 
2443  if (!in_array($allow, $sec_tags))
2444  {
2445  $only_secure = false;
2446  }
2447  $allow_array[] = $allow;
2448  }
2449  }
2450 
2451  // default behaviour: allow only secure tags 1:1
2452  if (($only_secure || $a_allow == "") && $a_strip_html)
2453  {
2454  if ($a_allow == "")
2455  {
2456  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2457  "gap", "sub", "sup", "pre", "strike");
2458  }
2459 
2460  // this currently removes parts of strings like "a <= b"
2461  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2462  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2463  $a_str = strip_tags($a_str); // strip all other tags
2464  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2465 
2466  // a possible solution could be something like:
2467  // $a_str = str_replace("<", "&lt;", $a_str);
2468  // $a_str = str_replace(">", "&gt;", $a_str);
2469  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2470  //
2471  // output would be ok then, but input fields would show
2472  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2473  }
2474  else
2475  {
2476  // only for scripts, that need to allow more/other tags and parameters
2477  if ($a_strip_html)
2478  {
2479  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2480  }
2481  }
2482 
2483  return $a_str;
2484  }
2485 
2486  function getSecureTags()
2487  {
2488  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2489  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2490  }
2491 
2492  function maskSecureTags($a_str, $allow_array)
2493  {
2494  foreach ($allow_array as $t)
2495  {
2496  switch($t)
2497  {
2498  case "a":
2499  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2500  break;
2501 
2502  case "img":
2503  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2504  break;
2505 
2506  case "p":
2507  case "div":
2508  $a_str = ilUtil::maskTag($a_str, $t, array(
2509  array("param" => "align", "value" => "left"),
2510  array("param" => "align", "value" => "center"),
2511  array("param" => "align", "value" => "justify"),
2512  array("param" => "align", "value" => "right")
2513  ));
2514  break;
2515 
2516  default:
2517  $a_str = ilUtil::maskTag($a_str, $t);
2518  break;
2519  }
2520  }
2521 
2522  return $a_str;
2523  }
2524 
2525  function unmaskSecureTags($a_str, $allow_array)
2526  {
2527  foreach ($allow_array as $t)
2528  {
2529  switch($t)
2530  {
2531  case "a":
2532  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2533  break;
2534 
2535  case "img":
2536  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2537  break;
2538 
2539  case "p":
2540  case "div":
2541  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2542  array("param" => "align", "value" => "left"),
2543  array("param" => "align", "value" => "center"),
2544  array("param" => "align", "value" => "justify"),
2545  array("param" => "align", "value" => "right")
2546  ));
2547  break;
2548 
2549  default:
2550  $a_str = ilUtil::unmaskTag($a_str, $t);
2551  break;
2552  }
2553  }
2554 
2555  return $a_str;
2556  }
2557 
2562  function securePlainString($a_str)
2563  {
2564  if (ini_get("magic_quotes_gpc"))
2565  {
2566  return stripslashes($a_str);
2567  }
2568  else
2569  {
2570  return $a_str;
2571  }
2572  }
2587  function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2588  {
2589  $encoded = "";
2590 
2591  if ($a_make_links_clickable)
2592  {
2593  // Find text sequences in the plain text string which match
2594  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2595  // Encode all other text sequences in the plain text string using
2596  // htmlspecialchars and nl2br.
2597  // The following expressions matches URI's as specified in RFC 2396.
2598  //
2599  // The expression matches URI's, which start with some well known
2600  // schemes, like "http:", or with "www.". This must be followed
2601  // by at least one of the following RFC 2396 expressions:
2602  // - alphanum: [a-zA-Z0-9]
2603  // - reserved: [;\/?:|&=+$,]
2604  // - mark: [\\-_.!~*\'()]
2605  // - escaped: %[0-9a-fA-F]{2}
2606  // - fragment delimiter: #
2607  // - uric_no_slash: [;?:@&=+$,]
2608  $matches = array();
2609  $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);
2610  $pos1 = 0;
2611  $encoded = "";
2612  foreach ($matches as $match)
2613  {
2614  }
2615  foreach ($matches[0] as $match)
2616  {
2617  $matched_text = $match[0];
2618  $pos2 = $match[1];
2619  if ($matched_offset != previous_offset)
2620  {
2621  // encode plain text
2622  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2623  }
2624  // encode URI
2625  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2626 
2627 
2628  $pos1 = $pos2 + strlen($matched_text);
2629  }
2630  if ($pos1 < strlen($a_str))
2631  {
2632  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2633  }
2634  }
2635  else
2636  {
2637  $encoded = nl2br(htmlspecialchars($a_str));
2638  }
2639  return $encoded;
2640  }
2641 
2642 
2643  function maskAttributeTag($a_str, $tag, $tag_att)
2644  {
2645  global $ilLog;
2646 
2647  $ws = "[ \t\r\f\v\n]*";
2648  $att = $ws."[^>]*".$ws;
2649 
2650  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2651  $a_str, $found))
2652  {
2653  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2654  $esc = array();
2655  foreach($un as $v)
2656  {
2657  $esc[] = "\\".$v;
2658  }
2659  $ff = str_replace($un, $esc, $found[1]);
2660 
2661  $old_str = $a_str;
2662  $a_str = eregi_replace("<".$ff.">",
2663  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2664  if ($old_str == $a_str)
2665  {
2666  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2667  htmlentities($a_str));
2668  return $a_str;
2669  }
2670  }
2671  $a_str = str_ireplace("</$tag>",
2672  "&lt;/$tag&gt;", $a_str);
2673  return $a_str;
2674  }
2675 
2676  function unmaskAttributeTag($a_str, $tag, $tag_att)
2677  {
2678  global $ilLog;
2679 
2680  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2681  $a_str, $found))
2682  {
2683  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2684  $esc = array();
2685  foreach($un as $v)
2686  {
2687  $esc[] = "\\".$v;
2688  }
2689  $ff = str_replace($un, $esc, $found[1]);
2690 
2691  $old_str = $a_str;
2692  $a_str = eregi_replace("&lt;".$ff."&gt;",
2693  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2694  if ($old_str == $a_str)
2695  {
2696  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2697  htmlentities($a_str));
2698  return $a_str;
2699  }
2700  }
2701  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2702  return $a_str;
2703  }
2704 
2705  function maskTag($a_str, $t, $fix_param = "")
2706  {
2707  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2708  "&lt;".$t."&gt;", $a_str);
2709  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2710  "&lt;/".$t."&gt;", $a_str);
2711 
2712  if (is_array($fix_param))
2713  {
2714  foreach ($fix_param as $p)
2715  {
2716  $k = $p["param"];
2717  $v = $p["value"];
2718  $a_str = str_replace("<$t $k=\"$v\">",
2719  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2720  }
2721  }
2722 
2723  return $a_str;
2724  }
2725 
2726  function unmaskTag($a_str, $t, $fix_param = "")
2727  {
2728  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2729  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2730 
2731  if (is_array($fix_param))
2732  {
2733  foreach ($fix_param as $p)
2734  {
2735  $k = $p["param"];
2736  $v = $p["value"];
2737  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2738  "<"."$t $k=\"$v\"".">", $a_str);
2739  }
2740  }
2741  return $a_str;
2742  }
2743 
2744  function secureLink($a_str)
2745  {
2746  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2747  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2748  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2749  return $a_str;
2750  }
2751 
2763  function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2764  {
2765  //$a_str = strip_tags($a_str, $a_allow);
2766 
2767  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
2768  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
2769  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
2770  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
2771  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
2772  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
2773  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
2774  "title,tr,tt,u,ul,var";
2775  $a_allow = strtolower ($a_allow);
2776  $negatives = split (",",$negativestr);
2777  $outer_old_str = "";
2778  while($outer_old_str != $a_str)
2779  {
2780  $outer_old_str = $a_str;
2781  foreach ($negatives as $item)
2782  {
2783  $pos = strpos($a_allow, "<$item>");
2784 
2785  // remove complete tag, if not allowed
2786  if ($pos === false)
2787  {
2788  $old_str = "";
2789  while($old_str != $a_str)
2790  {
2791  $old_str = $a_str;
2792  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2793  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2794  }
2795  }
2796  }
2797  }
2798 
2799  if ($a_rm_js)
2800  {
2801  // remove all attributes if an "on..." attribute is given
2802  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2803 
2804  // remove all attributes if a "javascript" is within tag
2805  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2806 
2807  // remove all attributes if an "expression" is within tag
2808  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2809  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2810  }
2811 
2812  return $a_str;
2813  }
2814 
2815 
2821  function addSlashes($a_str)
2822  {
2823  if (ini_get("magic_quotes_gpc"))
2824  {
2825  return $a_str;
2826  }
2827  else
2828  {
2829  return addslashes($a_str);
2830  }
2831  }
2832 
2842  function prepareFormOutput($a_str, $a_strip = false)
2843  {
2844  if($a_strip)
2845  {
2846  $a_str = ilUtil::stripSlashes($a_str);
2847  }
2848  $a_str = htmlspecialchars($a_str);
2849  // Added replacement of curly brackets to prevent
2850  // problems with PEAR templates, because {xyz} will
2851  // be removed as unused template variable
2852  $a_str = str_replace("{", "&#123;", $a_str);
2853  $a_str = str_replace("}", "&#125;", $a_str);
2854  // needed for LaTeX conversion \\ in LaTeX is a line break
2855  // but without this replacement, php changes \\ to \
2856  $a_str = str_replace("\\", "&#92;", $a_str);
2857  return $a_str;
2858  }
2859 
2860 
2868  function prepareDBString($a_str)
2869  {
2870  return addslashes($a_str);
2871  }
2872 
2873 
2880  function removeItemFromDesktops($a_id)
2881  {
2882  return ilObjUser::_removeItemFromDesktops($a_id);
2883  }
2884 
2885 
2893  function extractParameterString($a_parstr)
2894  {
2895  // parse parameters in array
2896  $par = array();
2897  $ok=true;
2898  while(($spos=strpos($a_parstr,"=")) && $ok)
2899  {
2900  // extract parameter
2901  $cpar = substr($a_parstr,0,$spos);
2902  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
2903  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
2904  $cpar = substr($cpar,1,strlen($cpar)-1);
2905  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
2906  $cpar = substr($cpar,0,strlen($cpar)-1);
2907 
2908  // parameter name should only
2909  $cpar_old = "";
2910  while($cpar != $cpar_old)
2911  {
2912  $cpar_old = $cpar;
2913  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
2914  }
2915 
2916  // extract value
2917  if ($cpar != "")
2918  {
2919  if($spos=strpos($a_parstr,"\""))
2920  {
2921  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
2922  $spos=strpos($a_parstr,"\"");
2923  if(is_int($spos))
2924  {
2925  $cval = substr($a_parstr,0,$spos);
2926  $par[$cpar]=$cval;
2927  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
2928  }
2929  else
2930  $ok=false;
2931  }
2932  else
2933  $ok=false;
2934  }
2935  }
2936 
2937  if($ok) return $par; else return false;
2938  }
2939 
2940  function assembleParameterString($a_par_arr)
2941  {
2942  if (is_array($a_par_arr))
2943  {
2944  $target_arr = array();
2945  foreach ($a_par_arr as $par => $val)
2946  {
2947  $target_arr[] = "$par=\"$val\"";
2948  }
2949  $target_str = implode(", ", $target_arr);
2950  }
2951 
2952  return $target_str;
2953  }
2954 
2958  function dumpString($a_str)
2959  {
2960  $ret = $a_str.": ";
2961  for($i=0; $i<strlen($a_str); $i++)
2962  {
2963  $ret.= ord(substr($a_str,$i,1))." ";
2964  }
2965  return $ret;
2966  }
2967 
2968 
2972  function yn2tf($a_yn)
2973  {
2974  if(strtolower($a_yn) == "y")
2975  {
2976  return true;
2977  }
2978  else
2979  {
2980  return false;
2981  }
2982  }
2983 
2987  function tf2yn($a_tf)
2988  {
2989  if($a_tf)
2990  {
2991  return "y";
2992  }
2993  else
2994  {
2995  return "n";
2996  }
2997  }
2998 
3007  function sort_func ($a, $b)
3008  {
3009  global $array_sortby,$array_sortorder;
3010 
3011  // this comparison should give optimal results if
3012  // locale is provided and mb string functions are supported
3013  if ($array_sortorder == "asc")
3014  {
3015  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3016  }
3017 
3018  if ($array_sortorder == "desc")
3019  {
3020  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3021  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3022  }
3023  }
3024 
3033  function sort_func_numeric ($a, $b)
3034  {
3035  global $array_sortby,$array_sortorder;
3036 
3037  if ($array_sortorder == "asc")
3038  {
3039  return $a["$array_sortby"] > $b["$array_sortby"];
3040  }
3041 
3042  if ($array_sortorder == "desc")
3043  {
3044  return $a["$array_sortby"] < $b["$array_sortby"];
3045  }
3046  }
3057  public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3058  $a_keep_keys = false)
3059  {
3060  include_once("./Services/Utilities/classes/class.ilStr.php");
3061 
3062  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3063  if (! $a_keep_keys) {
3064  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3065  }
3066  // END WebDAV Provide a 'stable' sort algorithm
3067 
3068  global $array_sortby,$array_sortorder;
3069 
3070  $array_sortby = $a_array_sortby;
3071 
3072  if ($a_array_sortorder == "desc")
3073  {
3074  $array_sortorder = "desc";
3075  }
3076  else
3077  {
3078  $array_sortorder = "asc";
3079  }
3080  if($a_numeric)
3081  {
3082  if ($a_keep_keys)
3083  {
3084  uasort($array, array("ilUtil", "sort_func_numeric"));
3085  }
3086  else
3087  {
3088  usort($array, array("ilUtil", "sort_func_numeric"));
3089  }
3090  }
3091  else
3092  {
3093  if ($a_keep_keys)
3094  {
3095  uasort($array, array("ilUtil", "sort_func"));
3096  }
3097  else
3098  {
3099  usort($array, array("ilUtil", "sort_func"));
3100  }
3101  }
3102  //usort($array,"ilUtil::sort_func");
3103 
3104  return $array;
3105  }
3106  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3119  function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3120  {
3121  global $array_sortby,$array_sortorder;
3122 
3123  $array_sortby = $a_array_sortby;
3124 
3125  if ($a_array_sortorder == "desc")
3126  {
3127  $array_sortorder = "desc";
3128  }
3129  else
3130  {
3131  $array_sortorder = "asc";
3132  }
3133 
3134  // Create a copy of the array values for sorting
3135  $sort_array = array_values($array);
3136 
3137  if($a_numeric)
3138  {
3139  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3140  }
3141  else
3142  {
3143  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3144  }
3145 
3146  return $sort_array;
3147  }
3148  function mergesort(&$array, $cmp_function = 'strcmp') {
3149  // Arrays of size < 2 require no action.
3150  if (count($array) < 2) return;
3151 
3152  // Split the array in half
3153  $halfway = count($array) / 2;
3154  $array1 = array_slice($array, 0, $halfway);
3155  $array2 = array_slice($array, $halfway);
3156 
3157  // Recurse to sort the two halves
3158  ilUtil::mergesort($array1, $cmp_function);
3159  ilUtil::mergesort($array2, $cmp_function);
3160 
3161  // If all of $array1 is <= all of $array2, just append them.
3162  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3163  $array = array_merge($array1, $array2);
3164  return;
3165  }
3166 
3167  // Merge the two sorted arrays into a single sorted array
3168  $array = array();
3169  $ptr1 = $ptr2 = 0;
3170  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3171  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3172  $array[] = $array1[$ptr1++];
3173  }
3174  else {
3175  $array[] = $array2[$ptr2++];
3176  }
3177  }
3178 
3179  // Merge the remainder
3180  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3181  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3182 
3183  return;
3184  }
3185  // END WebDAV: Provide a 'stable' sort algorithm
3186 
3196  function unique_multi_array($array, $sub_key)
3197  {
3198  $target = array();
3199  $existing_sub_key_values = array();
3200 
3201  foreach ($array as $key=>$sub_array)
3202  {
3203  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3204  {
3205  $existing_sub_key_values[] = $sub_array[$sub_key];
3206  $target[$key] = $sub_array;
3207  }
3208  }
3209 
3210  return $target;
3211  }
3212 
3213 
3221  function getGDSupportedImageType($a_desired_type)
3222  {
3223  $a_desired_type = strtolower($a_desired_type);
3224  // get supported Image Types
3225  $im_types = ImageTypes();
3226 
3227  switch($a_desired_type)
3228  {
3229  case "jpg":
3230  if ($im_types & IMG_JPG) return "jpg";
3231  if ($im_types & IMG_GIF) return "gif";
3232  if ($im_types & IMG_PNG) return "png";
3233  break;
3234 
3235  case "gif":
3236  if ($im_types & IMG_GIF) return "gif";
3237  if ($im_types & IMG_JPG) return "jpg";
3238  if ($im_types & IMG_PNG) return "png";
3239  break;
3240 
3241  case "png":
3242  if ($im_types & IMG_PNG) return "png";
3243  if ($im_types & IMG_JPG) return "jpg";
3244  if ($im_types & IMG_GIF) return "gif";
3245  break;
3246  }
3247 
3248  return "";
3249  }
3250 
3258  function deducibleSize($a_mime)
3259  {
3260  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3261  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3262  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3263  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3264  {
3265  return true;
3266  }
3267  else
3268  {
3269  return false;
3270  }
3271  }
3272 
3273 
3279  function redirect($a_script)
3280  {
3281  global $log, $PHP_SELF;
3282 //$log->write("redirect FROM:".$PHP_SELF." to ".$a_script);
3283  //vd($a_script);
3284 //echo "-".$a_script."-";
3285  header("Location: ".$a_script);
3286  exit();
3287  }
3288 
3294  function insertInstIntoID($a_value)
3295  {
3296  if (substr($a_value, 0, 4) == "il__")
3297  {
3298  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3299  }
3300 
3301  return $a_value;
3302  }
3303 
3312  function groupNameExists($a_group_name,$a_id = 0)
3313  {
3314  global $ilDB,$ilErr;
3315 
3316  if (empty($a_group_name))
3317  {
3318  $message = get_class($this)."::_NameExists(): No groupname given!";
3319  $ilErr->raiseError($message,$ilErr->WARNING);
3320  }
3321 
3322  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3323 
3324  $q = "SELECT obj_id FROM object_data ".
3325  "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3326  "AND type = ".$ilDB->quote("grp", "text").
3327  $clause;
3328 
3329  $r = $ilDB->query($q);
3330 
3331  if ($r->numRows())
3332  {
3333  return true;
3334  }
3335  else
3336  {
3337  return false;
3338  }
3339  }
3340 
3341  /*
3342  * get the user_ids which correspond a search string
3343  * static function
3344  * @param string search string
3345  * @access public
3346  */
3347  function searchGroups($a_search_str)
3348  {
3349  global $ilDB;
3350 
3351  $q = "SELECT * ".
3352  "FROM object_data ,object_reference ".
3353  "WHERE (".$ilDB->like("object_data.title", "text", "%".$a_search_str."%")." ".
3354  "OR ".$ilDB->like("object_data.description", "text", "%".$a_search_str."%").") ".
3355  "AND object_data.type = 'grp' ".
3356  "AND object_data.obj_id = object_reference.obj_id ".
3357  "ORDER BY title ";
3358 
3359  $res = $ilDB->query($q);
3360 
3361  while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3362  {
3363  // STORE DATA IN ARRAY WITH KEY obj_id
3364  // SO DUPLICATE ENTRIES ( LINKED OBJECTS ) ARE UNIQUE
3365  $ids[$row->obj_id] = array(
3366  "ref_id" => $row->ref_id,
3367  "title" => $row->title,
3368  "description" => $row->description);
3369  }
3370 
3371  return $ids ? $ids : array();
3372  }
3373 
3377  function getMemString()
3378  {
3379  $my_pid = getmypid();
3380  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3381  }
3382 
3386  function isWindows()
3387  {
3388  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3389  {
3390  return true;
3391  }
3392  return false;
3393  }
3394 
3395 
3396  function escapeShellArg($a_arg)
3397  {
3398  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3399  // see also ilias bug 5630
3400  return escapeshellarg($a_arg);
3401  }
3402 
3410  public function escapeShellCmd($a_arg)
3411  {
3412  if(ini_get('safe_mode') == 1)
3413  {
3414  return $a_arg;
3415  }
3416  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3417  return escapeshellcmd($a_arg);
3418  }
3419 
3427  public static function execQuoted($cmd, $args = NULL)
3428  {
3429  if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3430  {
3431  // cmd won't work without quotes
3432  $cmd = '"'.$cmd.'"';
3433  if($args)
3434  {
3435  // args are also quoted, workaround is to quote the whole command AGAIN
3436  // was fixed in php 5.2 (see php bug #25361)
3437  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3438  {
3439  $cmd = '"'.$cmd." ".$args.'"';
3440  }
3441  // args are not quoted or php is fixed, just append
3442  else
3443  {
3444  $cmd .= " ".$args;
3445  }
3446  }
3447  }
3448  // nothing todo, just append args
3449  else if($args)
3450  {
3451  $cmd .= " ".$args;
3452  }
3453  exec($cmd, $arr);
3454  return $arr;
3455  }
3456 
3457  /*
3458  * Calculates a Microsoft Excel date/time value
3459  *
3460  * Calculates a Microsoft Excel date/time value (nr of days after 1900/1/1 0:00) for
3461  * a given date and time. The function only accepts dates after 1970/1/1, because the
3462  * unix timestamp functions used in the function are starting with that date.
3463  * If you don't enter parameters the date/time value for the actual date/time
3464  * will be calculated.
3465  *
3466  * static function
3467  *
3468  * @param integer $year Year
3469  * @param integer $month Month
3470  * @param integer $day Day
3471  * @param integer $hour Hour
3472  * @param integer $minute Minute
3473  * @param integer $second Second
3474  * @return float The Microsoft Excel date/time value
3475  * @access public
3476  */
3477  function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3478  {
3479  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3480  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3481  {
3482  $target_time = time();
3483  }
3484  else
3485  {
3486  if ($year < 1970)
3487  {
3488  return 0;
3489  }
3490  }
3491  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3492  $difference = $target_time - $starting_time;
3493  $days = (($difference - ($difference % 86400)) / 86400);
3494  $difference = $difference - ($days * 86400) + 3600;
3495  return ($days + 25570 + ($difference / 86400));
3496  }
3497 
3501  function renameExecutables($a_dir)
3502  {
3503  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3504  foreach ($def_arr as $def)
3505  {
3506  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3507  }
3508 
3509  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3510  foreach ($def_arr as $def)
3511  {
3512  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3513  }
3514  }
3515 
3526  function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3527  {
3528  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3529  || trim($a_old_suffix) == "")
3530  {
3531  return false;
3532  }
3533 
3534  // check if argument is directory
3535  if (!@is_dir($a_dir))
3536  {
3537  return false;
3538  }
3539 
3540  // read a_dir
3541  $dir = opendir($a_dir);
3542 
3543  while($file = readdir($dir))
3544  {
3545  if ($file != "." and
3546  $file != "..")
3547  {
3548  // directories
3549  if (@is_dir($a_dir."/".$file))
3550  {
3551  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3552  }
3553 
3554  // files
3555  if (@is_file($a_dir."/".$file))
3556  {
3557  // first check for files with trailing dot
3558  if(strrpos($file,'.') == (strlen($file) - 1))
3559  {
3560  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3561  $file = substr($file,0,-1);
3562  }
3563 
3564  $path_info = pathinfo($a_dir."/".$file);
3565 
3566  if (strtolower($path_info["extension"]) ==
3567  strtolower($a_old_suffix))
3568  {
3569  $pos = strrpos($a_dir."/".$file, ".");
3570  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3571  rename($a_dir."/".$file, $new_name);
3572  }
3573  }
3574  }
3575  }
3576  return true;
3577  }
3578 
3579  function isAPICall () {
3580  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3581  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3582  }
3583 
3584  function KT_replaceParam($qstring, $paramName, $paramValue) {
3585  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3586  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3587  } else {
3588  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3589  }
3590  }
3591 
3592  function replaceUrlParameterString ($url, $parametersArray) {
3593 
3594  foreach ($parametersArray as $paramName => $paramValue ) {
3595  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3596  }
3597  return $url;
3598  }
3599 
3603  function generatePasswords ($a_number)
3604  {
3605  $ret = array();
3606  srand((double) microtime()*1000000);
3607 
3608  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3609  $security = ilSecuritySettings::_getInstance();
3610 
3611  for ($i=1; $i<=$a_number; $i++)
3612  {
3613  $min = ($security->getPasswordMinLength() > 0)
3614  ? $security->getPasswordMinLength()
3615  : 6;
3616  $max = ($security->getPasswordMaxLength() > 0)
3617  ? $security->getPasswordMaxLength()
3618  : 10;
3619  if ($min > $max)
3620  {
3621  $max = $max + 1;
3622  }
3623  $length = rand($min,$max);
3624  $next = rand(1,2);
3625  $vowels = "aeiou";
3626  $consonants = "bcdfghjklmnpqrstvwxyz";
3627  $numbers = "1234567890";
3628  $special = "_.+?#-*@!$%~";
3629  $pw = "";
3630 
3631  // position for number
3632  if ($security->isPasswordCharsAndNumbersEnabled())
3633  {
3634  $num_pos = rand(0, $length - 1);
3635  }
3636 
3637  // position for special character
3638  if ($security->isPasswordSpecialCharsEnabled())
3639  {
3640  $spec_pos = rand(0, $length - 1);
3641  if ($security->isPasswordCharsAndNumbersEnabled())
3642  {
3643  if ($num_pos == $spec_pos) // not same position for number/special
3644  {
3645  if ($spec_pos > 0)
3646  {
3647  $spec_pos -= 1;
3648  }
3649  else
3650  {
3651  $spec_pos += 1;
3652  }
3653  }
3654  }
3655  }
3656  for ($j=0; $j < $length; $j++)
3657  {
3658  if ($security->isPasswordCharsAndNumbersEnabled() && $num_pos == $j)
3659  {
3660  $pw.= $numbers[rand(0,strlen($numbers)-1)];
3661  }
3662  else if ($security->isPasswordSpecialCharsEnabled() && $spec_pos == $j)
3663  {
3664  $pw.= $special[rand(0,strlen($special)-1)];
3665  }
3666  else
3667  {
3668  switch ($next)
3669  {
3670  case 1:
3671  $pw.= $consonants[rand(0,strlen($consonants)-1)];
3672  $next = 2;
3673  break;
3674 
3675  case 2:
3676  $pw.= $vowels[rand(0,strlen($vowels)-1)];
3677  $next = 1;
3678  break;
3679  }
3680  }
3681  }
3682 
3683  $ret[] = $pw;
3684  }
3685  return $ret;
3686  }
3687 
3689  {
3690  $path = preg_replace("/[\/\\\]+$/", "", $path);
3691  return $path;
3692  }
3693 
3703  {
3704  if (empty($data))
3705  {
3706  $data = array();
3707  }
3708 
3709  foreach($data as $k=>$datum)
3710  {
3711  if(is_null($datum)) $data[$k] = 'null';
3712  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
3713  if(is_array($datum)) $data[$k] = array_php2js($datum);
3714  }
3715 
3716  return "[" . implode(', ', $data) . "]";
3717  }
3718 
3723  function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3724  {
3725  global $lng;
3726 
3727  if (IL_VIRUS_SCANNER != "None")
3728  {
3729  require_once("classes/class.ilVirusScannerFactory.php");
3731  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3732  {
3733  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
3734  {
3735  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3736  if ($vs->fileCleaned())
3737  {
3738  $vs_txt.= "<br />".$lng->txt("cleaned_file").
3739  "<br />".$clean_txt;
3740  $vs_txt.= "<br />".$lng->txt("repeat_scan");
3741  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3742  {
3743  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
3744  "<br />".nl2br($vs2_txt));
3745  }
3746  else
3747  {
3748  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
3749  }
3750  }
3751  else
3752  {
3753  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
3754  }
3755  }
3756  else
3757  {
3758  return array(false, nl2br($vs_txt));
3759  }
3760  }
3761  }
3762 
3763  return array(true,"");
3764  }
3765 
3766 
3770  function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true)
3771  {
3772  global $lng, $ilias;
3773 //echo "<br>ilUtli::moveuploadedFile($a_name)";
3774 
3775  if (!is_file($a_file))
3776  {
3777  if ($a_raise_errors)
3778  {
3779  $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
3780  }
3781  else
3782  {
3783  ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
3784  }
3785  return false;
3786  }
3787 
3788  // virus handling
3789  $vir = ilUtil::virusHandling($a_file, $a_name);
3790  if (!$vir[0])
3791  {
3792  unlink($a_file);
3793  if ($a_raise_errors)
3794  {
3795  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
3796  $vir[1],
3797  $ilias->error_obj->MESSAGE);
3798  }
3799  else
3800  {
3801  ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
3802  $vir[1], true);
3803  }
3804  return false;
3805  }
3806  else
3807  {
3808  if ($vir[1] != "")
3809  {
3810  ilUtil::sendInfo($vir[1], true);
3811  }
3812  return move_uploaded_file($a_file, $a_target);
3813  }
3814  }
3815 
3816 
3820  function date_mysql2time($mysql_date_time) {
3821  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
3822  list($jahr, $monat, $tag) = explode("-", $datum);
3823  list($std, $min, $sec) = explode(":", $uhrzeit);
3824  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3825  }
3826 
3830  function now()
3831  {
3832  return date("Y-m-d H:i:s");
3833  }
3834 
3848  function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
3849  {
3850  $resultarray = array();
3851  foreach ($row as $rowindex => $entry)
3852  {
3853  $surround = FALSE;
3854  if ($quoteAll)
3855  {
3856  $surround = TRUE;
3857  }
3858  if (strpos($entry, "\"") !== FALSE)
3859  {
3860  $entry = str_replace("\"", "\"\"", $entry);
3861  $surround = TRUE;
3862  }
3863  if (strpos($entry, $separator) !== FALSE)
3864  {
3865  $surround = TRUE;
3866  }
3867  if ($compatibleWithMSExcel)
3868  {
3869  // replace all CR LF with LF (for Excel for Windows compatibility
3870  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
3871  }
3872  if ($surround)
3873  {
3874  if ($outUTF8)
3875  {
3876  $resultarray[$rowindex] = "\"" . $entry . "\"";
3877  }
3878  else
3879  {
3880  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3881  }
3882  }
3883  else
3884  {
3885  if ($outUTF8)
3886  {
3887  $resultarray[$rowindex] = $entry;
3888  }
3889  else
3890  {
3891  $resultarray[$rowindex] = utf8_decode($entry);
3892  }
3893  }
3894  }
3895  return $resultarray;
3896  }
3897 
3898  // validates a domain name (example: www.ilias.de)
3899  function isDN($a_str)
3900  {
3901  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
3902  }
3903 
3904  // validates an IP address (example: 192.168.1.1)
3905  function isIPv4($a_str)
3906  {
3907  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])\.".
3908  "(\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));
3909  }
3910 
3911 
3938  function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
3939  {
3940  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
3941 
3942  if(!is_array($a_obj_type))
3943  {
3944  $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
3945  }
3946  else
3947  {
3948  $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
3949  }
3950 
3951  // limit number of results default is search result limit
3952  if(!$limit)
3953  {
3954  $limit = $ilias->getSetting('search_max_hits',100);
3955  }
3956  if($limit == -1)
3957  {
3958  $limit = 10000;
3959  }
3960 
3961  // default to logged in usr
3962  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
3963  $a_roles = $rbacreview->assignedRoles($a_usr_id);
3964 
3965  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
3966  // is assigned to the system role
3967  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
3968  {
3969  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
3970  "LEFT JOIN tree ON obr.ref_id = tree.child ".
3971  $where.
3972  "AND tree = 1";
3973 
3974  $res = $ilDB->query($query);
3975  $counter = 0;
3976  while($row = $ilDB->fetchObject($res))
3977  {
3978  // Filter recovery folder
3979  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
3980  {
3981  continue;
3982  }
3983 
3984  if($counter++ >= $limit)
3985  {
3986  break;
3987  }
3988 
3989  $ref_ids[] = $row->ref_id;
3990  }
3991  return $ref_ids ? $ref_ids : array();
3992  } // End Administrators
3993 
3994  // Check ownership if it is not asked for edit_permission or a create permission
3995  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
3996  {
3997  $check_owner = ") ";
3998  }
3999  else
4000  {
4001  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4002  }
4003 
4004  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4005  $ops_id = $ops_ids[0];
4006 
4007  $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4008 
4009  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4010  "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4011  "JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4012  $where.
4013  $and.
4014  "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4015  "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4016  $check_owner;
4017 
4018  $res = $ilDB->query($query);
4019  $counter = 0;
4020  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4021  {
4022  if($counter >= $limit)
4023  {
4024  break;
4025  }
4026 
4027  // Filter objects in recovery folder
4028  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4029  {
4030  continue;
4031  }
4032 
4033  // Check deleted, hierarchical access ...
4034  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4035  {
4036  $counter++;
4037  $ref_ids[] = $row->ref_id;
4038  }
4039  }
4040  return $ref_ids ? $ref_ids : array();
4041  }
4042 
4049  function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4050  {
4051  global $tpl, $lng, $ilUser;
4052 
4053  // - take care of html exports (-> see buildLatexImages)
4054  include_once "./Services/Administration/classes/class.ilSetting.php";
4055  $jsMathSetting = new ilSetting("jsMath");
4056  $use_jsmath =
4057  $jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault"))));
4058 
4059  if ($use_jsmath)
4060  {
4061  $info = "";
4062  if (!$tpl->out_jsmath_info)
4063  {
4064  include_once "./classes/class.ilTemplate.php";
4065  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4066  $lng->loadLanguageModule("jsmath");
4067  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4068  $info = $template->get();
4069  $tpl->out_jsmath_info = TRUE;
4070  }
4071  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4072  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4073  }
4074 
4075  // this is a fix for bug5362
4076  $cpos = 0;
4077  $o_start = $a_start;
4078  $o_end = $a_end;
4079  $a_start = str_replace("\\", "", $a_start);
4080  $a_end = str_replace("\\", "", $a_end);
4081  /*$a_start = str_replace("\]", "]", $a_start);
4082  $a_start = str_replace("\[", "[", $a_start);
4083  $a_end = str_replace("\]", "]", $a_end);
4084  $a_end = str_replace("\[", "[", $a_end);
4085  $a_end = str_replace("\/", "/", $a_end);*/
4086 
4087  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4088  {
4089  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4090  {
4091  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4092 
4093  // replace, if tags do not go across div borders
4094  if (!is_int(strpos($tex, "</div>")))
4095  {
4096  if (!$use_jsmath)
4097  {
4098  $a_text = substr($a_text, 0, $spos).
4099  "<img alt=\"".htmlentities($tex)."\" src=\"".$a_cgi."?".
4100  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4101  " />".
4102  substr($a_text, $epos + strlen($a_end));
4103  }
4104  else
4105  {
4106  $tex = $a_start.$tex.$a_end;
4107 //echo "<br>1:".$tex;
4108  $replacement =
4109  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4110  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $tex);
4111  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4112 //echo "<br>2:".htmlentities($replacement);
4113  $a_text = substr($a_text, 0, $spos).
4114  $replacement.
4115  substr($a_text, $epos + strlen($a_end));
4116  }
4117  }
4118  }
4119  $cpos = $spos + 1;
4120  }
4121 
4122  if ($use_jsmath)
4123  {
4124  $a_text = str_replace("[[info]]", $info, $a_text);
4125  }
4126 
4127  $result_text = $a_text;
4128 
4129 // $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4130 // "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4131 // " />'", $a_text);
4132 
4133 //echo htmlentities($a_text);
4134 
4135  return $result_text;
4136  }
4137 
4144  function __insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4145  {
4146  global $tpl, $lng, $ilUser;
4147 
4148 //echo "<br><br>".htmlentities($a_text);
4149 //echo "<br>-".htmlentities($a_start)."-".htmlentities($a_end)."-";
4150 
4151  // - take care of html exports (-> see buildLatexImages)
4152  include_once "./Services/Administration/classes/class.ilSetting.php";
4153  $jsMathSetting = new ilSetting("jsMath");
4154  if ($jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault")))))
4155  {
4156  $info = "";
4157  if (!$tpl->out_jsmath_info)
4158  {
4159  include_once "./classes/class.ilTemplate.php";
4160  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4161  $lng->loadLanguageModule("jsmath");
4162  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4163  $info = $template->get();
4164  $tpl->out_jsmath_info = TRUE;
4165  }
4166  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4167  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4168  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $a_text);
4169  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4170  $result_text = str_replace("[[info]]", $info, $result_text);
4171  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4172  }
4173  else
4174  {
4175  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4176  "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4177  " />'", $a_text);
4178  }
4179 
4180  return $result_text;
4181  }
4182 
4189  function buildLatexImages($a_text, $a_dir ,$a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4190  {
4191  $result_text = $a_text;
4192 
4193  if ($a_cgi != "")
4194  {
4195  while (preg_match('/' . $a_start . '(.*?)' . $a_end . '/ie', $result_text, $found))
4196  {
4197  $cnt = (int) $GLOBALS["teximgcnt"]++;
4198  // get image from cgi and write it to file
4199  $fpr = @fopen($a_cgi."?".rawurlencode($found[1]), "r");
4200  $lcnt = 0;
4201  if ($fpr)
4202  {
4203  while(!feof($fpr))
4204  {
4205  $buf = fread($fpr, 1024);
4206  if ($lcnt == 0)
4207  {
4208  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4209  {
4210  $suffix = "gif";
4211  }
4212  else
4213  {
4214  $suffix = "png";
4215  }
4216  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4217  }
4218  $lcnt++;
4219  fwrite($fpw, $buf);
4220  }
4221  fclose($fpw);
4222  fclose($fpr);
4223  }
4224 
4225  // replace tex-tag
4226  $img_str = "./teximg/img".$cnt.".".$suffix;
4227  $result_text = str_replace($found[0],
4228  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4229  }
4230  }
4231 
4232  return $result_text;
4233  }
4234 
4242  function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE)
4243  {
4244  $result = $txt_output;
4245  $is_html = $this->isHTML($result);
4246  if ($prepare_for_latex_output)
4247  {
4248  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>", URL_TO_LATEX);
4249  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]", URL_TO_LATEX);
4250  }
4251 
4252  // removed: did not work with magic_quotes_gpc = On
4253  if (!$is_html)
4254  {
4255  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4256  $result = preg_replace("/[\n]/", "<br />", $result);
4257  }
4258  else
4259  {
4260  // patch for problems with the <pre> tags in tinyMCE
4261  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4262  {
4263  foreach ($matches[0] as $found)
4264  {
4265  $replacement = "";
4266  if (strpos("\n", $found) === FALSE)
4267  {
4268  $replacement = "\n";
4269  }
4270  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4271  $result = str_replace($found, $removed, $result);
4272  }
4273  }
4274  }
4275  if ($prepare_for_latex_output)
4276  {
4277  // replace special characters to prevent problems with the ILIAS template system
4278  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4279  $result = str_replace("{", "&#123;", $result);
4280  $result = str_replace("}", "&#125;", $result);
4281  $result = str_replace("\\", "&#92;", $result);
4282  }
4283  return $result;
4284  }
4285 
4286 
4293  function int2array ($seconds, $periods = null)
4294  {
4295  // Define time periods
4296  if (!is_array($periods))
4297  {
4298  $periods = array (
4299  'years' => 31536000,
4300  'months' => 2592000,
4301  'days' => 86400,
4302  'hours' => 3600,
4303  'minutes' => 60,
4304  'seconds' => 1
4305  );
4306  }
4307 
4308  // Loop
4309  $seconds = (float) $seconds;
4310  foreach ($periods as $period => $value)
4311  {
4312  $count = floor($seconds / $value);
4313 
4314  if ($count == 0)
4315  {
4316  continue;
4317  }
4318 
4319  $values[$period] = $count;
4320  $seconds = $seconds % $value;
4321  }
4322  // Return
4323  if (empty($values))
4324  {
4325  $values = null;
4326  }
4327 
4328  return $values;
4329  }
4330 
4337  function timearray2string ($duration)
4338  {
4339  global $lng;
4340 
4341  if (!is_array($duration))
4342  {
4343  return false;
4344  }
4345 
4346  foreach ($duration as $key => $value) {
4347 
4348  // Plural
4349  if ($value > 1)
4350  {
4351  $segment_name = $key;
4352  $segment_name = $lng->txt($segment_name);
4353  $segment = $value . ' ' . $segment_name;
4354  }
4355  else
4356  {
4357  $segment_name = substr($key, 0, -1);
4358  $segment_name = $lng->txt($segment_name);
4359  $segment = $value . ' ' . $segment_name;
4360  }
4361 
4362  $array[] = $segment;
4363  }
4364  $len = count($array);
4365 
4366  if ($len>3)
4367  {
4368  $array=array_slice($array,0,(3-$len));
4369  }
4370 
4371  $str = implode(', ', $array);
4372 
4373  return $str;
4374  }
4375 
4376  function getFileSizeInfo()
4377  {
4378  global $lng;
4379 
4380  // get the value for the maximal uploadable filesize from the php.ini (if available)
4381  $umf=get_cfg_var("upload_max_filesize");
4382  // get the value for the maximal post data from the php.ini (if available)
4383  $pms=get_cfg_var("post_max_size");
4384 
4385  // use the smaller one as limit
4386  $max_filesize=min($umf, $pms);
4387  if (!$max_filesize) $max_filesize=max($umf, $pms);
4388 
4389  return $lng->txt("file_notice")." $max_filesize.";
4390  }
4391 
4398  function __extractRefId($role_title)
4399  {
4400 
4401  $test_str = explode('_',$role_title);
4402 
4403  if ($test_str[0] == 'il')
4404  {
4405  $test2 = (int) $test_str[3];
4406  return is_numeric ($test2) ? (int) $test2 : false;
4407  }
4408  return false;
4409  }
4410 
4420  function __extractId($ilias_id, $inst_id)
4421  {
4422 
4423  $test_str = explode('_',$ilias_id);
4424 
4425  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4426  {
4427  $test2 = (int) $test_str[3];
4428  return is_numeric ($test2) ? (int) $test2 : false;
4429  }
4430  return false;
4431  }
4432 
4445  function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4446  {
4447  global $ilDB;
4448 
4449  if(!$a_ids)
4450  {
4451  return array();
4452  }
4453 
4454  // use database to sort user array
4455  $where = "WHERE ".$a_id_name." IN (";
4456  $where .= implode(",", ilUtil::quoteArray($a_ids));
4457  $where .= ") ";
4458 
4459  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4460  $where.
4461  "ORDER BY ".$a_field;
4462 
4463  $res = $ilDB->query($query);
4464  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4465  {
4466  $ids[] = $row->$a_id_name;
4467  }
4468  return $ids ? $ids : array();
4469  }
4470 
4478  function getMySQLTimestamp($a_ts)
4479  {
4480  global $ilDB;
4481 
4482  return $a_ts;
4483  }
4484 
4488  function quoteArray($a_array)
4489  {
4490  global $ilDB;
4491 
4492 
4493  if(!is_array($a_array) or !count($a_array))
4494  {
4495  return array("''");
4496  }
4497 
4498  foreach($a_array as $k => $item)
4499  {
4500  $a_array[$k] = $ilDB->quote($item);
4501  }
4502 
4503  return $a_array;
4504  }
4505 
4512  public static function sendInfo($a_info = "",$a_keep = false)
4513  {
4514  global $tpl;
4515  $tpl->setMessage("info", $a_info, $a_keep);
4516  }
4517 
4524  public static function sendFailure($a_info = "",$a_keep = false)
4525  {
4526  global $tpl;
4527  $tpl->setMessage("failure", $a_info, $a_keep);
4528  }
4529 
4536  public static function sendQuestion($a_info = "",$a_keep = false)
4537  {
4538  global $tpl;
4539  $tpl->setMessage("question", $a_info, $a_keep);
4540  }
4541 
4548  public static function sendSuccess($a_info = "",$a_keep = false)
4549  {
4550  global $tpl;
4551  $tpl->setMessage("success", $a_info, $a_keep);
4552  }
4553 
4554  function infoPanel($a_keep = true)
4555  {
4556  global $tpl,$ilias,$lng;
4557 
4558  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4559  {
4560  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html");
4561  $tpl->setCurrentBlock("infopanel");
4562 
4563  if (!empty($_SESSION["infopanel"]["text"]))
4564  {
4565  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4566  ilFrameTargetInfo::_getFrame("MainContent").
4567  "\">";
4568  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4569  $link .= "</a>";
4570  }
4571 
4572  // deactivated
4573  if (!empty($_SESSION["infopanel"]["img"]))
4574  {
4575  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4576  ilFrameTargetInfo::_getFrame("MainContent").
4577  "\">";
4578  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4579  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4580  $link .= "</a></td>";
4581  }
4582 
4583  $tpl->setVariable("INFO_ICONS",$link);
4584  $tpl->parseCurrentBlock();
4585  }
4586 
4587  //if (!$a_keep)
4588  //{
4589  session_unregister("infopanel");
4590  //}
4591  }
4592 
4593 
4600  function dirsize($directory)
4601  {
4602  $size = 0;
4603  if (!is_dir($directory))
4604  {
4605  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4606  // dirsize of non-existing directory
4607  $size = @filesize($directory);
4608  // END DiskQuota Suppress PHP warning.
4609  return ($size === false) ? -1 : $size;
4610  }
4611  if ($DIR = opendir($directory))
4612  {
4613  while (($dirfile = readdir($DIR)) !== false)
4614  {
4615  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4616  continue;
4617  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4618  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4619  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
4620  {
4621  // BEGIN DiskQuota: dirsize is not a global function anymore
4622  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4623  // END DiskQuota: dirsize is not a global function anymore
4624  if ($dirSize >= 0)
4625  $size += $dirSize;
4626  else return -1;
4627  }
4628  }
4629  closedir($DIR);
4630  }
4631  return $size;
4632  }
4633 
4634  function randomhash()
4635  {
4636  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
4637  }
4638 
4639  public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4640  {
4641  /*
4642  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4643  else $expire = time() - (365*24*60*60);
4644  */
4645  // Temporary fix for feed.php
4646  if(!(bool)$a_set_cookie_invalid) $expire = 0;
4647  else $expire = time() - (365*24*60*60);
4648 
4649  // setcookie() supports 5th parameter
4650  // only for php version 5.2.0 and above
4651  if( version_compare(PHP_VERSION, '5.2.0', '>=') )
4652  {
4653  // PHP version >= 5.2.0
4654  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4655  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
4656  );
4657  }
4658  else
4659  {
4660  // PHP version < 5.2.0
4661  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4662  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE
4663  );
4664  }
4665 
4666  if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
4667  }
4668 
4669  public static function _sanitizeFilemame($a_filename)
4670  {
4671  return strip_tags(self::stripSlashes($a_filename));
4672  }
4673 } // END class.ilUtil
4674 
4675 
4676 ?>