ILIAS  Release_4_2_x_branch Revision 61807
 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 {
29  public static function getImageTagByType($a_type, $a_path, $a_big = false)
30  {
31  global $lng;
32 
33  if ($a_big)
34  {
35  $big = "_b";
36  }
37  $filename = "icon_".$a_type."$big.gif";
38 
39  return "<img src=\"".ilUtil::getImagePath($filename)."\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
40  //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\"/>";
41  }
42 
55  public static function getTypeIconPath($a_type,$a_obj_id,$a_size = 'small')
56  {
57  global $ilSetting;
58 
59  if($ilSetting->get("custom_icons"))
60  {
61  switch($a_type)
62  {
63  case 'cat':
64  case 'crs':
65  case 'grp':
66  include_once('./Services/Container/classes/class.ilContainer.php');
67  if(strlen($path = ilContainer::_lookupIconPath($a_obj_id,$a_size)))
68  {
69  return $path;
70  }
71  }
72  }
73 
74  switch($a_size)
75  {
76  case 'tiny':
77  $postfix = '_s.gif';
78  break;
79  case 'big':
80  $postfix = '_b.gif';
81  break;
82  default:
83  $postfix = '.gif';
84  break;
85  }
86  return ilUtil::getImagePath('icon_'.$a_type.$postfix);
87  }
88 
99  public static function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
100  {
101  global $ilias, $styleDefinition, $ilCtrl, $ilUser;
102 
103  if (is_int(strpos($_SERVER["PHP_SELF"], "setup.php")))
104  {
105  $module_path = "..";
106  }
107  if ($module_path != "")
108  {
109  $module_path = "/".$module_path;
110  }
111 
112  // default image
113  $default_img = ".".$module_path."/templates/default/images/".$img;
114 
115  // use ilStyleDefinition instead of account to get the current skin and style
116  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
117  $current_skin = ilStyleDefinition::getCurrentSkin();
118  $current_style = ilStyleDefinition::getCurrentStyle();
119 
120  if (is_object($styleDefinition))
121  {
122  $image_dir = $styleDefinition->getImageDirectory($current_style);
123  }
124  if ($current_skin == "default")
125  {
126  $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
127  $skin_img = ".".$module_path."/templates/default/images/".$img;
128  }
129  else if (is_object($styleDefinition) && $current_skin != "default")
130  {
131  $user_img = "./Customizing/global/skin/".
132  $current_skin.$module_path."/".$image_dir."/".$img;
133  $skin_img = "./Customizing/global/skin/".
134  $current_skin.$module_path."/images/".$img;
135  }
136 
137  if ($offline)
138  {
139  return "./images/".$img;
140  }
141  else if (@file_exists($user_img) && $image_dir != "")
142  {
143  return $user_img; // found image for skin and style
144  }
145  else if (file_exists($skin_img))
146  {
147  return $skin_img; // found image in skin/images
148  }
149 
150  return $default_img; // take image in default
151  }
152 
163  public static function getHtmlPath($relative_path)
164  {
165  if (substr($relative_path, 0, 2) == './')
166  {
167  $relative_path = (substr($relative_path, 1));
168  }
169  if (substr($relative_path, 0, 1) != '/')
170  {
171  $relative_path = '/' . $relative_path;
172  }
173  $htmlpath = ILIAS_HTTP_PATH . $relative_path;
174  return $htmlpath;
175  }
176 
189  public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
190  {
191  global $ilias;
192 
193  // add version as parameter to force reload for new releases
194  // use ilStyleDefinition instead of account to get the current style
195  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
196  $stylesheet_name = (strlen($a_css_name)) ? $a_css_name : ilStyleDefinition::getCurrentStyle().".css";
197  if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0)) $a_css_location = $a_css_location . "/";
198 
199  $filename = "";
200  // use ilStyleDefinition instead of account to get the current skin
201  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
202  if (ilStyleDefinition::getCurrentSkin() != "default")
203  {
204  $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_css_location.$stylesheet_name;
205  }
206  if (strlen($filename) == 0 || !file_exists($filename))
207  {
208  $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
209  }
210  $vers = "";
211  if ($mode != "filesystem")
212  {
213  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
214  $vers = "?vers=".str_replace(".", "-", $vers);
215  }
216  return $filename . $vers;
217  }
218 
229  public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
230  {
231  global $ilias;
232 
233  // add version as parameter to force reload for new releases
234  $js_name = $a_js_name;
235  if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
236 
237  $filename = "";
238  // use ilStyleDefinition instead of account to get the current skin
239  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
240  if (ilStyleDefinition::getCurrentSkin() != "default")
241  {
242  $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_js_location.$js_name;
243  }
244  if (strlen($filename) == 0 || !file_exists($filename))
245  {
246  $filename = "./" . $a_js_location . "templates/default/".$js_name;
247  }
248  $vers = "";
249  if ($add_version)
250  {
251  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
252  $vers = "?vers=".str_replace(".", "-", $vers);
253  }
254  return $filename . $vers;
255  }
256 
264  public static function getP3PLocation()
265  {
266  global $ilias;
267 
268  if (defined("ILIAS_MODULE"))
269  {
270  $base = '';
271  for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
272  {
273  $base .= "../Services/Privacy/";
274  }
275  }
276  else
277  {
278  $base = "./Services/Privacy/";
279  }
280 
281  if (is_file($base."w3c/p3p.xml"))
282  {
283  return ILIAS_HTTP_PATH."w3c/p3p.xml";
284  }
285  else
286  {
287  return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
288  }
289  }
290 
298  public static function getNewContentStyleSheetLocation($mode = "output")
299  {
300  global $ilias;
301 
302  // add version as parameter to force reload for new releases
303  if ($mode != "filesystem")
304  {
305  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
306  $vers = "?vers=".str_replace(".", "-", $vers);
307  }
308 
309  // use ilStyleDefinition instead of account to get the current skin and style
310  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
311  if (ilStyleDefinition::getCurrentSkin() == "default")
312  {
313  $in_style = "./templates/".ilStyleDefinition::getCurrentSkin()."/"
314  .ilStyleDefinition::getCurrentStyle()."_cont.css";
315  }
316  else
317  {
318  $in_style = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/"
319  .ilStyleDefinition::getCurrentStyle()."_cont.css";
320  }
321 
322  if (is_file("./".$in_style))
323  {
324  return $in_style.$vers;
325  }
326  else
327  {
328  return "templates/default/delos_cont.css".$vers;
329  }
330  }
331 
350  public static function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
351  $style_class = "", $attribs = "",$disabled = false)
352  {
353  global $lng;
354 
355  if ($multiple == true)
356  {
357  $multiple = " multiple=\"multiple\"";
358  }
359  else
360  {
361  $multiple = "";
362  $size = 0;
363  }
364 
365  if ($style_class != "")
366  {
367  $class = " class=\"".$style_class."\"";
368  }
369  else
370  {
371  $class = "";
372  }
373  $attributes = "";
374  if (is_array($attribs))
375  {
376  foreach ($attribs as $key => $val)
377  {
378  $attributes .= " ".$key."=\"".$val."\"";
379  }
380  }
381  if($disabled)
382  {
383  $disabled = ' disabled=\"disabled\"';
384  }
385 
386  $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
387 
388  foreach ((array) $options as $key => $val)
389  {
390  $style = "";
391  if (is_array($val))
392  {
393  $style = $val["style"];
394  $val = $val["text"]; // mus be last line, since we overwrite
395  }
396 
397  $sty = ($style != "")
398  ? ' style="'.$style.'" '
399  : "";
400 
401  if ($direct_text)
402  {
403  $str .= " <option $sty value=\"".$key."\"";
404  }
405  else
406  {
407  $str .= " <option $sty value=\"".$val."\"";
408  }
409  if (is_array($selected) )
410  {
411  if (in_array($key,$selected))
412  {
413  $str .= " selected=\"selected\"";
414  }
415  }
416  else if ($selected == $key)
417  {
418  $str .= " selected=\"selected\"";
419  }
420 
421  if ($direct_text)
422  {
423  $str .= ">".$val."</option>\n";
424  }
425  else
426  {
427  $str .= ">".$lng->txt($val)."</option>\n";
428  }
429  }
430 
431  $str .= "</select>\n";
432 
433  return $str;
434  }
435 
445  public static function getSelectName ($selected,$values)
446  {
447  return($values[$selected]);
448  }
449 
461  public static function formCheckbox ($checked,$varname,$value,$disabled = false)
462  {
463  $str = "<input type=\"checkbox\" name=\"".$varname."\"";
464 
465  if ($checked == 1)
466  {
467  $str .= " checked=\"checked\"";
468  }
469 
470  if ($disabled)
471  {
472  $str .= " disabled=\"disabled\"";
473  }
474 
475  $array_var = false;
476 
477  if (substr($varname,-2) == "[]")
478  {
479  $array_var = true;
480  }
481 
482  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
483  if ($array_var)
484  {
485  $varname_id = substr($varname,0,-2)."_".$value;
486  }
487  else
488  {
489  $varname_id = $varname;
490  }
491 
492  // dirty removal of other "[]" in string
493  $varname_id = ereg_replace("\[","_",$varname_id);
494  $varname_id = ereg_replace("\]","",$varname_id);
495 
496  $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
497 
498  return $str;
499  }
500 
512  public static function formDisabledRadioButton($checked,$varname,$value,$disabled)
513  {
514  if ($disabled) {
515  $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
516  }
517  else {
518  $str = "<input type=\"radio\" name=\"".$varname."\"";
519  }
520  if ($checked == 1)
521  {
522  $str .= " checked=\"checked\"";
523  }
524 
525  $str .= " value=\"".$value."\"";
526  $str .= " id=\"".$value."\" />\n";
527 
528  return $str;
529 
530  }
531 
532 
543  public static function formRadioButton($checked,$varname,$value)
544  {
545  $str = "<input type=\"radio\" name=\"".$varname."\"";
546  if ($checked == 1)
547  {
548  $str .= " checked=\"checked\"";
549  }
550 
551  $str .= " value=\"".$value."\"";
552 
553  $str .= " id=\"".$value."\" />\n";
554 
555  return $str;
556  }
557 
558 
568  public static function formInput($varname,$value,$disabled = false)
569  {
570 
571  $str = "<input type=\"input\" name=\"".$varname."\"";
572  if ($disabled)
573  {
574  $str .= " disabled";
575  }
576 
577  $str .= " value=\"".$value."\"";
578 
579  $str .= " id=\"".$value."\" />\n";
580 
581  return $str;
582  }
583 
584 
591  public static function checkInput ($vars)
592  {
593  // TO DO:
594  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
595  }
596 
603  public static function setPathStr ($a_path)
604  {
605  if ("" != $a_path && "/" != substr($a_path, -1))
606  {
607  $a_path .= "/";
608  //$a_path = substr($a_path,1);
609  }
610 
611  //return getcwd().$a_path;
612  return $a_path;
613  }
614 
627  public static function switchColor ($a_num,$a_css1,$a_css2)
628  {
629  if (!($a_num % 2))
630  {
631  return $a_css1;
632  }
633  else
634  {
635  return $a_css2;
636  }
637  }
638 
650  static function showTabs($a_hl, $a_o)
651  {
652  global $lng;
653 
654  $tpltab = new ilTemplate("tpl.tabs.html", true, true);
655 
656  for ($i=1; $i<=4; $i++)
657  {
658  $tpltab->setCurrentBlock("tab");
659  if ($a_hl == $i)
660  {
661  $tabtype = "tabactive";
662  $tab = $tabtype;
663  }
664  else
665  {
666  $tabtype = "tabinactive";
667  $tab = "tab";
668  }
669 
670  switch ($i)
671  {
672  case 1:
673  $txt = $lng->txt("view_content");
674  break;
675  case 2:
676  $txt = $lng->txt("edit_properties");
677  break;
678  case 3:
679  $txt = $lng->txt("perm_settings");
680  break;
681  case 4:
682  $txt = $lng->txt("show_owner");
683  break;
684  } // switch
685  $tpltab->setVariable("CONTENT", $txt);
686  $tpltab->setVariable("TABTYPE", $tabtype);
687  $tpltab->setVariable("TAB", $tab);
688  $tpltab->setVariable("LINK", $a_o["LINK".$i]);
689  $tpltab->parseCurrentBlock();
690  }
691 
692  return $tpltab->get();
693  }
694 
695 
696 
705  public static function checkFormEmpty ($emptyFields)
706  {
707 
708  $feedback = "";
709 
710  foreach ($emptyFields as $key => $val)
711  {
712  if ($val == "") {
713  if ($feedback != "") $feedback .= ", ";
714  $feedback .= $key;
715  }
716  }
717 
718  return $feedback;
719  }
720 
745  public static function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
746  {
747  $LinkBar = "";
748 
749  $layout_link = "";
750  $layout_prev = "&lt;&lt;";
751  $layout_next = "&gt;&gt;";
752 
753  // layout options
754  if (count($ALayout > 0))
755  {
756  if ($ALayout["link"])
757  {
758  $layout_link = " class=\"".$ALayout["link"]."\"";
759  }
760 
761  if ($ALayout["prev"])
762  {
763  $layout_prev = $ALayout["prev"];
764  }
765 
766  if ($ALayout["next"])
767  {
768  $layout_next = $ALayout["next"];
769  }
770  }
771 
772  // show links, if hits greater limit
773  // or offset > 0 (can be > 0 due to former setting)
774  if ($AHits > $ALimit || $AOffset > 0)
775  {
776  if (!empty($AParams))
777  {
778  foreach ($AParams as $key => $value)
779  {
780  $params.= $key."=".$value."&";
781  }
782  }
783  // if ($params) $params = substr($params,0,-1);
784  if(strpos($AScript,'&'))
785  {
786  $link = $AScript."&".$params.$prefix."offset=";
787  }
788  else
789  {
790  $link = $AScript."?".$params.$prefix."offset=";
791  }
792 
793  // ?bergehe "zurck"-link, wenn offset 0 ist.
794  if ($AOffset >= 1)
795  {
796  $prevoffset = $AOffset - $ALimit;
797  if ($prevoffset < 0) $prevoffset = 0;
798  $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
799  }
800 
801  // Ben?tigte Seitenzahl kalkulieren
802  $pages=intval($AHits/$ALimit);
803 
804  // Wenn ein Rest bleibt, addiere eine Seite
805  if (($AHits % $ALimit))
806  $pages++;
807 
808  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
809  // if ($AOffset != 0) {
810 
811  // ansonsten zeige Links zu den anderen Seiten an
812  for ($i = 1 ;$i <= $pages ; $i++)
813  {
814  $newoffset=$ALimit*($i-1);
815 
816  if ($newoffset == $AOffset)
817  {
818  $LinkBar .= "[".$i."] ";
819  }
820  else
821  {
822  $LinkBar .= '<a '.$layout_link.' href="'.
823  $link.$newoffset.'">['.$i.']</a> ';
824  }
825  }
826  // }
827 
828  // Checken, ob letze Seite erreicht ist
829  // Wenn nicht, gebe einen "Weiter"-Link aus
830  if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
831  {
832  $newoffset=$AOffset+$ALimit;
833  $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
834  }
835 
836  return $LinkBar;
837  }
838  else
839  {
840  return false;
841  }
842  }
843 
855  public static function makeClickable($a_text, $detectGotoLinks = false)
856  {
857  // New code, uses MediaWiki Sanitizer
858  $ret = $a_text;
859 
860  // www-URL ohne ://-Angabe
861  $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
862  "\\1http://\\2\\3", $ret);
863 
864  // ftp-URL ohne ://-Angabe
865  $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
866  "\\1ftp://\\2\\3", $ret);
867 
868  // E-Mail (this does not work as expected, users must add mailto: manually)
869  //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
870  // "mailto:\\1", $ret);
871 
872  // mask existing image tags
873  $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
874 
875  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
876  $parser = new ilMWParserAdapter();
877  $ret = $parser->replaceFreeExternalLinks($ret);
878 
879  // unmask existing image tags
880  $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
881 
882  // Should be Safe
883 
884  if ($detectGotoLinks)
885  // replace target blank with self and text with object title.
886  {
887  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
888 // echo htmlentities($regExp);
889  $ret = preg_replace_callback(
890  "/".$regExp."/i",
891  array("ilUtil", "replaceLinkProperties"),
892  $ret);
893 
894  // Static links
895  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
896 // echo htmlentities($regExp);
897  $ret = preg_replace_callback(
898  "/".$regExp."/i",
899  array("ilUtil", "replaceLinkProperties"),
900  $ret);
901  }
902 
903  return($ret);
904  }
905 
919  public static function replaceLinkProperties ($matches)
920  {
921  $link = $matches[0];
922  $ref_id = $matches[2];
923 
924  if ($ref_id > 0)
925  {
926  $obj_id = ilObject::_lookupObjId($ref_id);
927  if ($obj_id > 0)
928  {
929  $title = ilObject::_lookupTitle($obj_id);
930  $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
931  }
932  }
933  return $link;
934  }
935 
954  public static function StopWatch($begin = -1)
955  {
956  $m = explode(" ",microtime());
957  $m = $m[0] + $m[1];
958 
959  if ($begin != -1)
960  {
961  $m = $m - $begin;
962  }
963 
964  return($m);
965  }
966 
985  public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
986  {
987  global $lng;
988 
989  $disabled = '';
990  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
991  {
992  $disabled = 'disabled="disabled" ';
993  }
994 
995  $now = getdate();
996  if (!$emptyoption)
997  {
998  if (!strlen($year)) $year = $now["year"];
999  if (!strlen($month)) $month = $now["mon"];
1000  if (!strlen($day)) $day = $now["mday"];
1001  }
1002 
1003  $year = (int) $year;
1004  $month = (int) $month;
1005  $day = (int) $day;
1006 
1007  // build day select
1008 
1009  $sel_day .= '<select ';
1010  if(isset($a_further_options['select_attributes']))
1011  {
1012  foreach($a_further_options['select_attributes'] as $name => $value)
1013  {
1014  $sel_day .= ($name.'="'.$value.'" ');
1015  }
1016  }
1017 
1018  $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
1019 
1020  if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
1021  for ($i = 1; $i <= 31; $i++)
1022  {
1023  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1024  }
1025  $sel_day .= "</select>\n";
1026  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
1027 
1028  // build month select
1029  $sel_month = '<select ';
1030  if(isset($a_further_options['select_attributes']))
1031  {
1032  foreach($a_further_options['select_attributes'] as $name => $value)
1033  {
1034  $sel_month .= ($name.'="'.$value.'" ');
1035  }
1036  }
1037  $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
1038 
1039  if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
1040  for ($i = 1; $i <= 12; $i++)
1041  {
1042  if($a_long_month)
1043  {
1044  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
1045  }
1046  else
1047  {
1048  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
1049  }
1050  }
1051  $sel_month .= "</select>\n";
1052  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
1053 
1054  // build year select
1055  $sel_year = '<select ';
1056  if(isset($a_further_options['select_attributes']))
1057  {
1058  foreach($a_further_options['select_attributes'] as $name => $value)
1059  {
1060  $sel_year .= ($name.'="'.$value.'" ');
1061  }
1062  }
1063  $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
1064  if ((strlen($startyear) == 0) || ($startyear > $year))
1065  {
1066  if (!$emptyoption || $year != 0) $startyear = $year - 5;
1067  }
1068 
1069  if(($year + 5) < (date('Y',time()) + 5))
1070  {
1071  $end_year = date('Y',time()) + 5;
1072  }
1073  else
1074  {
1075  $end_year = $year + 5;
1076  }
1077 
1078  if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
1079  for ($i = $startyear; $i <= $end_year; $i++)
1080  {
1081  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
1082  }
1083  $sel_year .= "</select>\n";
1084  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
1085 
1086  //$dateformat = $lng->text["lang_dateformat"];
1087  $dateformat = "d-m-Y";
1088  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1089  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1090  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1091  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1092  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1093  return $dateformat;
1094  }
1095 
1114  public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1115  {
1116  global $lng, $ilUser;
1117 
1118  $minute_steps = 1;
1119  $disabled = '';
1120  if(count($a_further_options))
1121  {
1122  if(isset($a_further_options['minute_steps']))
1123  {
1124  $minute_steps = $a_further_options['minute_steps'];
1125  }
1126  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1127  {
1128  $disabled = 'disabled="disabled" ';
1129  }
1130  }
1131 
1132  if ($a_use_default and !strlen("$hour$minute$second")) {
1133  $now = localtime();
1134  $hour = $now[2];
1135  $minute = $now[1];
1136  $second = $now[0];
1137  } else {
1138  $hour = (int)$hour;
1139  $minute = (int)$minute;
1140  $second = (int)$second;
1141  }
1142  // build hour select
1143  $sel_hour = '<select ';
1144  if(isset($a_further_options['select_attributes']))
1145  {
1146  foreach($a_further_options['select_attributes'] as $name => $value)
1147  {
1148  $sel_hour .= $name.'='.$value.' ';
1149  }
1150  }
1151  $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\">\n";
1152 
1153  $format = $ilUser->getTimeFormat();
1154  for ($i = 0; $i <= 23; $i++)
1155  {
1156  if($format == ilCalendarSettings::TIME_FORMAT_24)
1157  {
1158  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1159  }
1160  else
1161  {
1162  $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1163  }
1164  }
1165  $sel_hour .= "</select>\n";
1166  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1167 
1168  // build minutes select
1169  $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
1170 
1171  for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1172  {
1173  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1174  }
1175  $sel_minute .= "</select>\n";
1176  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1177 
1178  if (!$short) {
1179  // build seconds select
1180  $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\">\n";
1181 
1182  for ($i = 0; $i <= 59; $i++)
1183  {
1184  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1185  }
1186  $sel_second .= "</select>\n";
1187  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1188  }
1189  $timeformat = $lng->text["lang_timeformat"];
1190  if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1191  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1192  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1193  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1194  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1195  if ($short) {
1196  $timeformat = preg_replace("/%%s/", "", $timeformat);
1197  } else {
1198  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1199  }
1200  return $timeformat;
1201  }
1202 
1216  public static function is_email($a_email)
1217  {
1218  // BEGIN Mail: If possible, use PearMail to validate e-mail address
1219  global $ilErr, $ilias;
1220 
1221  // Note the use of @include_once here. We need this, because
1222  // inclusion fails when the function is_email is called from setup.php.
1223  $successfulInclude = @include_once ('Services/Mail/classes/class.ilMail.php');
1224 
1225  // additional checks for include and ilias object are needed,
1226  // otherwise setup will fail with this if branch
1227  if ($successfulInclude && is_object($ilias) && ilMail::_usePearMail())
1228  {
1229  require_once 'Mail/RFC822.php';
1230  $parser = &new Mail_RFC822();
1232  try {
1233  $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1234  if (! is_a($addresses, 'PEAR_Error') &&
1235  count($addresses) == 1 && $addresses[0]->host != 'ilias')
1236  {
1237  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1238  return true;
1239  }
1240  } catch (Exception $e) {
1241  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1242  return false;
1243  }
1244  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1245  return false;
1246  }
1247  else
1248  {
1249  $tlds = strtolower(
1250  "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|".
1251  "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|".
1252  "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|".
1253  "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|".
1254  "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|".
1255  "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|".
1256  "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|".
1257  "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|".
1258  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1259 
1260  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));
1261  }
1262  // END Mail: If possible, use PearMail to validate e-mail address
1263  }
1264 
1273  public static function isPassword($a_passwd, &$customError = null)
1274  {
1275  global $lng;
1276 
1277  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1278  $security = ilSecuritySettings::_getInstance();
1279 
1280  if( $security->getAccountSecurityMode() != ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1281  {
1283 
1284  $customError = null;
1285 
1286  switch( true )
1287  {
1288  // no empty password
1289  case empty($a_passwd):
1290 
1291  // min password length is 6
1292  case strlen($a_passwd) < 6:
1293 
1294  // valid chars for password
1295  case !preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~]+$/", $a_passwd):
1296 
1297  return false;
1298 
1299  default:
1300 
1301  return true;
1302  }
1303  }
1304 
1306 
1307  // check if password is empty
1308  if( empty($a_passwd) )
1309  {
1310  $customError = $lng->txt('password_empty');
1311  return false;
1312  }
1313 
1314  $isPassword = true;
1315  $errors = array();
1316 
1317  // check if password to short
1318  if( $security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength() )
1319  {
1320  $errors[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1321  $isPassword = false;
1322  }
1323 
1324  // check if password not to long
1325  if( $security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength() )
1326  {
1327  $errors[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1328  $isPassword = false;
1329  }
1330 
1331  // if password must contains Chars and Numbers
1332  if( $security->isPasswordCharsAndNumbersEnabled() )
1333  {
1334  $hasCharsAndNumbers = true;
1335 
1336  // check password for existing chars
1337  if( !preg_match('/[A-Za-z]+/',$a_passwd) )
1338  {
1339  $hasCharsAndNumbers = false;
1340  }
1341 
1342  // check password for existing numbers
1343  if( !preg_match('/[0-9]+/',$a_passwd) )
1344  {
1345  $hasCharsAndNumbers = false;
1346  }
1347 
1348  if( !$hasCharsAndNumbers )
1349  {
1350  $errors[] = $lng->txt('password_must_chars_and_numbers');
1351  $isPassword = false;
1352  }
1353  }
1354 
1355  // if password must contains Special-Chars
1356  if( $security->isPasswordSpecialCharsEnabled() )
1357  {
1358  $specialCharsReg = '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1359 
1360  // check password for existing special-chars
1361  if( !preg_match($specialCharsReg, $a_passwd) )
1362  {
1363  $errors[] = $lng->txt('password_must_special_chars');
1364  $isPassword = false;
1365  }
1366  }
1367 
1368  // ensure password matches the positive list of chars/special-chars
1369  if( !preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/", $a_passwd) )
1370  {
1371  $errors[] = $lng->txt('password_contains_invalid_chars');
1372  $isPassword = false;
1373  }
1374 
1375  // build custom error message
1376  if( count($errors) == 1 )
1377  {
1378  $customError = $errors[0];
1379  }
1380  elseif( count($errors) > 1 )
1381  {
1382  $customError = $lng->txt('password_multiple_errors');
1383  $customError .= '<br />'.implode('<br />', $errors);
1384  }
1385 
1386  return $isPassword;
1387  }
1388 
1397  public static function getPasswordRequirementsInfo()
1398  {
1399  global $lng;
1400 
1401  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1402  $security = ilSecuritySettings::_getInstance();
1403 
1404  if( $security->getAccountSecurityMode() == ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1405  {
1406  $validPasswordChars = 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1407  }
1408  else
1409  {
1410  $validPasswordChars = 'A-Z a-z 0-9 _.+?#-*@!$%~';
1411  }
1412 
1413  return sprintf($lng->txt('password_allow_chars'), $validPasswordChars);
1414  }
1415 
1416  /*
1417  * validates a login
1418  * @access public
1419  * @param string login
1420  * @return boolean true if valid
1421  */
1422  function isLogin($a_login)
1423  {
1424  if (empty($a_login))
1425  {
1426  return false;
1427  }
1428 
1429  if (strlen($a_login) < 3)
1430  {
1431  return false;
1432  }
1433 
1434  // FIXME - If ILIAS is configured to use RFC 822
1435  // compliant mail addresses we should not
1436  // allow the @ character.
1437  if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1438  {
1439  return false;
1440  }
1441 
1442  return true;
1443  }
1444 
1458  public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1459  $a_keep_extension = false)
1460  {
1461  include_once("./Services/Utilities/classes/class.ilStr.php");
1462  if (ilStr::strLen($a_str) > $a_len)
1463  {
1464  if ($a_next_blank)
1465  {
1466  $len = ilStr::strPos($a_str, " ", $a_len);
1467  }
1468  else
1469  {
1470  $len = $a_len;
1471  }
1472  // BEGIN WebDAV
1473  // - Shorten names in the middle, before the filename extension
1474  // Workaround for Windows WebDAV Client:
1475  // Use the unicode ellipsis symbol for shortening instead of
1476  // three full stop characters.
1477  if ($a_keep_extension)
1478  {
1479  $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1480  }
1481  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1482  {
1483  $a_str = ilStr::subStr($a_str,0,$len);
1484  if ($a_dots)
1485  {
1486  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1487  }
1488  }
1489  else
1490  {
1491  if ($a_dots)
1492  {
1493  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1494  }
1495  else
1496  {
1497  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1498  }
1499  }
1500  }
1501 
1502  return $a_str;
1503  }
1504 
1515  public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1516  {
1517  include_once("./Services/Utilities/classes/class.ilStr.php");
1518  $str_arr = explode(" ", $a_str);
1519 
1520  for ($i = 0; $i < count($str_arr); $i++)
1521  {
1522  if (ilStr::strLen($str_arr[$i]) > $a_len)
1523  {
1524  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1525  if ($a_dots)
1526  {
1527  $str_arr[$i].= "...";
1528  }
1529  }
1530  }
1531 
1532  return implode($str_arr, " ");
1533  }
1534 
1544  public static function attribsToArray($a_str)
1545  {
1546  $attribs = array();
1547  while (is_int(strpos($a_str, "=")))
1548  {
1549  $eq_pos = strpos($a_str, "=");
1550  $qu1_pos = strpos($a_str, "\"");
1551  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1552  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1553  {
1554  $var = trim(substr($a_str, 0, $eq_pos));
1555  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1556  $attribs[$var] = $val;
1557  $a_str = substr($a_str, $qu2_pos + 1);
1558  }
1559  else
1560  {
1561  $a_str = "";
1562  }
1563  }
1564  return $attribs;
1565  }
1566 
1578  public static function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1579  {
1580  // check if arguments are directories
1581  if (!@is_dir($a_sdir) or
1582  !@is_dir($a_tdir))
1583  {
1584  return FALSE;
1585  }
1586 
1587  // read a_sdir, copy files and copy directories recursively
1588  $dir = opendir($a_sdir);
1589 
1590  while($file = readdir($dir))
1591  {
1592  if ($file != "." and
1593  $file != "..")
1594  {
1595  // directories
1596  if (@is_dir($a_sdir."/".$file))
1597  {
1598  if (!@is_dir($a_tdir."/".$file))
1599  {
1600  if (!ilUtil::makeDir($a_tdir."/".$file))
1601  return FALSE;
1602 
1603  //chmod($a_tdir."/".$file, 0775);
1604  }
1605 
1606  if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1607  {
1608  return FALSE;
1609  }
1610  }
1611 
1612  // files
1613  if (@is_file($a_sdir."/".$file))
1614  {
1615  if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1616  {
1617  return FALSE;
1618  }
1619  if ($preserveTimeAttributes)
1620  touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1621  }
1622  }
1623  }
1624  return TRUE;
1625  }
1626 
1635  public static function getWebspaceDir($mode = "filesystem")
1636  {
1637  global $ilias;
1638 
1639  if ($mode == "filesystem")
1640  {
1641  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1642  }
1643  else
1644  {
1645  if (defined("ILIAS_MODULE"))
1646  {
1647  return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1648  }
1649  else
1650  {
1651  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1652  }
1653  }
1654 
1655  //return $ilias->ini->readVariable("server","webspace_dir");
1656  }
1657 
1664  public static function getDataDir()
1665  {
1666  return CLIENT_DATA_DIR;
1667  //global $ilias;
1668 
1669  //return $ilias->ini->readVariable("server", "data_dir");
1670  }
1671 
1681  public static function getUsersOnline($a_user_id = 0)
1682  {
1683  include_once("./Services/User/classes/class.ilObjUser.php");
1684  return ilObjUser::_getUsersOnline($a_user_id);
1685  }
1686 
1697  public static function getAssociatedUsersOnline($a_user_id)
1698  {
1699  include_once("./Services/User/classes/class.ilObjUser.php");
1700  return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1701  }
1702 
1710  public static function ilTempnam()
1711  {
1712  $temp_path = ilUtil::getDataDir() . "/temp";
1713  if (!is_dir($temp_path))
1714  {
1715  ilUtil::createDirectory($temp_path);
1716  }
1717  $temp_name = tempnam($temp_path, "tmp");
1718  // --->
1719  // added the following line because tempnam creates a backslash on some
1720  // Windows systems which leads to problems, because the "...\tmp..." can be
1721  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1722  // even under windows (Helmut Schottmüller, 2005-08-31)
1723  $temp_name = str_replace("\\", "/", $temp_name);
1724  // --->
1725  unlink($temp_name);
1726  return $temp_name;
1727  }
1728 
1737  public static function createDirectory($a_dir, $a_mod = 0755)
1738  {
1739  ilUtil::makeDir($a_dir);
1740  //@mkdir($a_dir);
1741  //@chmod($a_dir, $a_mod);
1742  }
1743 
1744 
1753  public static function unzip($a_file, $overwrite = false, $a_flat = false)
1754  {
1755  if (!is_file($a_file))
1756  {
1757  return;
1758  }
1759 
1760  // if flat, move file to temp directory first
1761  if ($a_flat)
1762  {
1763  $tmpdir = ilUtil::ilTempnam();
1764  ilUtil::makeDir($tmpdir);
1765  copy($a_file, $tmpdir.DIRECTORY_SEPARATOR.basename($a_file));
1766  $orig_file = $a_file;
1767  $a_file = $tmpdir.DIRECTORY_SEPARATOR.basename($a_file);
1768  $origpathinfo = pathinfo($orig_file);
1769  }
1770 
1771  $pathinfo = pathinfo($a_file);
1772  $dir = $pathinfo["dirname"];
1773  $file = $pathinfo["basename"];
1774 
1775  // unzip
1776  $cdir = getcwd();
1777  chdir($dir);
1778  $unzip = PATH_TO_UNZIP;
1779 
1780  // workaround for unzip problem (unzip of subdirectories fails, so
1781  // we create the subdirectories ourselves first)
1782  // get list
1783  $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1784  $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1785  $zdirs = array();
1786 
1787  foreach($arr as $line)
1788  {
1789  if(is_int(strpos($line, "/")))
1790  {
1791  $zdir = substr($line, 0, strrpos($line, "/"));
1792  $nr = substr_count($zdir, "/");
1793  //echo $zdir." ".$nr."<br>";
1794  while ($zdir != "")
1795  {
1796  $nr = substr_count($zdir, "/");
1797  $zdirs[$zdir] = $nr; // collect directories
1798  //echo $dir." ".$nr."<br>";
1799  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1800  }
1801  }
1802  }
1803 
1804  asort($zdirs);
1805 
1806  foreach($zdirs as $zdir => $nr) // create directories
1807  {
1808  ilUtil::createDirectory($zdir);
1809  }
1810 
1811  // real unzip
1812  if (!$overwrite)
1813  {
1814  $unzipcmd = ilUtil::escapeShellArg($file);
1815  }
1816  else
1817  {
1818  $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1819  }
1820  ilUtil::execQuoted($unzip, $unzipcmd);
1821 
1822  chdir($cdir);
1823 
1824  // if flat, get all files and move them to original directory
1825  if ($a_flat)
1826  {
1827  include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1828  $filearray = array();
1829  ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1830  if (is_array($filearray["file"]))
1831  {
1832  foreach ($filearray["file"] as $k => $f)
1833  {
1834  if (substr($f, 0, 1) != "." && $f != basename($orig_file))
1835  {
1836  copy($filearray["path"][$k].$f, $origpathinfo["dirname"].DIRECTORY_SEPARATOR.$f);
1837  }
1838  }
1839  }
1840  ilUtil::delDir($tmpdir);
1841  }
1842  }
1843 
1850  public static function zip($a_dir, $a_file, $compress_content = false)
1851  {
1852  $cdir = getcwd();
1853 
1854  if($compress_content)
1855  {
1856  $a_dir .="/*";
1857  $pathinfo = pathinfo($a_dir);
1858  chdir($pathinfo["dirname"]);
1859  }
1860 
1861  $pathinfo = pathinfo($a_file);
1862  $dir = $pathinfo["dirname"];
1863  $file = $pathinfo["basename"];
1864 
1865  if(!$compress_content)
1866  {
1867  chdir($dir);
1868  }
1869 
1870  $zip = PATH_TO_ZIP;
1871 
1872  if(!$zip)
1873  {
1874  chdir($cdir);
1875  return false;
1876  }
1877 
1878  if (is_array($a_dir))
1879  {
1880  $source = "";
1881  foreach($a_dir as $dir)
1882  {
1883  $name = basename($dir);
1884  $source.= " ".ilUtil::escapeShellArg($name);
1885  }
1886  }
1887  else
1888  {
1889  $name = basename($a_dir);
1890  if (trim($name) != "*")
1891  {
1892  $source = ilUtil::escapeShellArg($name);
1893  }
1894  else
1895  {
1896  $source = $name;
1897  }
1898  }
1899 
1900  $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1901  ilUtil::execQuoted($zip, $zipcmd);
1902  chdir($cdir);
1903  return true;
1904  }
1905 
1906  public static function CreateIsoFromFolder($a_dir, $a_file)
1907  {
1908  $cdir = getcwd();
1909 
1910  $pathinfo = pathinfo($a_dir);
1911  chdir($pathinfo["dirname"]);
1912 
1913  $pathinfo = pathinfo($a_file);
1914  $dir = $pathinfo["dirname"];
1915  $file = $pathinfo["basename"]; $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1916 
1917  $mkisofs = PATH_TO_MKISOFS;
1918  if(!$mkisofs)
1919  {
1920  chdir($cdir);
1921  return false;
1922  }
1923 
1924  $name = basename($a_dir);
1925  $source = ilUtil::escapeShellArg($name);
1926 
1927  $zipcmd = "-r -J -o ".$a_file." ".$source;
1928  ilUtil::execQuoted($mkisofs, $zipcmd);
1929  chdir($cdir);
1930  return true;
1931  }
1932 
1941  public static function getConvertCmd()
1942  {
1943  return PATH_TO_CONVERT;
1944  }
1945 
1953  public static function execConvert($args)
1954  {
1955  ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1956  }
1957 
1964  public static function isConvertVersionAtLeast($a_version)
1965  {
1966  $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1967  $current_version = self::processConvertVersion($current_version[0]);
1968  $version = self::processConvertVersion($a_version);
1969  if($current_version >= $version)
1970  {
1971  return true;
1972  }
1973  return false;
1974  }
1975 
1982  protected static function processConvertVersion($a_version)
1983  {
1984  if(preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)[\.|\-]([0-9]+)/", $a_version, $match))
1985  {
1986  $version = str_pad($match[1], 2, 0, STR_PAD_LEFT).
1987  str_pad($match[2], 2, 0, STR_PAD_LEFT).
1988  str_pad($match[3], 2, 0, STR_PAD_LEFT).
1989  str_pad($match[4], 2, 0, STR_PAD_LEFT);
1990  return (int)$version;
1991  }
1992  }
1993 
2003  public static function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
2004  $a_background_color = "")
2005  {
2006  $format_str = ($a_target_format != "")
2007  ? strtoupper($a_target_format).":"
2008  : "";
2009  $geometry = ($a_geometry != "")
2010  ? " -geometry ".$a_geometry."x".$a_geometry." "
2011  : "";
2012  $bg_color = ($a_background_color != "")
2013  ? " -background color ".$a_background_color." "
2014  : "";
2015  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
2016 
2017  ilUtil::execConvert($convert_cmd);
2018  }
2019 
2030  public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
2031  {
2032  if ($a_constrain_prop)
2033  {
2034  $size = " -geometry ".$a_width."x".$a_height." ";
2035  }
2036  else
2037  {
2038  $size = " -resize ".$a_width."x".$a_height."! ";
2039  }
2040  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
2041 
2042  ilUtil::execConvert($convert_cmd);
2043  }
2044 
2051  public static function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0)
2052  {
2053  $img = '<img src="'.$a_src.'"';
2054  if ($a_alt != "")
2055  {
2056  $img.= ' alt="'.$a_alt.'" title="'.$a_alt.'"';
2057  }
2058  if ($a_width != "")
2059  {
2060  $img.= ' width="'.$a_width.'"';
2061  }
2062  if ($a_height != "")
2063  {
2064  $img.= ' height="'.$a_height.'"';
2065  }
2066  $img.= ' border="'.(int) $a_border.'"/>';
2067 
2068  return $img;
2069  }
2070 
2078  public static function html2pdf($html, $pdf_file)
2079  {
2080  $html_file = str_replace(".pdf",".html",$pdf_file);
2081 
2082  $fp = fopen( $html_file ,"wb");
2083  fwrite($fp, $html);
2084  fclose($fp);
2085 
2086  ilUtil::htmlfile2pdf($html_file,$pdf_file);
2087  }
2088 
2095  public static function htmlfile2pdf($html_file, $pdf_file)
2096  {
2097  $htmldoc_path = PATH_TO_HTMLDOC;
2098 
2099  $htmldoc = "--no-toc ";
2100  $htmldoc .= "--no-jpeg ";
2101  $htmldoc .= "--webpage ";
2102  $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
2103  $htmldoc .= "--bodyfont Arial ";
2104  $htmldoc .= "--charset iso-8859-15 ";
2105  $htmldoc .= "--color ";
2106  $htmldoc .= "--size A4 "; // --landscape
2107  $htmldoc .= "--format pdf ";
2108  $htmldoc .= "--footer ... ";
2109  $htmldoc .= "--header ... ";
2110  $htmldoc .= "--left 60 ";
2111  // $htmldoc .= "--right 200 ";
2112  $htmldoc .= $html_file;
2113  ilUtil::execQuoted($htmldoc_path, $htmldoc);
2114 
2115  }
2116 
2123  public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
2124  {
2125  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
2126  // $mime = "application/octet-stream"; // or whatever the mime type is
2127 
2128  include_once './classes/class.ilHTTPS.php';
2129 
2130  //if($_SERVER['HTTPS'])
2131  if( ilHTTPS::getInstance()->isDetected() )
2132  {
2133 
2134  // Added different handling for IE and HTTPS => send pragma after content informations
2138  #header("Pragma: ");
2139  #header("Cache-Control: ");
2140  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2141  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
2142  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
2143  #header("Cache-Control: post-check=0, pre-check=0", false);
2144  }
2145  else if ($disposition == "attachment")
2146  {
2147  header("Cache-control: private");
2148  }
2149  else
2150  {
2151  header("Cache-Control: no-cache, must-revalidate");
2152  header("Pragma: no-cache");
2153  }
2154 
2155  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2156 
2157  if (strlen($charset))
2158  {
2159  $charset = "; charset=$charset";
2160  }
2161  header("Content-Type: $mime$charset");
2162  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2163  header("Content-Description: ".$ascii_filename);
2164  header("Content-Length: ".(string)(strlen($a_data)));
2165 
2166  //if($_SERVER['HTTPS'])
2167  if( ilHTTPS::getInstance()->isDetected() )
2168  {
2169  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2170  header('Pragma: public');
2171  }
2172 
2173  header("Connection: close");
2174  echo $a_data;
2175  exit;
2176  }
2177 
2178  // BEGIN WebDAV: Show file in browser or provide it as attachment
2186  public static function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false,
2187  $a_exit_after = true)
2188  {
2189  // should we fail silently?
2190  if(!file_exists($a_file))
2191  {
2192  return false;
2193  }
2194 
2195  if ($isInline) {
2196  $disposition = "inline"; // "inline" to view file in browser
2197  } else {
2198  $disposition = "attachment"; // "attachment" to download to hard disk
2199  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2200  }
2201  // END WebDAV: Show file in browser or provide it as attachment
2202 
2203  if(strlen($a_mime))
2204  {
2205  $mime = $a_mime;
2206  }
2207  else
2208  {
2209  $mime = "application/octet-stream"; // or whatever the mime type is
2210  }
2211  // BEGIN WebDAV: Removed broken HTTPS code.
2212  // END WebDAV: Removed broken HTTPS code.
2213  if ($disposition == "attachment")
2214  {
2215  header("Cache-control: private");
2216  }
2217  else
2218  {
2219  header("Cache-Control: no-cache, must-revalidate");
2220  header("Pragma: no-cache");
2221  }
2222 
2223  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2224 
2225  header("Content-Type: $mime");
2226  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2227  header("Content-Description: ".$ascii_filename);
2228 
2229  // #7271: if notice gets thrown download will fail in IE
2230  $filesize = @filesize($a_file);
2231  if ($filesize)
2232  {
2233  header("Content-Length: ".(string)$filesize);
2234  }
2235 
2236  include_once './classes/class.ilHTTPS.php';
2237  #if($_SERVER['HTTPS'])
2238  if(ilHTTPS::getInstance()->isDetected())
2239  {
2240  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2241  header('Pragma: public');
2242  }
2243 
2244  header("Connection: close");
2245  ilUtil::readFile( $a_file );
2246  if ($removeAfterDelivery)
2247  {
2248  unlink ($a_file);
2249  }
2250  if ($a_exit_after)
2251  {
2252  exit;
2253  }
2254  }
2255 
2256 
2266  public static function readFile($a_file)
2267  {
2268  $chunksize = 1*(1024*1024); // how many bytes per chunk
2269  $buffer = '';
2270  $handle = fopen($a_file, 'rb');
2271  if ($handle === false)
2272  {
2273  return false;
2274  }
2275  while (!feof($handle))
2276  {
2277  $buffer = fread($handle, $chunksize);
2278  print $buffer;
2279  }
2280  return fclose($handle);
2281  }
2282 
2290  public static function getASCIIFilename($a_filename)
2291  {
2292  // The filename must be converted to ASCII, as of RFC 2183,
2293  // section 2.3.
2294 
2306 
2309 
2310  $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2311  $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2312  $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2313 
2314  // OS do not allow the following characters in filenames: \/:*?"<>|
2315  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2316 
2317  return $ascii_filename;
2318  }
2319 
2326  public static function htmlentitiesOutsideHTMLTags($htmlText)
2327  {
2328  $matches = Array();
2329  $sep = '###HTMLTAG###';
2330 
2331  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2332  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2333  $tmp = explode($sep, $tmp);
2334 
2335  for ($i=0; $i<count($tmp); $i++)
2336  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2337 
2338  $tmp = join($sep, $tmp);
2339 
2340  for ($i=0; $i<count($matches[0]); $i++)
2341  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2342 
2343  return $tmp;
2344  }
2345 
2352  public static function getJavaPath()
2353  {
2354  return PATH_TO_JAVA;
2355  //global $ilias;
2356 
2357  //return $ilias->getSetting("java_path");
2358  }
2359 
2367  public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2368  {
2369  $amp = $xml_style
2370  ? "&amp;"
2371  : "&";
2372 
2373  $url = (is_int(strpos($a_url, "?")))
2374  ? $a_url.$amp.$a_par
2375  : $a_url."?".$a_par;
2376 
2377  return $url;
2378  }
2379 
2395  public static function makeDir($a_dir)
2396  {
2397  $a_dir = trim($a_dir);
2398 
2399  // remove trailing slash (bugfix for php 4.2.x)
2400  if (substr($a_dir,-1) == "/")
2401  {
2402  $a_dir = substr($a_dir,0,-1);
2403  }
2404 
2405  // check if a_dir comes with a path
2406  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2407  {
2408  $path = ".";
2409  }
2410 
2411  // create directory with file permissions of parent directory
2412  umask(0000);
2413  return @mkdir($a_dir,fileperms($path));
2414  }
2415 
2416 
2431  public static function makeDirParents($a_dir)
2432  {
2433  $dirs = array($a_dir);
2434  $a_dir = dirname($a_dir);
2435  $last_dirname = '';
2436 
2437  while($last_dirname != $a_dir)
2438  {
2439  array_unshift($dirs, $a_dir);
2440  $last_dirname = $a_dir;
2441  $a_dir = dirname($a_dir);
2442  }
2443 
2444  // find the first existing dir
2445  $reverse_paths = array_reverse($dirs, TRUE);
2446  $found_index = -1;
2447  foreach ($reverse_paths as $key => $value)
2448  {
2449  if ($found_index == -1)
2450  {
2451  if (is_dir($value))
2452  {
2453  $found_index = $key;
2454  }
2455  }
2456  }
2457 
2458  umask(0000);
2459  foreach ($dirs as $dirindex => $dir)
2460  {
2461  // starting with the longest existing path
2462  if ($dirindex >= $found_index)
2463  {
2464  if (! file_exists($dir))
2465  {
2466  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2467  {
2468  // on some systems there is an error when there is a slash
2469  // at the end of a directory in mkdir, see Mantis #2554
2470  $dir = substr($dir,0,strlen($dir)-1);
2471  }
2472  if (! mkdir($dir, $umask))
2473  {
2474  error_log("Can't make directory: $dir");
2475  return false;
2476  }
2477  }
2478  elseif (! is_dir($dir))
2479  {
2480  error_log("$dir is not a directory");
2481  return false;
2482  }
2483  else
2484  {
2485  // get umask of the last existing parent directory
2486  $umask = fileperms($dir);
2487  }
2488  }
2489  }
2490  return true;
2491  }
2492 
2502  public static function delDir($a_dir, $a_clean_only = false)
2503  {
2504  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2505  {
2506  return;
2507  }
2508 
2509  $current_dir = opendir($a_dir);
2510 
2511  $files = array();
2512 
2513  // this extra loop has been necessary because of a strange bug
2514  // at least on MacOS X. A looped readdir() didn't work
2515  // correctly with larger directories
2516  // when an unlink happened inside the loop. Getting all files
2517  // into the memory first solved the problem.
2518  while($entryname = readdir($current_dir))
2519  {
2520  $files[] = $entryname;
2521  }
2522 
2523  foreach($files as $file)
2524  {
2525  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2526  {
2527  ilUtil::delDir(${a_dir}."/".${file});
2528  }
2529  elseif ($file != "." and $file != "..")
2530  {
2531  unlink(${a_dir}."/".${file});
2532  }
2533  }
2534 
2535  closedir($current_dir);
2536  if (!$a_clean_only)
2537  {
2538  @rmdir(${a_dir});
2539  }
2540  }
2541 
2542 
2549  public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2550  {
2551  $current_dir = opendir($a_dir.$a_sub_dir);
2552 
2553  $dirs = array();
2554  $files = array();
2555  $subitems = array();
2556  while($entry = readdir($current_dir))
2557  {
2558  if(is_dir($a_dir."/".$entry))
2559  {
2560  $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2561  "subdir" => $a_sub_dir);
2562  if ($a_rec && $entry != "." && $entry != "..")
2563  {
2564  $si = ilUtil::getDir($a_dir, true, $a_sub_dir."/".$entry);
2565  $subitems = array_merge($subitems, $si);
2566  }
2567  }
2568  else
2569  {
2570  if ($entry != "." && $entry != "..")
2571  {
2572  $size = filesize($a_dir.$a_sub_dir."/".$entry);
2573  $files[$entry] = array("type" => "file", "entry" => $entry,
2574  "size" => $size, "subdir" => $a_sub_dir);
2575  }
2576  }
2577  }
2578  ksort($dirs);
2579  ksort($files);
2580 
2581  return array_merge($dirs, $files, $subitems);
2582  }
2583 
2590  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2591  {
2592  if (is_array($a_arr))
2593  {
2594  foreach ($a_arr as $k => $v)
2595  {
2596  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2597  }
2598  }
2599 
2600  return $a_arr;
2601  }
2602 
2609  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2610  {
2611  if (is_array($a_data))
2612  {
2613  foreach ($a_data as $k => $v)
2614  {
2615  if (is_array($v))
2616  {
2617  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2618  }
2619  else
2620  {
2621  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2622  }
2623  }
2624  }
2625  else
2626  {
2627  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2628  }
2629 
2630  return $a_data;
2631  }
2632 
2640  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2641  {
2642  if (ini_get("magic_quotes_gpc"))
2643  {
2644  $a_str = stripslashes($a_str);
2645  }
2646 //echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2647 //echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2648  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2649  }
2650 
2658  public static function stripOnlySlashes($a_str)
2659  {
2660  if (ini_get("magic_quotes_gpc"))
2661  {
2662  $a_str = stripslashes($a_str);
2663  }
2664 
2665  return $a_str;
2666  }
2667 
2674  public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2675  {
2676  // check whether all allowed tags can be made secure
2677  $only_secure = true;
2678  $allow_tags = explode(">", $a_allow);
2679  $sec_tags = ilUtil::getSecureTags();
2680  $allow_array = array();
2681  foreach($allow_tags as $allow)
2682  {
2683  if ($allow != "")
2684  {
2685  $allow = str_replace("<", "", $allow);
2686 
2687  if (!in_array($allow, $sec_tags))
2688  {
2689  $only_secure = false;
2690  }
2691  $allow_array[] = $allow;
2692  }
2693  }
2694 
2695  // default behaviour: allow only secure tags 1:1
2696  if (($only_secure || $a_allow == "") && $a_strip_html)
2697  {
2698  if ($a_allow == "")
2699  {
2700  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2701  "gap", "sub", "sup", "pre", "strike");
2702  }
2703 
2704  // this currently removes parts of strings like "a <= b"
2705  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2706  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2707  $a_str = strip_tags($a_str); // strip all other tags
2708  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2709 
2710  // a possible solution could be something like:
2711  // $a_str = str_replace("<", "&lt;", $a_str);
2712  // $a_str = str_replace(">", "&gt;", $a_str);
2713  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2714  //
2715  // output would be ok then, but input fields would show
2716  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2717  }
2718  else
2719  {
2720  // only for scripts, that need to allow more/other tags and parameters
2721  if ($a_strip_html)
2722  {
2723  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2724  }
2725  }
2726 
2727  return $a_str;
2728  }
2729 
2730  public static function getSecureTags()
2731  {
2732  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2733  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2734  }
2735 
2736  public static function maskSecureTags($a_str, $allow_array)
2737  {
2738  foreach ($allow_array as $t)
2739  {
2740  switch($t)
2741  {
2742  case "a":
2743  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2744  break;
2745 
2746  case "img":
2747  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2748  break;
2749 
2750  case "p":
2751  case "div":
2752  $a_str = ilUtil::maskTag($a_str, $t, array(
2753  array("param" => "align", "value" => "left"),
2754  array("param" => "align", "value" => "center"),
2755  array("param" => "align", "value" => "justify"),
2756  array("param" => "align", "value" => "right")
2757  ));
2758  break;
2759 
2760  default:
2761  $a_str = ilUtil::maskTag($a_str, $t);
2762  break;
2763  }
2764  }
2765 
2766  return $a_str;
2767  }
2768 
2769  public static function unmaskSecureTags($a_str, $allow_array)
2770  {
2771  foreach ($allow_array as $t)
2772  {
2773  switch($t)
2774  {
2775  case "a":
2776  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2777  break;
2778 
2779  case "img":
2780  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2781  break;
2782 
2783  case "p":
2784  case "div":
2785  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2786  array("param" => "align", "value" => "left"),
2787  array("param" => "align", "value" => "center"),
2788  array("param" => "align", "value" => "justify"),
2789  array("param" => "align", "value" => "right")
2790  ));
2791  break;
2792 
2793  default:
2794  $a_str = ilUtil::unmaskTag($a_str, $t);
2795  break;
2796  }
2797  }
2798 
2799  return $a_str;
2800  }
2801 
2809  public static function securePlainString($a_str)
2810  {
2811  if (ini_get("magic_quotes_gpc"))
2812  {
2813  return stripslashes($a_str);
2814  }
2815  else
2816  {
2817  return $a_str;
2818  }
2819  }
2836  public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2837  {
2838  $encoded = "";
2839 
2840  if ($a_make_links_clickable)
2841  {
2842  // Find text sequences in the plain text string which match
2843  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2844  // Encode all other text sequences in the plain text string using
2845  // htmlspecialchars and nl2br.
2846  // The following expressions matches URI's as specified in RFC 2396.
2847  //
2848  // The expression matches URI's, which start with some well known
2849  // schemes, like "http:", or with "www.". This must be followed
2850  // by at least one of the following RFC 2396 expressions:
2851  // - alphanum: [a-zA-Z0-9]
2852  // - reserved: [;\/?:|&=+$,]
2853  // - mark: [\\-_.!~*\'()]
2854  // - escaped: %[0-9a-fA-F]{2}
2855  // - fragment delimiter: #
2856  // - uric_no_slash: [;?:@&=+$,]
2857  $matches = array();
2858  $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);
2859  $pos1 = 0;
2860  $encoded = "";
2861  foreach ($matches as $match)
2862  {
2863  }
2864  foreach ($matches[0] as $match)
2865  {
2866  $matched_text = $match[0];
2867  $pos2 = $match[1];
2868  if ($matched_offset != previous_offset)
2869  {
2870  // encode plain text
2871  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2872  }
2873  // encode URI
2874  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2875 
2876 
2877  $pos1 = $pos2 + strlen($matched_text);
2878  }
2879  if ($pos1 < strlen($a_str))
2880  {
2881  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2882  }
2883  }
2884  else
2885  {
2886  $encoded = nl2br(htmlspecialchars($a_str));
2887  }
2888  return $encoded;
2889  }
2890 
2891 
2892  public static function maskAttributeTag($a_str, $tag, $tag_att)
2893  {
2894  global $ilLog;
2895 
2896  $ws = "[ \t\r\f\v\n]*";
2897  $att = $ws."[^>]*".$ws;
2898 
2899  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2900  $a_str, $found))
2901  {
2902  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2903  $esc = array();
2904  foreach($un as $v)
2905  {
2906  $esc[] = "\\".$v;
2907  }
2908  $ff = str_replace($un, $esc, $found[1]);
2909 
2910  $old_str = $a_str;
2911  $a_str = eregi_replace("<".$ff.">",
2912  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2913  if ($old_str == $a_str)
2914  {
2915  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2916  htmlentities($a_str));
2917  return $a_str;
2918  }
2919  }
2920  $a_str = str_ireplace("</$tag>",
2921  "&lt;/$tag&gt;", $a_str);
2922  return $a_str;
2923  }
2924 
2925  public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2926  {
2927  global $ilLog;
2928 
2929  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2930  $a_str, $found))
2931  {
2932  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2933  $esc = array();
2934  foreach($un as $v)
2935  {
2936  $esc[] = "\\".$v;
2937  }
2938  $ff = str_replace($un, $esc, $found[1]);
2939 
2940  $old_str = $a_str;
2941  $a_str = eregi_replace("&lt;".$ff."&gt;",
2942  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2943  if ($old_str == $a_str)
2944  {
2945  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2946  htmlentities($a_str));
2947  return $a_str;
2948  }
2949  }
2950  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2951  return $a_str;
2952  }
2953 
2954  public static function maskTag($a_str, $t, $fix_param = "")
2955  {
2956  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2957  "&lt;".$t."&gt;", $a_str);
2958  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2959  "&lt;/".$t."&gt;", $a_str);
2960 
2961  if (is_array($fix_param))
2962  {
2963  foreach ($fix_param as $p)
2964  {
2965  $k = $p["param"];
2966  $v = $p["value"];
2967  $a_str = str_replace("<$t $k=\"$v\">",
2968  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2969  }
2970  }
2971 
2972  return $a_str;
2973  }
2974 
2975  public static function unmaskTag($a_str, $t, $fix_param = "")
2976  {
2977  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2978  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2979 
2980  if (is_array($fix_param))
2981  {
2982  foreach ($fix_param as $p)
2983  {
2984  $k = $p["param"];
2985  $v = $p["value"];
2986  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2987  "<"."$t $k=\"$v\"".">", $a_str);
2988  }
2989  }
2990  return $a_str;
2991  }
2992 
2993  public static function secureLink($a_str)
2994  {
2995  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2996  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2997  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2998  return $a_str;
2999  }
3000 
3014  public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
3015  {
3016  //$a_str = strip_tags($a_str, $a_allow);
3017 
3018  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
3019  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
3020  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
3021  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
3022  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
3023  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
3024  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
3025  "title,tr,tt,u,ul,var";
3026  $a_allow = strtolower ($a_allow);
3027  $negatives = explode(",",$negativestr);
3028  $outer_old_str = "";
3029  while($outer_old_str != $a_str)
3030  {
3031  $outer_old_str = $a_str;
3032  foreach ($negatives as $item)
3033  {
3034  $pos = strpos($a_allow, "<$item>");
3035 
3036  // remove complete tag, if not allowed
3037  if ($pos === false)
3038  {
3039  $old_str = "";
3040  while($old_str != $a_str)
3041  {
3042  $old_str = $a_str;
3043  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
3044  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
3045  }
3046  }
3047  }
3048  }
3049 
3050  if ($a_rm_js)
3051  {
3052  // remove all attributes if an "on..." attribute is given
3053  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
3054 
3055  // remove all attributes if a "javascript" is within tag
3056  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
3057 
3058  // remove all attributes if an "expression" is within tag
3059  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
3060  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
3061  }
3062 
3063  return $a_str;
3064  }
3065 
3066 
3075  public static function addSlashes($a_str)
3076  {
3077  if (ini_get("magic_quotes_gpc"))
3078  {
3079  return $a_str;
3080  }
3081  else
3082  {
3083  return addslashes($a_str);
3084  }
3085  }
3086 
3098  public static function prepareFormOutput($a_str, $a_strip = false)
3099  {
3100  if($a_strip)
3101  {
3102  $a_str = ilUtil::stripSlashes($a_str);
3103  }
3104  $a_str = htmlspecialchars($a_str);
3105  // Added replacement of curly brackets to prevent
3106  // problems with PEAR templates, because {xyz} will
3107  // be removed as unused template variable
3108  $a_str = str_replace("{", "&#123;", $a_str);
3109  $a_str = str_replace("}", "&#125;", $a_str);
3110  // needed for LaTeX conversion \\ in LaTeX is a line break
3111  // but without this replacement, php changes \\ to \
3112  $a_str = str_replace("\\", "&#92;", $a_str);
3113  return $a_str;
3114  }
3115 
3116 
3126  public static function prepareDBString($a_str)
3127  {
3128  return addslashes($a_str);
3129  }
3130 
3131 
3140  public static function removeItemFromDesktops($a_id)
3141  {
3142  return ilObjUser::_removeItemFromDesktops($a_id);
3143  }
3144 
3145 
3155  public static function extractParameterString($a_parstr)
3156  {
3157  // parse parameters in array
3158  $par = array();
3159  $ok=true;
3160  while(($spos=strpos($a_parstr,"=")) && $ok)
3161  {
3162  // extract parameter
3163  $cpar = substr($a_parstr,0,$spos);
3164  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
3165  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
3166  $cpar = substr($cpar,1,strlen($cpar)-1);
3167  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
3168  $cpar = substr($cpar,0,strlen($cpar)-1);
3169 
3170  // parameter name should only
3171  $cpar_old = "";
3172  while($cpar != $cpar_old)
3173  {
3174  $cpar_old = $cpar;
3175  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
3176  }
3177 
3178  // extract value
3179  if ($cpar != "")
3180  {
3181  if($spos=strpos($a_parstr,"\""))
3182  {
3183  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
3184  $spos=strpos($a_parstr,"\"");
3185  if(is_int($spos))
3186  {
3187  $cval = substr($a_parstr,0,$spos);
3188  $par[$cpar]=$cval;
3189  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
3190  }
3191  else
3192  $ok=false;
3193  }
3194  else
3195  $ok=false;
3196  }
3197  }
3198 
3199  if($ok) return $par; else return false;
3200  }
3201 
3202  public static function assembleParameterString($a_par_arr)
3203  {
3204  if (is_array($a_par_arr))
3205  {
3206  $target_arr = array();
3207  foreach ($a_par_arr as $par => $val)
3208  {
3209  $target_arr[] = "$par=\"$val\"";
3210  }
3211  $target_str = implode(", ", $target_arr);
3212  }
3213 
3214  return $target_str;
3215  }
3216 
3223  public static function dumpString($a_str)
3224  {
3225  $ret = $a_str.": ";
3226  for($i=0; $i<strlen($a_str); $i++)
3227  {
3228  $ret.= ord(substr($a_str,$i,1))." ";
3229  }
3230  return $ret;
3231  }
3232 
3233 
3240  public static function yn2tf($a_yn)
3241  {
3242  if(strtolower($a_yn) == "y")
3243  {
3244  return true;
3245  }
3246  else
3247  {
3248  return false;
3249  }
3250  }
3251 
3258  public static function tf2yn($a_tf)
3259  {
3260  if($a_tf)
3261  {
3262  return "y";
3263  }
3264  else
3265  {
3266  return "n";
3267  }
3268  }
3269 
3280  public static function sort_func ($a, $b)
3281  {
3282  global $array_sortby,$array_sortorder;
3283 
3284  // this comparison should give optimal results if
3285  // locale is provided and mb string functions are supported
3286  if ($array_sortorder == "asc")
3287  {
3288  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3289  }
3290 
3291  if ($array_sortorder == "desc")
3292  {
3293  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3294  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3295  }
3296  }
3297 
3308  public static function sort_func_numeric ($a, $b)
3309  {
3310  global $array_sortby,$array_sortorder;
3311 
3312  if ($array_sortorder == "asc")
3313  {
3314  return $a["$array_sortby"] > $b["$array_sortby"];
3315  }
3316 
3317  if ($array_sortorder == "desc")
3318  {
3319  return $a["$array_sortby"] < $b["$array_sortby"];
3320  }
3321  }
3334  public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3335  $a_keep_keys = false)
3336  {
3337  include_once("./Services/Utilities/classes/class.ilStr.php");
3338 
3339  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3340  if (! $a_keep_keys) {
3341  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3342  }
3343  // END WebDAV Provide a 'stable' sort algorithm
3344 
3345  global $array_sortby,$array_sortorder;
3346 
3347  $array_sortby = $a_array_sortby;
3348 
3349  if ($a_array_sortorder == "desc")
3350  {
3351  $array_sortorder = "desc";
3352  }
3353  else
3354  {
3355  $array_sortorder = "asc";
3356  }
3357  if($a_numeric)
3358  {
3359  if ($a_keep_keys)
3360  {
3361  uasort($array, array("ilUtil", "sort_func_numeric"));
3362  }
3363  else
3364  {
3365  usort($array, array("ilUtil", "sort_func_numeric"));
3366  }
3367  }
3368  else
3369  {
3370  if ($a_keep_keys)
3371  {
3372  uasort($array, array("ilUtil", "sort_func"));
3373  }
3374  else
3375  {
3376  usort($array, array("ilUtil", "sort_func"));
3377  }
3378  }
3379  //usort($array,"ilUtil::sort_func");
3380 
3381  return $array;
3382  }
3383  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3398  public static function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3399  {
3400  global $array_sortby,$array_sortorder;
3401 
3402  $array_sortby = $a_array_sortby;
3403 
3404  if ($a_array_sortorder == "desc")
3405  {
3406  $array_sortorder = "desc";
3407  }
3408  else
3409  {
3410  $array_sortorder = "asc";
3411  }
3412 
3413  // Create a copy of the array values for sorting
3414  $sort_array = array_values($array);
3415 
3416  if($a_numeric)
3417  {
3418  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3419  }
3420  else
3421  {
3422  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3423  }
3424 
3425  return $sort_array;
3426  }
3427  public static function mergesort(&$array, $cmp_function = 'strcmp') {
3428  // Arrays of size < 2 require no action.
3429  if (count($array) < 2) return;
3430 
3431  // Split the array in half
3432  $halfway = count($array) / 2;
3433  $array1 = array_slice($array, 0, $halfway);
3434  $array2 = array_slice($array, $halfway);
3435 
3436  // Recurse to sort the two halves
3437  ilUtil::mergesort($array1, $cmp_function);
3438  ilUtil::mergesort($array2, $cmp_function);
3439 
3440  // If all of $array1 is <= all of $array2, just append them.
3441  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3442  $array = array_merge($array1, $array2);
3443  return;
3444  }
3445 
3446  // Merge the two sorted arrays into a single sorted array
3447  $array = array();
3448  $ptr1 = $ptr2 = 0;
3449  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3450  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3451  $array[] = $array1[$ptr1++];
3452  }
3453  else {
3454  $array[] = $array2[$ptr2++];
3455  }
3456  }
3457 
3458  // Merge the remainder
3459  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3460  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3461 
3462  return;
3463  }
3464  // END WebDAV: Provide a 'stable' sort algorithm
3465 
3477  public static function unique_multi_array($array, $sub_key)
3478  {
3479  $target = array();
3480  $existing_sub_key_values = array();
3481 
3482  foreach ($array as $key=>$sub_array)
3483  {
3484  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3485  {
3486  $existing_sub_key_values[] = $sub_array[$sub_key];
3487  $target[$key] = $sub_array;
3488  }
3489  }
3490 
3491  return $target;
3492  }
3493 
3494 
3504  public static function getGDSupportedImageType($a_desired_type)
3505  {
3506  $a_desired_type = strtolower($a_desired_type);
3507  // get supported Image Types
3508  $im_types = ImageTypes();
3509 
3510  switch($a_desired_type)
3511  {
3512  case "jpg":
3513  if ($im_types & IMG_JPG) return "jpg";
3514  if ($im_types & IMG_GIF) return "gif";
3515  if ($im_types & IMG_PNG) return "png";
3516  break;
3517 
3518  case "gif":
3519  if ($im_types & IMG_GIF) return "gif";
3520  if ($im_types & IMG_JPG) return "jpg";
3521  if ($im_types & IMG_PNG) return "png";
3522  break;
3523 
3524  case "png":
3525  if ($im_types & IMG_PNG) return "png";
3526  if ($im_types & IMG_JPG) return "jpg";
3527  if ($im_types & IMG_GIF) return "gif";
3528  break;
3529  }
3530 
3531  return "";
3532  }
3533 
3543  public static function deducibleSize($a_mime)
3544  {
3545  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3546  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3547  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3548  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3549  {
3550  return true;
3551  }
3552  else
3553  {
3554  return false;
3555  }
3556  }
3557 
3558 
3566  public static function redirect($a_script)
3567  {
3568  global $log, $PHP_SELF;
3569 
3570 //echo "<br>".$a_script;
3571  if (!is_int(strpos($a_script, "://")))
3572  {
3573  if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3574  {
3575  if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3576  {
3577  $a_script = "setup/".$a_script;
3578  }
3579  $a_script = ILIAS_HTTP_PATH."/".$a_script;
3580  }
3581  }
3582 //echo "<br>".$a_script; exit;
3583 
3584  // include the user interface hook
3585  global $ilPluginAdmin;
3586  if (is_object($ilPluginAdmin))
3587  {
3588  $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk");
3589  foreach ($pl_names as $pl)
3590  {
3591  $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl);
3592  $gui_class = $ui_plugin->getUIClassInstance();
3593  $resp = $gui_class->getHTML("Services/Utilities", "redirect", array("html" => $a_script));
3594  if ($resp["mode"] != ilUIHookPluginGUI::KEEP)
3595  {
3596  $a_script = $gui_class->modifyHTML($a_script, $resp);
3597  }
3598  }
3599  }
3600 
3601  header("Location: ".$a_script);
3602  exit();
3603  }
3604 
3613  public static function insertInstIntoID($a_value)
3614  {
3615  if (substr($a_value, 0, 4) == "il__")
3616  {
3617  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3618  }
3619 
3620  return $a_value;
3621  }
3622 
3633  public static function groupNameExists($a_group_name,$a_id = 0)
3634  {
3635  global $ilDB,$ilErr;
3636 
3637  if (empty($a_group_name))
3638  {
3639  $message = __METHOD__.": No groupname given!";
3640  $ilErr->raiseError($message,$ilErr->WARNING);
3641  }
3642 
3643  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3644 
3645  $q = "SELECT obj_id FROM object_data ".
3646  "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3647  "AND type = ".$ilDB->quote("grp", "text").
3648  $clause;
3649 
3650  $r = $ilDB->query($q);
3651 
3652  if ($r->numRows())
3653  {
3654  return true;
3655  }
3656  else
3657  {
3658  return false;
3659  }
3660  }
3661 
3670  public static function searchGroups($a_search_str)
3671  {
3672  global $ilDB;
3673 
3674  $q = "SELECT * ".
3675  "FROM object_data ,object_reference ".
3676  "WHERE (".$ilDB->like("object_data.title", "text", "%".$a_search_str."%")." ".
3677  "OR ".$ilDB->like("object_data.description", "text", "%".$a_search_str."%").") ".
3678  "AND object_data.type = 'grp' ".
3679  "AND object_data.obj_id = object_reference.obj_id ".
3680  "ORDER BY title ";
3681 
3682  $res = $ilDB->query($q);
3683 
3684  while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3685  {
3686  // STORE DATA IN ARRAY WITH KEY obj_id
3687  // SO DUPLICATE ENTRIES ( LINKED OBJECTS ) ARE UNIQUE
3688  $ids[$row->obj_id] = array(
3689  "ref_id" => $row->ref_id,
3690  "title" => $row->title,
3691  "description" => $row->description);
3692  }
3693 
3694  return $ids ? $ids : array();
3695  }
3696 
3703  public static function getMemString()
3704  {
3705  $my_pid = getmypid();
3706  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3707  }
3708 
3715  public static function isWindows()
3716  {
3717  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3718  {
3719  return true;
3720  }
3721  return false;
3722  }
3723 
3724 
3725  public static function escapeShellArg($a_arg)
3726  {
3727  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3728  // see also ilias bug 5630
3729  return escapeshellarg($a_arg);
3730  }
3731 
3741  public static function escapeShellCmd($a_arg)
3742  {
3743  if(ini_get('safe_mode') == 1)
3744  {
3745  return $a_arg;
3746  }
3747  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3748  return escapeshellcmd($a_arg);
3749  }
3750 
3760  public static function execQuoted($cmd, $args = NULL)
3761  {
3762  if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3763  {
3764  // cmd won't work without quotes
3765  $cmd = '"'.$cmd.'"';
3766  if($args)
3767  {
3768  // args are also quoted, workaround is to quote the whole command AGAIN
3769  // was fixed in php 5.2 (see php bug #25361)
3770  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3771  {
3772  $cmd = '"'.$cmd." ".$args.'"';
3773  }
3774  // args are not quoted or php is fixed, just append
3775  else
3776  {
3777  $cmd .= " ".$args;
3778  }
3779  }
3780  }
3781  // nothing todo, just append args
3782  else if($args)
3783  {
3784  $cmd .= " ".$args;
3785  }
3786 //echo "<br>".$cmd;
3787  exec($cmd, $arr);
3788  return $arr;
3789  }
3790 
3813  public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3814  {
3815  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3816  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3817  {
3818  $target_time = time();
3819  }
3820  else
3821  {
3822  if ($year < 1970)
3823  {
3824  return 0;
3825  }
3826  }
3827  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3828  $difference = $target_time - $starting_time;
3829  $days = (($difference - ($difference % 86400)) / 86400);
3830  $difference = $difference - ($days * 86400) + 3600;
3831  return ($days + 25570 + ($difference / 86400));
3832  }
3833 
3840  public static function renameExecutables($a_dir)
3841  {
3842  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3843  foreach ($def_arr as $def)
3844  {
3845  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3846  }
3847 
3848  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3849  foreach ($def_arr as $def)
3850  {
3851  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3852  }
3853  }
3854 
3867  public static function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3868  {
3869  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3870  || trim($a_old_suffix) == "")
3871  {
3872  return false;
3873  }
3874 
3875  // check if argument is directory
3876  if (!@is_dir($a_dir))
3877  {
3878  return false;
3879  }
3880 
3881  // read a_dir
3882  $dir = opendir($a_dir);
3883 
3884  while($file = readdir($dir))
3885  {
3886  if ($file != "." and
3887  $file != "..")
3888  {
3889  // directories
3890  if (@is_dir($a_dir."/".$file))
3891  {
3892  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3893  }
3894 
3895  // files
3896  if (@is_file($a_dir."/".$file))
3897  {
3898  // first check for files with trailing dot
3899  if(strrpos($file,'.') == (strlen($file) - 1))
3900  {
3901  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3902  $file = substr($file,0,-1);
3903  }
3904 
3905  $path_info = pathinfo($a_dir."/".$file);
3906 
3907  if (strtolower($path_info["extension"]) ==
3908  strtolower($a_old_suffix))
3909  {
3910  $pos = strrpos($a_dir."/".$file, ".");
3911  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3912  rename($a_dir."/".$file, $new_name);
3913  }
3914  }
3915  }
3916  }
3917  return true;
3918  }
3919 
3920  public static function isAPICall () {
3921  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3922  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3923  }
3924 
3925  public static function KT_replaceParam($qstring, $paramName, $paramValue) {
3926  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3927  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3928  } else {
3929  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3930  }
3931  }
3932 
3933  public static function replaceUrlParameterString ($url, $parametersArray) {
3934 
3935  foreach ($parametersArray as $paramName => $paramValue ) {
3936  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3937  }
3938  return $url;
3939  }
3940 
3947  public static function generatePasswords ($a_number)
3948  {
3949  $ret = array();
3950  srand((double) microtime()*1000000);
3951 
3952  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3953  $security = ilSecuritySettings::_getInstance();
3954 
3955  for ($i=1; $i<=$a_number; $i++)
3956  {
3957  $min = ($security->getPasswordMinLength() > 0)
3958  ? $security->getPasswordMinLength()
3959  : 6;
3960  $max = ($security->getPasswordMaxLength() > 0)
3961  ? $security->getPasswordMaxLength()
3962  : 10;
3963  if ($min > $max)
3964  {
3965  $max = $max + 1;
3966  }
3967  $length = rand($min,$max);
3968  $next = rand(1,2);
3969  $vowels = "aeiou";
3970  $consonants = "bcdfghjklmnpqrstvwxyz";
3971  $numbers = "1234567890";
3972  $special = "_.+?#-*@!$%~";
3973  $pw = "";
3974 
3975  // position for number
3976  if ($security->isPasswordCharsAndNumbersEnabled())
3977  {
3978  $num_pos = rand(0, $length - 1);
3979  }
3980 
3981  // position for special character
3982  if ($security->isPasswordSpecialCharsEnabled())
3983  {
3984  $spec_pos = rand(0, $length - 1);
3985  if ($security->isPasswordCharsAndNumbersEnabled())
3986  {
3987  if ($num_pos == $spec_pos) // not same position for number/special
3988  {
3989  if ($spec_pos > 0)
3990  {
3991  $spec_pos -= 1;
3992  }
3993  else
3994  {
3995  $spec_pos += 1;
3996  }
3997  }
3998  }
3999  }
4000  for ($j=0; $j < $length; $j++)
4001  {
4002  if ($security->isPasswordCharsAndNumbersEnabled() && $num_pos == $j)
4003  {
4004  $pw.= $numbers[rand(0,strlen($numbers)-1)];
4005  }
4006  else if ($security->isPasswordSpecialCharsEnabled() && $spec_pos == $j)
4007  {
4008  $pw.= $special[rand(0,strlen($special)-1)];
4009  }
4010  else
4011  {
4012  switch ($next)
4013  {
4014  case 1:
4015  $pw.= $consonants[rand(0,strlen($consonants)-1)];
4016  $next = 2;
4017  break;
4018 
4019  case 2:
4020  $pw.= $vowels[rand(0,strlen($vowels)-1)];
4021  $next = 1;
4022  break;
4023  }
4024  }
4025  }
4026 
4027  $ret[] = $pw;
4028  }
4029  return $ret;
4030  }
4031 
4032  public static function removeTrailingPathSeparators($path)
4033  {
4034  $path = preg_replace("/[\/\\\]+$/", "", $path);
4035  return $path;
4036  }
4037 
4048  public static function array_php2js($data)
4049  {
4050  if (empty($data))
4051  {
4052  $data = array();
4053  }
4054 
4055  foreach($data as $k=>$datum)
4056  {
4057  if(is_null($datum)) $data[$k] = 'null';
4058  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
4059  if(is_array($datum)) $data[$k] = array_php2js($datum);
4060  }
4061 
4062  return "[" . implode(', ', $data) . "]";
4063  }
4064 
4071  public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
4072  {
4073  global $lng;
4074 
4075  if (IL_VIRUS_SCANNER != "None")
4076  {
4077  require_once("classes/class.ilVirusScannerFactory.php");
4079  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4080  {
4081  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
4082  {
4083  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
4084  if ($vs->fileCleaned())
4085  {
4086  $vs_txt.= "<br />".$lng->txt("cleaned_file").
4087  "<br />".$clean_txt;
4088  $vs_txt.= "<br />".$lng->txt("repeat_scan");
4089  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4090  {
4091  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
4092  "<br />".nl2br($vs2_txt));
4093  }
4094  else
4095  {
4096  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
4097  }
4098  }
4099  else
4100  {
4101  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
4102  }
4103  }
4104  else
4105  {
4106  return array(false, nl2br($vs_txt));
4107  }
4108  }
4109  }
4110 
4111  return array(true,"");
4112  }
4113 
4114 
4121  public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true,
4122  $a_mode = "move_uploaded")
4123  {
4124  global $lng, $ilias;
4125 //echo "<br>ilUtli::moveuploadedFile($a_name)";
4126 
4127  if (!is_file($a_file))
4128  {
4129  if ($a_raise_errors)
4130  {
4131  $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
4132  }
4133  else
4134  {
4135  ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
4136  }
4137  return false;
4138  }
4139 
4140  // virus handling
4141  $vir = ilUtil::virusHandling($a_file, $a_name);
4142  if (!$vir[0])
4143  {
4144  unlink($a_file);
4145  if ($a_raise_errors)
4146  {
4147  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
4148  $vir[1],
4149  $ilias->error_obj->MESSAGE);
4150  }
4151  else
4152  {
4153  ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
4154  $vir[1], true);
4155  }
4156  return false;
4157  }
4158  else
4159  {
4160  if ($vir[1] != "")
4161  {
4162  ilUtil::sendInfo($vir[1], true);
4163  }
4164  switch ($a_mode)
4165  {
4166  case "rename":
4167  return rename($a_file, $a_target);
4168  break;
4169 
4170  case "copy":
4171  return copy($a_file, $a_target);
4172  break;
4173 
4174  default:
4175  return move_uploaded_file($a_file, $a_target);
4176  break;
4177  }
4178  }
4179  }
4180 
4181 
4188  public static function date_mysql2time($mysql_date_time) {
4189  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
4190  list($jahr, $monat, $tag) = explode("-", $datum);
4191  list($std, $min, $sec) = explode(":", $uhrzeit);
4192  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
4193  }
4194 
4201  public static function now()
4202  {
4203  return date("Y-m-d H:i:s");
4204  }
4205 
4221  public static function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
4222  {
4223  $resultarray = array();
4224  foreach ($row as $rowindex => $entry)
4225  {
4226  $surround = FALSE;
4227  if ($quoteAll)
4228  {
4229  $surround = TRUE;
4230  }
4231  if (strpos($entry, "\"") !== FALSE)
4232  {
4233  $entry = str_replace("\"", "\"\"", $entry);
4234  $surround = TRUE;
4235  }
4236  if (strpos($entry, $separator) !== FALSE)
4237  {
4238  $surround = TRUE;
4239  }
4240  if ($compatibleWithMSExcel)
4241  {
4242  // replace all CR LF with LF (for Excel for Windows compatibility
4243  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4244  }
4245  if ($surround)
4246  {
4247  if ($outUTF8)
4248  {
4249  $resultarray[$rowindex] = "\"" . $entry . "\"";
4250  }
4251  else
4252  {
4253  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4254  }
4255  }
4256  else
4257  {
4258  if ($outUTF8)
4259  {
4260  $resultarray[$rowindex] = $entry;
4261  }
4262  else
4263  {
4264  $resultarray[$rowindex] = utf8_decode($entry);
4265  }
4266  }
4267  }
4268  return $resultarray;
4269  }
4270 
4271  // validates a domain name (example: www.ilias.de)
4272  public static function isDN($a_str)
4273  {
4274  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
4275  }
4276 
4277  // validates an IP address (example: 192.168.1.1)
4278  public static function isIPv4($a_str)
4279  {
4280  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])\.".
4281  "(\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));
4282  }
4283 
4284 
4313  public static function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
4314  {
4315  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
4316 
4317  if(!is_array($a_obj_type))
4318  {
4319  $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4320  }
4321  else
4322  {
4323  $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4324  }
4325 
4326  // limit number of results default is search result limit
4327  if(!$limit)
4328  {
4329  $limit = $ilias->getSetting('search_max_hits',100);
4330  }
4331  if($limit == -1)
4332  {
4333  $limit = 10000;
4334  }
4335 
4336  // default to logged in usr
4337  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4338  $a_roles = $rbacreview->assignedRoles($a_usr_id);
4339 
4340  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4341  // is assigned to the system role
4342  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4343  {
4344  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4345  "LEFT JOIN tree ON obr.ref_id = tree.child ".
4346  $where.
4347  "AND tree = 1";
4348 
4349  $res = $ilDB->query($query);
4350  $counter = 0;
4351  while($row = $ilDB->fetchObject($res))
4352  {
4353  // Filter recovery folder
4354  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4355  {
4356  continue;
4357  }
4358 
4359  if($counter++ >= $limit)
4360  {
4361  break;
4362  }
4363 
4364  $ref_ids[] = $row->ref_id;
4365  }
4366  return $ref_ids ? $ref_ids : array();
4367  } // End Administrators
4368 
4369  // Check ownership if it is not asked for edit_permission or a create permission
4370  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4371  {
4372  $check_owner = ") ";
4373  }
4374  else
4375  {
4376  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4377  }
4378 
4379  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4380  $ops_id = $ops_ids[0];
4381 
4382  $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4383 
4384  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4385  "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4386  "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4387  $where.
4388  $and.
4389  "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4390  "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4391  $check_owner;
4392 
4393  $res = $ilDB->query($query);
4394  $counter = 0;
4395  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4396  {
4397  if($counter >= $limit)
4398  {
4399  break;
4400  }
4401 
4402  // Filter objects in recovery folder
4403  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4404  {
4405  continue;
4406  }
4407 
4408  // Check deleted, hierarchical access ...
4409  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4410  {
4411  $counter++;
4412  $ref_ids[] = $row->ref_id;
4413  }
4414  }
4415  return $ref_ids ? $ref_ids : array();
4416  }
4417 
4427  public static function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4428  {
4429  global $tpl, $lng, $ilUser;
4430 
4431  // - take care of html exports (-> see buildLatexImages)
4432  include_once "./Services/Administration/classes/class.ilSetting.php";
4433  $jsMathSetting = new ilSetting("jsMath");
4434  $use_jsmath =
4435  $jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault"))));
4436 
4437  if ($use_jsmath)
4438  {
4439  $info = "";
4440  if (!$tpl->out_jsmath_info)
4441  {
4442  include_once "./classes/class.ilTemplate.php";
4443  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4444  $lng->loadLanguageModule("jsmath");
4445  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4446  $info = $template->get();
4447  $tpl->out_jsmath_info = TRUE;
4448  }
4449  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4450  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4451  }
4452 
4453  // this is a fix for bug5362
4454  $cpos = 0;
4455  $o_start = $a_start;
4456  $o_end = $a_end;
4457  $a_start = str_replace("\\", "", $a_start);
4458  $a_end = str_replace("\\", "", $a_end);
4459  /*$a_start = str_replace("\]", "]", $a_start);
4460  $a_start = str_replace("\[", "[", $a_start);
4461  $a_end = str_replace("\]", "]", $a_end);
4462  $a_end = str_replace("\[", "[", $a_end);
4463  $a_end = str_replace("\/", "/", $a_end);*/
4464 
4465  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4466  {
4467  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4468  {
4469  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4470 
4471  // replace, if tags do not go across div borders
4472  if (!is_int(strpos($tex, "</div>")))
4473  {
4474  if (!$use_jsmath)
4475  {
4476  $a_text = substr($a_text, 0, $spos).
4477  "<img alt=\"".htmlentities($tex)."\" src=\"".$a_cgi."?".
4478  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4479  " />".
4480  substr($a_text, $epos + strlen($a_end));
4481  }
4482  else
4483  {
4484  $tex = $a_start.$tex.$a_end;
4485 //echo "<br>1:".$tex;
4486  $replacement =
4487  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4488  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $tex);
4489  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4490 //echo "<br>2:".htmlentities($replacement);
4491  $a_text = substr($a_text, 0, $spos).
4492  $replacement.
4493  substr($a_text, $epos + strlen($a_end));
4494  }
4495  }
4496  }
4497  $cpos = $spos + 1;
4498  }
4499 
4500  if ($use_jsmath)
4501  {
4502  $a_text = str_replace("[[info]]", $info, $a_text);
4503  }
4504 
4505  $result_text = $a_text;
4506 
4507 // $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4508 // "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4509 // " />'", $a_text);
4510 
4511 //echo htmlentities($a_text);
4512 
4513  return $result_text;
4514  }
4515 
4525  public static function __insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4526  {
4527  global $tpl, $lng, $ilUser;
4528 
4529 //echo "<br><br>".htmlentities($a_text);
4530 //echo "<br>-".htmlentities($a_start)."-".htmlentities($a_end)."-";
4531 
4532  // - take care of html exports (-> see buildLatexImages)
4533  include_once "./Services/Administration/classes/class.ilSetting.php";
4534  $jsMathSetting = new ilSetting("jsMath");
4535  if ($jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault")))))
4536  {
4537  $info = "";
4538  if (!$tpl->out_jsmath_info)
4539  {
4540  include_once "./classes/class.ilTemplate.php";
4541  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
4542  $lng->loadLanguageModule("jsmath");
4543  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
4544  $info = $template->get();
4545  $tpl->out_jsmath_info = TRUE;
4546  }
4547  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4548  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4549  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $a_text);
4550  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4551  $result_text = str_replace("[[info]]", $info, $result_text);
4552  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
4553  }
4554  else
4555  {
4556  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
4557  "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
4558  " />'", $a_text);
4559  }
4560 
4561  return $result_text;
4562  }
4563 
4573  public static function buildLatexImages($a_text, $a_dir ,$a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
4574  {
4575  $result_text = $a_text;
4576 
4577  if ($a_cgi != "")
4578  {
4579  while (preg_match('/' . $a_start . '(.*?)' . $a_end . '/ie', $result_text, $found))
4580  {
4581  $cnt = (int) $GLOBALS["teximgcnt"]++;
4582  // get image from cgi and write it to file
4583  $fpr = @fopen($a_cgi."?".rawurlencode($found[1]), "r");
4584  $lcnt = 0;
4585  if ($fpr)
4586  {
4587  while(!feof($fpr))
4588  {
4589  $buf = fread($fpr, 1024);
4590  if ($lcnt == 0)
4591  {
4592  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4593  {
4594  $suffix = "gif";
4595  }
4596  else
4597  {
4598  $suffix = "png";
4599  }
4600  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4601  }
4602  $lcnt++;
4603  fwrite($fpw, $buf);
4604  }
4605  fclose($fpw);
4606  fclose($fpr);
4607  }
4608 
4609  // replace tex-tag
4610  $img_str = "./teximg/img".$cnt.".".$suffix;
4611  $result_text = str_replace($found[0],
4612  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4613  }
4614  }
4615 
4616  return $result_text;
4617  }
4618 
4627  public function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE)
4628  {
4629  $result = $txt_output;
4630  $is_html = $this->isHTML($result);
4631 
4632  if ($prepare_for_latex_output)
4633  {
4634  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>", URL_TO_LATEX);
4635  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]", URL_TO_LATEX);
4636  }
4637 
4638  // removed: did not work with magic_quotes_gpc = On
4639  if (!$is_html)
4640  {
4641  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4642  $result = preg_replace("/[\n]/", "<br />", $result);
4643  }
4644  else
4645  {
4646  // patch for problems with the <pre> tags in tinyMCE
4647  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4648  {
4649  foreach ($matches[0] as $found)
4650  {
4651  $replacement = "";
4652  if (strpos("\n", $found) === FALSE)
4653  {
4654  $replacement = "\n";
4655  }
4656  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4657  $result = str_replace($found, $removed, $result);
4658  }
4659  }
4660  }
4661  if ($prepare_for_latex_output)
4662  {
4663  // replace special characters to prevent problems with the ILIAS template system
4664  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4665  $result = str_replace("{", "&#123;", $result);
4666  $result = str_replace("}", "&#125;", $result);
4667  $result = str_replace("\\", "&#92;", $result);
4668  }
4669  return $result;
4670  }
4671 
4672 
4681  public static function int2array ($seconds, $periods = null)
4682  {
4683  // Define time periods
4684  if (!is_array($periods))
4685  {
4686  $periods = array (
4687  'years' => 31536000,
4688  'months' => 2592000,
4689  'days' => 86400,
4690  'hours' => 3600,
4691  'minutes' => 60,
4692  'seconds' => 1
4693  );
4694  }
4695 
4696  // Loop
4697  $seconds = (float) $seconds;
4698  foreach ($periods as $period => $value)
4699  {
4700  $count = floor($seconds / $value);
4701 
4702  if ($count == 0)
4703  {
4704  continue;
4705  }
4706 
4707  $values[$period] = $count;
4708  $seconds = $seconds % $value;
4709  }
4710  // Return
4711  if (empty($values))
4712  {
4713  $values = null;
4714  }
4715 
4716  return $values;
4717  }
4718 
4727  public static function timearray2string ($duration)
4728  {
4729  global $lng;
4730 
4731  if (!is_array($duration))
4732  {
4733  return false;
4734  }
4735 
4736  foreach ($duration as $key => $value) {
4737 
4738  // Plural
4739  if ($value > 1)
4740  {
4741  $segment_name = $key;
4742  $segment_name = $lng->txt($segment_name);
4743  $segment = $value . ' ' . $segment_name;
4744  }
4745  else
4746  {
4747  $segment_name = substr($key, 0, -1);
4748  $segment_name = $lng->txt($segment_name);
4749  $segment = $value . ' ' . $segment_name;
4750  }
4751 
4752  $array[] = $segment;
4753  }
4754  $len = count($array);
4755 
4756  if ($len>3)
4757  {
4758  $array=array_slice($array,0,(3-$len));
4759  }
4760 
4761  $str = implode(', ', $array);
4762 
4763  return $str;
4764  }
4765 
4766  public static function getFileSizeInfo()
4767  {
4768  global $lng;
4769 
4770  // get the value for the maximal uploadable filesize from the php.ini (if available)
4771  $umf=get_cfg_var("upload_max_filesize");
4772  // get the value for the maximal post data from the php.ini (if available)
4773  $pms=get_cfg_var("post_max_size");
4774 
4775  // use the smaller one as limit
4776  $max_filesize=min($umf, $pms);
4777  if (!$max_filesize) $max_filesize=max($umf, $pms);
4778 
4779  return $lng->txt("file_notice")." $max_filesize.";
4780  }
4781 
4790  public static function __extractRefId($role_title)
4791  {
4792 
4793  $test_str = explode('_',$role_title);
4794 
4795  if ($test_str[0] == 'il')
4796  {
4797  $test2 = (int) $test_str[3];
4798  return is_numeric ($test2) ? (int) $test2 : false;
4799  }
4800  return false;
4801  }
4802 
4813  public static function __extractId($ilias_id, $inst_id)
4814  {
4815 
4816  $test_str = explode('_',$ilias_id);
4817 
4818  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4819  {
4820  $test2 = (int) $test_str[3];
4821  return is_numeric ($test2) ? (int) $test2 : false;
4822  }
4823  return false;
4824  }
4825 
4840  public static function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4841  {
4842  global $ilDB;
4843 
4844  if(!$a_ids)
4845  {
4846  return array();
4847  }
4848 
4849  // use database to sort user array
4850  $where = "WHERE ".$a_id_name." IN (";
4851  $where .= implode(",", ilUtil::quoteArray($a_ids));
4852  $where .= ") ";
4853 
4854  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4855  $where.
4856  "ORDER BY ".$a_field;
4857 
4858  $res = $ilDB->query($query);
4859  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4860  {
4861  $ids[] = $row->$a_id_name;
4862  }
4863  return $ids ? $ids : array();
4864  }
4865 
4875  public static function getMySQLTimestamp($a_ts)
4876  {
4877  global $ilDB;
4878 
4879  return $a_ts;
4880  }
4881 
4888  public static function quoteArray($a_array)
4889  {
4890  global $ilDB;
4891 
4892 
4893  if(!is_array($a_array) or !count($a_array))
4894  {
4895  return array("''");
4896  }
4897 
4898  foreach($a_array as $k => $item)
4899  {
4900  $a_array[$k] = $ilDB->quote($item);
4901  }
4902 
4903  return $a_array;
4904  }
4905 
4914  public static function sendInfo($a_info = "",$a_keep = false)
4915  {
4916  global $tpl;
4917  $tpl->setMessage("info", $a_info, $a_keep);
4918  }
4919 
4928  public static function sendFailure($a_info = "",$a_keep = false)
4929  {
4930  global $tpl;
4931  $tpl->setMessage("failure", $a_info, $a_keep);
4932  }
4933 
4940  public static function sendQuestion($a_info = "",$a_keep = false)
4941  {
4942  global $tpl;
4943  $tpl->setMessage("question", $a_info, $a_keep);
4944  }
4945 
4954  public static function sendSuccess($a_info = "",$a_keep = false)
4955  {
4956  global $tpl;
4957  $tpl->setMessage("success", $a_info, $a_keep);
4958  }
4959 
4960  public static function infoPanel($a_keep = true)
4961  {
4962  global $tpl,$ilias,$lng;
4963 
4964  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4965  {
4966  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html");
4967  $tpl->setCurrentBlock("infopanel");
4968 
4969  if (!empty($_SESSION["infopanel"]["text"]))
4970  {
4971  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4972  ilFrameTargetInfo::_getFrame("MainContent").
4973  "\">";
4974  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4975  $link .= "</a>";
4976  }
4977 
4978  // deactivated
4979  if (!empty($_SESSION["infopanel"]["img"]))
4980  {
4981  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4982  ilFrameTargetInfo::_getFrame("MainContent").
4983  "\">";
4984  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4985  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4986  $link .= "</a></td>";
4987  }
4988 
4989  $tpl->setVariable("INFO_ICONS",$link);
4990  $tpl->parseCurrentBlock();
4991  }
4992 
4993  //if (!$a_keep)
4994  //{
4995  //session_unregister("infopanel"); // deprecated
4996  unset($_SESSION["infopanel"]);
4997  //}
4998  }
4999 
5000 
5009  public static function dirsize($directory)
5010  {
5011  $size = 0;
5012  if (!is_dir($directory))
5013  {
5014  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
5015  // dirsize of non-existing directory
5016  $size = @filesize($directory);
5017  // END DiskQuota Suppress PHP warning.
5018  return ($size === false) ? -1 : $size;
5019  }
5020  if ($DIR = opendir($directory))
5021  {
5022  while (($dirfile = readdir($DIR)) !== false)
5023  {
5024  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
5025  continue;
5026  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
5027  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
5028  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
5029  {
5030  // BEGIN DiskQuota: dirsize is not a global function anymore
5031  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
5032  // END DiskQuota: dirsize is not a global function anymore
5033  if ($dirSize >= 0)
5034  $size += $dirSize;
5035  else return -1;
5036  }
5037  }
5038  closedir($DIR);
5039  }
5040  return $size;
5041  }
5042 
5043  public static function randomhash()
5044  {
5045  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
5046  }
5047 
5048  public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
5049  {
5050  /*
5051  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
5052  else $expire = time() - (365*24*60*60);
5053  */
5054  // Temporary fix for feed.php
5055  if(!(bool)$a_set_cookie_invalid) $expire = 0;
5056  else $expire = time() - (365*24*60*60);
5057 
5058  // setcookie() supports 5th parameter
5059  // only for php version 5.2.0 and above
5060  if( version_compare(PHP_VERSION, '5.2.0', '>=') )
5061  {
5062  // PHP version >= 5.2.0
5063  setcookie( $a_cookie_name, $a_cookie_value, $expire,
5064  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
5065  );
5066  }
5067  else
5068  {
5069  // PHP version < 5.2.0
5070  setcookie( $a_cookie_name, $a_cookie_value, $expire,
5071  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE
5072  );
5073  }
5074 
5075  if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
5076  }
5077 
5078  public static function _sanitizeFilemame($a_filename)
5079  {
5080  return strip_tags(self::stripSlashes($a_filename));
5081  }
5082 
5083  public static function _getHttpPath()
5084  {
5085  global $ilIliasIniFile;
5086 
5087  if($_SERVER['SHELL'])
5088  {
5089  return $ilIliasIniFile->readVariable('server', 'http_path');
5090  }
5091  else
5092  {
5093  return ILIAS_HTTP_PATH;
5094  }
5095  }
5096 
5105  public static function printBacktrace()
5106  {
5107  $bt = debug_backtrace();
5108  foreach ($bt as $t)
5109  {
5110  echo "<br>".$t["file"].", ".$t["function"]." [".$t["line"]."]";
5111  }
5112  }
5113 
5128  public static function parseImportId($a_import_id)
5129  {
5130  $exploded = explode('_'.$a_import_id);
5131 
5132  $parsed['orig'] = $a_import_id;
5133  if($exploded[0] == 'il')
5134  {
5135  $parsed['prefix'] = $exploded[0];
5136  }
5137  if(is_numeric($exploded[1]))
5138  {
5139  $parsed['inst_id'] = (int) $exploded[1];
5140  }
5141  $parsed['type'] = $exploded[2];
5142 
5143  if(is_numeric($exploded[3]))
5144  {
5145  $parsed['id'] = (int) $exploded[3];
5146  }
5147  return $parsed;
5148  }
5149 
5150 } // END class.ilUtil
5151 
5152 
5153 ?>