ILIAS  release_4-3 Revision
 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.png";
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.png\" 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.png';
78  break;
79  case 'big':
80  $postfix = '_b.png';
81  break;
82  default:
83  $postfix = '.png';
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(
124  $current_style);
125  }
126  if ($current_skin == "default")
127  {
128  $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
129  $skin_img = ".".$module_path."/templates/default/images/".$img;
130  }
131  else if (is_object($styleDefinition) && $current_skin != "default")
132  {
133  $user_img = "./Customizing/global/skin/".
134  $current_skin.$module_path."/".$image_dir."/".$img;
135  $skin_img = "./Customizing/global/skin/".
136  $current_skin.$module_path."/images/".$img;
137  }
138 
139  if ($offline)
140  {
141  return "./images/".$img;
142  }
143  else if (@file_exists($user_img) && $image_dir != "")
144  {
145  return $user_img; // found image for skin and style
146  }
147  else if (file_exists($skin_img))
148  {
149  return $skin_img; // found image in skin/images
150  }
151 
152  return $default_img; // take image in default
153  }
154 
165  public static function getHtmlPath($relative_path)
166  {
167  if (substr($relative_path, 0, 2) == './')
168  {
169  $relative_path = (substr($relative_path, 1));
170  }
171  if (substr($relative_path, 0, 1) != '/')
172  {
173  $relative_path = '/' . $relative_path;
174  }
175  $htmlpath = ILIAS_HTTP_PATH . $relative_path;
176  return $htmlpath;
177  }
178 
191  public static function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
192  {
193  global $ilias;
194 
195  // add version as parameter to force reload for new releases
196  // use ilStyleDefinition instead of account to get the current style
197  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
198  $stylesheet_name = (strlen($a_css_name))
199  ? $a_css_name
201  if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0))
202  {
203  $a_css_location = $a_css_location . "/";
204  }
205 
206  $filename = "";
207  // use ilStyleDefinition instead of account to get the current skin
208  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
209  if (ilStyleDefinition::getCurrentSkin() != "default")
210  {
211  $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_css_location.$stylesheet_name;
212  }
213  if (strlen($filename) == 0 || !file_exists($filename))
214  {
215  $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
216  }
217  $vers = "";
218  if ($mode != "filesystem")
219  {
220  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
221  $vers = "?vers=".str_replace(".", "-", $vers);
222  }
223  return $filename . $vers;
224  }
225 
236  public static function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
237  {
238  global $ilias;
239 
240  // add version as parameter to force reload for new releases
241  $js_name = $a_js_name;
242  if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
243 
244  $filename = "";
245  // use ilStyleDefinition instead of account to get the current skin
246  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
247  if (ilStyleDefinition::getCurrentSkin() != "default")
248  {
249  $filename = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/".$a_js_location.$js_name;
250  }
251  if (strlen($filename) == 0 || !file_exists($filename))
252  {
253  $filename = "./" . $a_js_location . "templates/default/".$js_name;
254  }
255  $vers = "";
256  if ($add_version)
257  {
258  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
259  $vers = "?vers=".str_replace(".", "-", $vers);
260  }
261  return $filename . $vers;
262  }
263 
271  public static function getP3PLocation()
272  {
273  global $ilias;
274 
275  if (defined("ILIAS_MODULE"))
276  {
277  $base = '';
278  for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
279  {
280  $base .= "../Services/Privacy/";
281  }
282  }
283  else
284  {
285  $base = "./Services/Privacy/";
286  }
287 
288  if (is_file($base."w3c/p3p.xml"))
289  {
290  return ILIAS_HTTP_PATH."w3c/p3p.xml";
291  }
292  else
293  {
294  return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
295  }
296  }
297 
305  public static function getNewContentStyleSheetLocation($mode = "output")
306  {
307  global $ilias;
308 
309  // add version as parameter to force reload for new releases
310  if ($mode != "filesystem")
311  {
312  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
313  $vers = "?vers=".str_replace(".", "-", $vers);
314  }
315 
316  // use ilStyleDefinition instead of account to get the current skin and style
317  require_once("./Services/Style/classes/class.ilStyleDefinition.php");
318  if (ilStyleDefinition::getCurrentSkin() == "default")
319  {
320  $in_style = "./templates/".ilStyleDefinition::getCurrentSkin()."/"
321  .ilStyleDefinition::getCurrentStyle()."_cont.css";
322  }
323  else
324  {
325  $in_style = "./Customizing/global/skin/".ilStyleDefinition::getCurrentSkin()."/"
326  .ilStyleDefinition::getCurrentStyle()."_cont.css";
327  }
328 
329  if (is_file("./".$in_style))
330  {
331  return $in_style.$vers;
332  }
333  else
334  {
335  return "templates/default/delos_cont.css".$vers;
336  }
337  }
338 
357  public static function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
358  $style_class = "", $attribs = "",$disabled = false)
359  {
360  global $lng;
361 
362  if ($multiple == true)
363  {
364  $multiple = " multiple=\"multiple\"";
365  }
366  else
367  {
368  $multiple = "";
369  $size = 0;
370  }
371 
372  if ($style_class != "")
373  {
374  $class = " class=\"".$style_class."\"";
375  }
376  else
377  {
378  $class = "";
379  }
380  $attributes = "";
381  if (is_array($attribs))
382  {
383  foreach ($attribs as $key => $val)
384  {
385  $attributes .= " ".$key."=\"".$val."\"";
386  }
387  }
388  if($disabled)
389  {
390  $disabled = ' disabled=\"disabled\"';
391  }
392 
393  $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
394 
395  foreach ((array) $options as $key => $val)
396  {
397  $style = "";
398  if (is_array($val))
399  {
400  $style = $val["style"];
401  $val = $val["text"]; // mus be last line, since we overwrite
402  }
403 
404  $sty = ($style != "")
405  ? ' style="'.$style.'" '
406  : "";
407 
408  if ($direct_text)
409  {
410  $str .= " <option $sty value=\"".$key."\"";
411  }
412  else
413  {
414  $str .= " <option $sty value=\"".$val."\"";
415  }
416  if (is_array($selected) )
417  {
418  if (in_array($key,$selected))
419  {
420  $str .= " selected=\"selected\"";
421  }
422  }
423  else if ($selected == $key)
424  {
425  $str .= " selected=\"selected\"";
426  }
427 
428  if ($direct_text)
429  {
430  $str .= ">".$val."</option>\n";
431  }
432  else
433  {
434  $str .= ">".$lng->txt($val)."</option>\n";
435  }
436  }
437 
438  $str .= "</select>\n";
439 
440  return $str;
441  }
442 
452  public static function getSelectName ($selected,$values)
453  {
454  return($values[$selected]);
455  }
456 
468  public static function formCheckbox ($checked,$varname,$value,$disabled = false)
469  {
470  $str = "<input type=\"checkbox\" name=\"".$varname."\"";
471 
472  if ($checked == 1)
473  {
474  $str .= " checked=\"checked\"";
475  }
476 
477  if ($disabled)
478  {
479  $str .= " disabled=\"disabled\"";
480  }
481 
482  $array_var = false;
483 
484  if (substr($varname,-2) == "[]")
485  {
486  $array_var = true;
487  }
488 
489  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
490  if ($array_var)
491  {
492  $varname_id = substr($varname,0,-2)."_".$value;
493  }
494  else
495  {
496  $varname_id = $varname;
497  }
498 
499  // dirty removal of other "[]" in string
500  $varname_id = ereg_replace("\[","_",$varname_id);
501  $varname_id = ereg_replace("\]","",$varname_id);
502 
503  $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
504 
505  return $str;
506  }
507 
519  public static function formDisabledRadioButton($checked,$varname,$value,$disabled)
520  {
521  if ($disabled) {
522  $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
523  }
524  else {
525  $str = "<input type=\"radio\" name=\"".$varname."\"";
526  }
527  if ($checked == 1)
528  {
529  $str .= " checked=\"checked\"";
530  }
531 
532  $str .= " value=\"".$value."\"";
533  $str .= " id=\"".$value."\" />\n";
534 
535  return $str;
536 
537  }
538 
539 
550  public static function formRadioButton($checked,$varname,$value,$onclick=null)
551  {
552  $str = '<input ';
553 
554  if($onclick)
555  {
556  $str .= ('onclick="'.$onclick.'"');
557  }
558 
559  $str .= (" type=\"radio\" name=\"".$varname."\"");
560  if ($checked == 1)
561  {
562  $str .= " checked=\"checked\"";
563  }
564 
565  $str .= " value=\"".$value."\"";
566 
567  $str .= " id=\"".$value."\" />\n";
568 
569  return $str;
570  }
571 
572 
582  public static function formInput($varname,$value,$disabled = false)
583  {
584 
585  $str = "<input type=\"input\" name=\"".$varname."\"";
586  if ($disabled)
587  {
588  $str .= " disabled";
589  }
590 
591  $str .= " value=\"".$value."\"";
592 
593  $str .= " id=\"".$value."\" />\n";
594 
595  return $str;
596  }
597 
598 
605  public static function checkInput ($vars)
606  {
607  // TO DO:
608  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
609  }
610 
617  public static function setPathStr ($a_path)
618  {
619  if ("" != $a_path && "/" != substr($a_path, -1))
620  {
621  $a_path .= "/";
622  //$a_path = substr($a_path,1);
623  }
624 
625  //return getcwd().$a_path;
626  return $a_path;
627  }
628 
641  public static function switchColor ($a_num,$a_css1,$a_css2)
642  {
643  if (!($a_num % 2))
644  {
645  return $a_css1;
646  }
647  else
648  {
649  return $a_css2;
650  }
651  }
652 
661  public static function checkFormEmpty ($emptyFields)
662  {
663 
664  $feedback = "";
665 
666  foreach ($emptyFields as $key => $val)
667  {
668  if ($val == "") {
669  if ($feedback != "") $feedback .= ", ";
670  $feedback .= $key;
671  }
672  }
673 
674  return $feedback;
675  }
676 
701  public static function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
702  {
703  $LinkBar = "";
704 
705  $layout_link = "";
706  $layout_prev = "&lt;&lt;";
707  $layout_next = "&gt;&gt;";
708 
709  // layout options
710  if (count($ALayout > 0))
711  {
712  if ($ALayout["link"])
713  {
714  $layout_link = " class=\"".$ALayout["link"]."\"";
715  }
716 
717  if ($ALayout["prev"])
718  {
719  $layout_prev = $ALayout["prev"];
720  }
721 
722  if ($ALayout["next"])
723  {
724  $layout_next = $ALayout["next"];
725  }
726  }
727 
728  // show links, if hits greater limit
729  // or offset > 0 (can be > 0 due to former setting)
730  if ($AHits > $ALimit || $AOffset > 0)
731  {
732  if (!empty($AParams))
733  {
734  foreach ($AParams as $key => $value)
735  {
736  $params.= $key."=".$value."&";
737  }
738  }
739  // if ($params) $params = substr($params,0,-1);
740  if(strpos($AScript,'&'))
741  {
742  $link = $AScript."&".$params.$prefix."offset=";
743  }
744  else
745  {
746  $link = $AScript."?".$params.$prefix."offset=";
747  }
748 
749  // ?bergehe "zurck"-link, wenn offset 0 ist.
750  if ($AOffset >= 1)
751  {
752  $prevoffset = $AOffset - $ALimit;
753  if ($prevoffset < 0) $prevoffset = 0;
754  $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
755  }
756 
757  // Ben?tigte Seitenzahl kalkulieren
758  $pages=intval($AHits/$ALimit);
759 
760  // Wenn ein Rest bleibt, addiere eine Seite
761  if (($AHits % $ALimit))
762  $pages++;
763 
764  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
765  // if ($AOffset != 0) {
766 
767  // ansonsten zeige Links zu den anderen Seiten an
768  for ($i = 1 ;$i <= $pages ; $i++)
769  {
770  $newoffset=$ALimit*($i-1);
771 
772  if ($newoffset == $AOffset)
773  {
774  $LinkBar .= "[".$i."] ";
775  }
776  else
777  {
778  $LinkBar .= '<a '.$layout_link.' href="'.
779  $link.$newoffset.'">['.$i.']</a> ';
780  }
781  }
782  // }
783 
784  // Checken, ob letze Seite erreicht ist
785  // Wenn nicht, gebe einen "Weiter"-Link aus
786  if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
787  {
788  $newoffset=$AOffset+$ALimit;
789  $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
790  }
791 
792  return $LinkBar;
793  }
794  else
795  {
796  return false;
797  }
798  }
799 
811  public static function makeClickable($a_text, $detectGotoLinks = false)
812  {
813  // New code, uses MediaWiki Sanitizer
814  $ret = $a_text;
815 
816  // www-URL ohne ://-Angabe
817  $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
818  "\\1http://\\2\\3", $ret);
819 
820  // ftp-URL ohne ://-Angabe
821  $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
822  "\\1ftp://\\2\\3", $ret);
823 
824  // E-Mail (this does not work as expected, users must add mailto: manually)
825  //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
826  // "mailto:\\1", $ret);
827 
828  // mask existing image tags
829  $ret = str_replace('src="http://', '"***masked_im_start***', $ret);
830 
831  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
832  $parser = new ilMWParserAdapter();
833  $ret = $parser->replaceFreeExternalLinks($ret);
834 
835  // unmask existing image tags
836  $ret = str_replace('"***masked_im_start***', 'src="http://', $ret);
837 
838  // Should be Safe
839 
840  if ($detectGotoLinks)
841  // replace target blank with self and text with object title.
842  {
843  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
844 // echo htmlentities($regExp);
845  $ret = preg_replace_callback(
846  "/".$regExp."/i",
847  array("ilUtil", "replaceLinkProperties"),
848  $ret);
849 
850  // Static links
851  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
852 // echo htmlentities($regExp);
853  $ret = preg_replace_callback(
854  "/".$regExp."/i",
855  array("ilUtil", "replaceLinkProperties"),
856  $ret);
857  }
858 
859  return($ret);
860  }
861 
875  public static function replaceLinkProperties ($matches)
876  {
877  $link = $matches[0];
878  $ref_id = $matches[2];
879 
880  if ($ref_id > 0)
881  {
882  $obj_id = ilObject::_lookupObjId($ref_id);
883  if ($obj_id > 0)
884  {
885  $title = ilObject::_lookupTitle($obj_id);
886  $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
887  }
888  }
889  return $link;
890  }
891 
910  public static function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array(), $emptyoption = false)
911  {
912  global $lng;
913 
914  $disabled = '';
915  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
916  {
917  $disabled = 'disabled="disabled" ';
918  }
919 
920  $now = getdate();
921  if (!$emptyoption)
922  {
923  if (!strlen($year)) $year = $now["year"];
924  if (!strlen($month)) $month = $now["mon"];
925  if (!strlen($day)) $day = $now["mday"];
926  }
927 
928  $year = (int) $year;
929  $month = (int) $month;
930  $day = (int) $day;
931 
932  // build day select
933 
934  $sel_day .= '<select ';
935  if(isset($a_further_options['select_attributes']))
936  {
937  foreach($a_further_options['select_attributes'] as $name => $value)
938  {
939  $sel_day .= ($name.'="'.$value.'" ');
940  }
941  }
942 
943  $sel_day .= $disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
944 
945  if ($emptyoption) $sel_day .= "<option value=\"0\">--</option>\n";
946  for ($i = 1; $i <= 31; $i++)
947  {
948  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
949  }
950  $sel_day .= "</select>\n";
951  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
952 
953  // build month select
954  $sel_month = '<select ';
955  if(isset($a_further_options['select_attributes']))
956  {
957  foreach($a_further_options['select_attributes'] as $name => $value)
958  {
959  $sel_month .= ($name.'="'.$value.'" ');
960  }
961  }
962  $sel_month .= $disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
963 
964  if ($emptyoption) $sel_month .= "<option value=\"0\">--</option>\n";
965  for ($i = 1; $i <= 12; $i++)
966  {
967  if($a_long_month)
968  {
969  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
970  }
971  else
972  {
973  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
974  }
975  }
976  $sel_month .= "</select>\n";
977  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
978 
979  // build year select
980  $sel_year = '<select ';
981  if(isset($a_further_options['select_attributes']))
982  {
983  foreach($a_further_options['select_attributes'] as $name => $value)
984  {
985  $sel_year .= ($name.'="'.$value.'" ');
986  }
987  }
988  $sel_year .= $disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
989  if ((strlen($startyear) == 0) || ($startyear > $year))
990  {
991  if (!$emptyoption || $year != 0) $startyear = $year - 5;
992  }
993 
994  if(($year + 5) < (date('Y',time()) + 5))
995  {
996  $end_year = date('Y',time()) + 5;
997  }
998  else
999  {
1000  $end_year = $year + 5;
1001  }
1002 
1003  if ($emptyoption) $sel_year .= "<option value=\"0\">----</option>\n";
1004  for ($i = $startyear; $i <= $end_year; $i++)
1005  {
1006  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
1007  }
1008  $sel_year .= "</select>\n";
1009  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
1010 
1011  //$dateformat = $lng->text["lang_dateformat"];
1012  $dateformat = "d-m-Y";
1013  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1014  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1015  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1016  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1017  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1018  return $dateformat;
1019  }
1020 
1039  public static function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1040  {
1041  global $lng, $ilUser;
1042 
1043  $minute_steps = 1;
1044  $disabled = '';
1045  if(count($a_further_options))
1046  {
1047  if(isset($a_further_options['minute_steps']))
1048  {
1049  $minute_steps = $a_further_options['minute_steps'];
1050  }
1051  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1052  {
1053  $disabled = 'disabled="disabled" ';
1054  }
1055  }
1056 
1057  if ($a_use_default and !strlen("$hour$minute$second")) {
1058  $now = localtime();
1059  $hour = $now[2];
1060  $minute = $now[1];
1061  $second = $now[0];
1062  } else {
1063  $hour = (int)$hour;
1064  $minute = (int)$minute;
1065  $second = (int)$second;
1066  }
1067  // build hour select
1068  $sel_hour = '<select ';
1069  if(isset($a_further_options['select_attributes']))
1070  {
1071  foreach($a_further_options['select_attributes'] as $name => $value)
1072  {
1073  $sel_hour .= $name.'='.$value.' ';
1074  }
1075  }
1076  $sel_hour .= " ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\">\n";
1077 
1078  $format = $ilUser->getTimeFormat();
1079  for ($i = 0; $i <= 23; $i++)
1080  {
1081  if($format == ilCalendarSettings::TIME_FORMAT_24)
1082  {
1083  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1084  }
1085  else
1086  {
1087  $sel_hour .= "<option value=\"$i\">" . date("ga", mktime($i, 0, 0)) . "</option>\n";
1088  }
1089  }
1090  $sel_hour .= "</select>\n";
1091  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1092 
1093  // build minutes select
1094  $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
1095 
1096  for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1097  {
1098  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1099  }
1100  $sel_minute .= "</select>\n";
1101  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1102 
1103  if (!$short) {
1104  // build seconds select
1105  $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\">\n";
1106 
1107  for ($i = 0; $i <= 59; $i++)
1108  {
1109  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1110  }
1111  $sel_second .= "</select>\n";
1112  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1113  }
1114  $timeformat = $lng->text["lang_timeformat"];
1115  if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1116  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1117  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1118  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1119  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1120  if ($short) {
1121  $timeformat = preg_replace("/%%s/", "", $timeformat);
1122  } else {
1123  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1124  }
1125  return $timeformat;
1126  }
1127 
1141  public static function is_email($a_email)
1142  {
1143  // BEGIN Mail: If possible, use PearMail to validate e-mail address
1144  global $ilErr, $ilias;
1145 
1146  // additional check for ilias object is needed,
1147  // otherwise setup will fail with this if branch
1148  if(is_object($ilias))
1149  {
1150  require_once './Services/PEAR/lib/Mail/RFC822.php';
1151  $parser = new Mail_RFC822();
1153  try
1154  {
1155  $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1156  if(!is_a($addresses, 'PEAR_Error') &&
1157  count($addresses) == 1 && $addresses[0]->host != 'ilias'
1158  )
1159  {
1160  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1161  return true;
1162  }
1163  }
1164  catch(Exception $e)
1165  {
1166  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1167  return false;
1168  }
1169  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1170  return false;
1171  }
1172  else
1173  {
1174  $tlds = strtolower(
1175  "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|".
1176  "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|".
1177  "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|".
1178  "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|".
1179  "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|".
1180  "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|".
1181  "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|".
1182  "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|".
1183  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1184 
1185  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));
1186  }
1187  // END Mail: If possible, use PearMail to validate e-mail address
1188  }
1189 
1198  public static function isPassword($a_passwd, &$customError = null)
1199  {
1200  global $lng;
1201 
1202  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1203  $security = ilSecuritySettings::_getInstance();
1204 
1205  if( $security->getAccountSecurityMode() != ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1206  {
1208 
1209  $customError = null;
1210 
1211  switch( true )
1212  {
1213  // no empty password
1214  case empty($a_passwd):
1215 
1216  // min password length is 6
1217  case strlen($a_passwd) < 6:
1218 
1219  // valid chars for password
1220  case !preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~]+$/", $a_passwd):
1221 
1222  return false;
1223 
1224  default:
1225 
1226  return true;
1227  }
1228  }
1229 
1231 
1232  // check if password is empty
1233  if( empty($a_passwd) )
1234  {
1235  $customError = $lng->txt('password_empty');
1236  return false;
1237  }
1238 
1239  $isPassword = true;
1240  $errors = array();
1241 
1242  // check if password to short
1243  if( $security->getPasswordMinLength() > 0 && strlen($a_passwd) < $security->getPasswordMinLength() )
1244  {
1245  $errors[] = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1246  $isPassword = false;
1247  }
1248 
1249  // check if password not to long
1250  if( $security->getPasswordMaxLength() > 0 && strlen($a_passwd) > $security->getPasswordMaxLength() )
1251  {
1252  $errors[] = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1253  $isPassword = false;
1254  }
1255 
1256  // if password must contains Chars and Numbers
1257  if( $security->isPasswordCharsAndNumbersEnabled() )
1258  {
1259  $hasCharsAndNumbers = true;
1260 
1261  // check password for existing chars
1262  if( !preg_match('/[A-Za-z]+/',$a_passwd) )
1263  {
1264  $hasCharsAndNumbers = false;
1265  }
1266 
1267  // check password for existing numbers
1268  if( !preg_match('/[0-9]+/',$a_passwd) )
1269  {
1270  $hasCharsAndNumbers = false;
1271  }
1272 
1273  if( !$hasCharsAndNumbers )
1274  {
1275  $errors[] = $lng->txt('password_must_chars_and_numbers');
1276  $isPassword = false;
1277  }
1278  }
1279 
1280  // if password must contains Special-Chars
1281  if( $security->isPasswordSpecialCharsEnabled() )
1282  {
1283  $specialCharsReg = '/[_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+/';
1284 
1285  // check password for existing special-chars
1286  if( !preg_match($specialCharsReg, $a_passwd) )
1287  {
1288  $errors[] = $lng->txt('password_must_special_chars');
1289  $isPassword = false;
1290  }
1291  }
1292 
1293  // ensure password matches the positive list of chars/special-chars
1294  if( !preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~\/\:\;]+$/", $a_passwd) )
1295  {
1296  $errors[] = $lng->txt('password_contains_invalid_chars');
1297  $isPassword = false;
1298  }
1299 
1300  // build custom error message
1301  if( count($errors) == 1 )
1302  {
1303  $customError = $errors[0];
1304  }
1305  elseif( count($errors) > 1 )
1306  {
1307  $customError = $lng->txt('password_multiple_errors');
1308  $customError .= '<br />'.implode('<br />', $errors);
1309  }
1310 
1311  return $isPassword;
1312  }
1313 
1322  public static function getPasswordRequirementsInfo()
1323  {
1324  global $lng;
1325 
1326  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1327  $security = ilSecuritySettings::_getInstance();
1328 
1329  if( $security->getAccountSecurityMode() == ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1330  {
1331  $validPasswordChars = 'A-Z a-z 0-9 _.+?#-*@!$%~/:;';
1332  }
1333  else
1334  {
1335  $validPasswordChars = 'A-Z a-z 0-9 _.+?#-*@!$%~';
1336  }
1337 
1338  return sprintf($lng->txt('password_allow_chars'), $validPasswordChars);
1339  }
1340 
1341  /*
1342  * validates a login
1343  * @access public
1344  * @param string login
1345  * @return boolean true if valid
1346  */
1347  function isLogin($a_login)
1348  {
1349  if (empty($a_login))
1350  {
1351  return false;
1352  }
1353 
1354  if (strlen($a_login) < 3)
1355  {
1356  return false;
1357  }
1358 
1359  // FIXME - If ILIAS is configured to use RFC 822
1360  // compliant mail addresses we should not
1361  // allow the @ character.
1362  if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1363  {
1364  return false;
1365  }
1366 
1367  return true;
1368  }
1369 
1383  public static function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false,
1384  $a_keep_extension = false)
1385  {
1386  include_once("./Services/Utilities/classes/class.ilStr.php");
1387  if (ilStr::strLen($a_str) > $a_len)
1388  {
1389  if ($a_next_blank)
1390  {
1391  $len = ilStr::strPos($a_str, " ", $a_len);
1392  }
1393  else
1394  {
1395  $len = $a_len;
1396  }
1397  // BEGIN WebDAV
1398  // - Shorten names in the middle, before the filename extension
1399  // Workaround for Windows WebDAV Client:
1400  // Use the unicode ellipsis symbol for shortening instead of
1401  // three full stop characters.
1402  if ($a_keep_extension)
1403  {
1404  $p = strrpos($a_str, '.'); // this messes up normal shortening, see bug #6190
1405  }
1406  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1407  {
1408  $a_str = ilStr::subStr($a_str,0,$len);
1409  if ($a_dots)
1410  {
1411  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1412  }
1413  }
1414  else
1415  {
1416  if ($a_dots)
1417  {
1418  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1419  }
1420  else
1421  {
1422  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1423  }
1424  }
1425  }
1426 
1427  return $a_str;
1428  }
1429 
1440  public static function shortenWords($a_str, $a_len = 30, $a_dots = true)
1441  {
1442  include_once("./Services/Utilities/classes/class.ilStr.php");
1443  $str_arr = explode(" ", $a_str);
1444 
1445  for ($i = 0; $i < count($str_arr); $i++)
1446  {
1447  if (ilStr::strLen($str_arr[$i]) > $a_len)
1448  {
1449  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1450  if ($a_dots)
1451  {
1452  $str_arr[$i].= "...";
1453  }
1454  }
1455  }
1456 
1457  return implode($str_arr, " ");
1458  }
1459 
1469  public static function attribsToArray($a_str)
1470  {
1471  $attribs = array();
1472  while (is_int(strpos($a_str, "=")))
1473  {
1474  $eq_pos = strpos($a_str, "=");
1475  $qu1_pos = strpos($a_str, "\"");
1476  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1477  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1478  {
1479  $var = trim(substr($a_str, 0, $eq_pos));
1480  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1481  $attribs[$var] = $val;
1482  $a_str = substr($a_str, $qu2_pos + 1);
1483  }
1484  else
1485  {
1486  $a_str = "";
1487  }
1488  }
1489  return $attribs;
1490  }
1491 
1503  public static function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1504  {
1505  // check if arguments are directories
1506  if (!@is_dir($a_sdir) or
1507  !@is_dir($a_tdir))
1508  {
1509  return FALSE;
1510  }
1511 
1512  // read a_sdir, copy files and copy directories recursively
1513  $dir = opendir($a_sdir);
1514 
1515  while($file = readdir($dir))
1516  {
1517  if ($file != "." and
1518  $file != "..")
1519  {
1520  // directories
1521  if (@is_dir($a_sdir."/".$file))
1522  {
1523  if (!@is_dir($a_tdir."/".$file))
1524  {
1525  if (!ilUtil::makeDir($a_tdir."/".$file))
1526  return FALSE;
1527 
1528  //chmod($a_tdir."/".$file, 0775);
1529  }
1530 
1531  if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1532  {
1533  return FALSE;
1534  }
1535  }
1536 
1537  // files
1538  if (@is_file($a_sdir."/".$file))
1539  {
1540  if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1541  {
1542  return FALSE;
1543  }
1544  if ($preserveTimeAttributes)
1545  touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1546  }
1547  }
1548  }
1549  return TRUE;
1550  }
1551 
1560  public static function getWebspaceDir($mode = "filesystem")
1561  {
1562  global $ilias;
1563 
1564  if ($mode == "filesystem")
1565  {
1566  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1567  }
1568  else
1569  {
1570  if (defined("ILIAS_MODULE"))
1571  {
1572  return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1573  }
1574  else
1575  {
1576  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1577  }
1578  }
1579 
1580  //return $ilias->ini->readVariable("server","webspace_dir");
1581  }
1582 
1589  public static function getDataDir()
1590  {
1591  return CLIENT_DATA_DIR;
1592  //global $ilias;
1593 
1594  //return $ilias->ini->readVariable("server", "data_dir");
1595  }
1596 
1606  public static function getUsersOnline($a_user_id = 0)
1607  {
1608  include_once("./Services/User/classes/class.ilObjUser.php");
1609  return ilObjUser::_getUsersOnline($a_user_id);
1610  }
1611 
1622  public static function getAssociatedUsersOnline($a_user_id)
1623  {
1624  include_once("./Services/User/classes/class.ilObjUser.php");
1625  return ilObjUser::_getAssociatedUsersOnline($a_user_id);
1626  }
1627 
1635  public static function ilTempnam()
1636  {
1637  $temp_path = ilUtil::getDataDir() . "/temp";
1638  if (!is_dir($temp_path))
1639  {
1640  ilUtil::createDirectory($temp_path);
1641  }
1642  $temp_name = tempnam($temp_path, "tmp");
1643  // --->
1644  // added the following line because tempnam creates a backslash on some
1645  // Windows systems which leads to problems, because the "...\tmp..." can be
1646  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1647  // even under windows (Helmut Schottmüller, 2005-08-31)
1648  $temp_name = str_replace("\\", "/", $temp_name);
1649  // --->
1650  unlink($temp_name);
1651  return $temp_name;
1652  }
1653 
1662  public static function createDirectory($a_dir, $a_mod = 0755)
1663  {
1664  ilUtil::makeDir($a_dir);
1665  //@mkdir($a_dir);
1666  //@chmod($a_dir, $a_mod);
1667  }
1668 
1669 
1678  public static function unzip($a_file, $overwrite = false, $a_flat = false)
1679  {
1680  if (!is_file($a_file))
1681  {
1682  return;
1683  }
1684 
1685  // if flat, move file to temp directory first
1686  if ($a_flat)
1687  {
1688  $tmpdir = ilUtil::ilTempnam();
1689  ilUtil::makeDir($tmpdir);
1690  copy($a_file, $tmpdir.DIRECTORY_SEPARATOR.basename($a_file));
1691  $orig_file = $a_file;
1692  $a_file = $tmpdir.DIRECTORY_SEPARATOR.basename($a_file);
1693  $origpathinfo = pathinfo($orig_file);
1694  }
1695 
1696  $pathinfo = pathinfo($a_file);
1697  $dir = $pathinfo["dirname"];
1698  $file = $pathinfo["basename"];
1699 
1700  // unzip
1701  $cdir = getcwd();
1702  chdir($dir);
1703  $unzip = PATH_TO_UNZIP;
1704 
1705  // the following workaround has been removed due to bug
1706  // http://www.ilias.de/mantis/view.php?id=7578
1707  // since the workaround is quite old, it may not be necessary
1708  // anymore, alex 9 Oct 2012
1709 /*
1710  // workaround for unzip problem (unzip of subdirectories fails, so
1711  // we create the subdirectories ourselves first)
1712  // get list
1713  $unzipcmd = "-Z -1 ".ilUtil::escapeShellArg($file);
1714  $arr = ilUtil::execQuoted($unzip, $unzipcmd);
1715  $zdirs = array();
1716 
1717  foreach($arr as $line)
1718  {
1719  if(is_int(strpos($line, "/")))
1720  {
1721  $zdir = substr($line, 0, strrpos($line, "/"));
1722  $nr = substr_count($zdir, "/");
1723  //echo $zdir." ".$nr."<br>";
1724  while ($zdir != "")
1725  {
1726  $nr = substr_count($zdir, "/");
1727  $zdirs[$zdir] = $nr; // collect directories
1728  //echo $dir." ".$nr."<br>";
1729  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1730  }
1731  }
1732  }
1733 
1734  asort($zdirs);
1735 
1736  foreach($zdirs as $zdir => $nr) // create directories
1737  {
1738  ilUtil::createDirectory($zdir);
1739  }
1740 */
1741 
1742  // real unzip
1743  if (!$overwrite)
1744  {
1745  $unzipcmd = ilUtil::escapeShellArg($file);
1746  }
1747  else
1748  {
1749  $unzipcmd = "-o ".ilUtil::escapeShellArg($file);
1750  }
1751  ilUtil::execQuoted($unzip, $unzipcmd);
1752 
1753  chdir($cdir);
1754 
1755  // if flat, get all files and move them to original directory
1756  if ($a_flat)
1757  {
1758  include_once("./Services/Utilities/classes/class.ilFileUtils.php");
1759  $filearray = array();
1760  ilFileUtils::recursive_dirscan($tmpdir, $filearray);
1761  if (is_array($filearray["file"]))
1762  {
1763  foreach ($filearray["file"] as $k => $f)
1764  {
1765  if (substr($f, 0, 1) != "." && $f != basename($orig_file))
1766  {
1767  copy($filearray["path"][$k].$f, $origpathinfo["dirname"].DIRECTORY_SEPARATOR.$f);
1768  }
1769  }
1770  }
1771  ilUtil::delDir($tmpdir);
1772  }
1773  }
1774 
1781  public static function zip($a_dir, $a_file, $compress_content = false)
1782  {
1783  $cdir = getcwd();
1784 
1785  if($compress_content)
1786  {
1787  $a_dir .="/*";
1788  $pathinfo = pathinfo($a_dir);
1789  chdir($pathinfo["dirname"]);
1790  }
1791 
1792  $pathinfo = pathinfo($a_file);
1793  $dir = $pathinfo["dirname"];
1794  $file = $pathinfo["basename"];
1795 
1796  if(!$compress_content)
1797  {
1798  chdir($dir);
1799  }
1800 
1801  $zip = PATH_TO_ZIP;
1802 
1803  if(!$zip)
1804  {
1805  chdir($cdir);
1806  return false;
1807  }
1808 
1809  if (is_array($a_dir))
1810  {
1811  $source = "";
1812  foreach($a_dir as $dir)
1813  {
1814  $name = basename($dir);
1815  $source.= " ".ilUtil::escapeShellArg($name);
1816  }
1817  }
1818  else
1819  {
1820  $name = basename($a_dir);
1821  if (trim($name) != "*")
1822  {
1823  $source = ilUtil::escapeShellArg($name);
1824  }
1825  else
1826  {
1827  $source = $name;
1828  }
1829  }
1830 
1831  $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1832  ilUtil::execQuoted($zip, $zipcmd);
1833  chdir($cdir);
1834  return true;
1835  }
1836 
1837  public static function CreateIsoFromFolder($a_dir, $a_file)
1838  {
1839  $cdir = getcwd();
1840 
1841  $pathinfo = pathinfo($a_dir);
1842  chdir($pathinfo["dirname"]);
1843 
1844  $pathinfo = pathinfo($a_file);
1845  $dir = $pathinfo["dirname"];
1846  $file = $pathinfo["basename"]; $zipcmd = "-r ".ilUtil::escapeShellArg($a_file)." ".$source;
1847 
1848  $mkisofs = PATH_TO_MKISOFS;
1849  if(!$mkisofs)
1850  {
1851  chdir($cdir);
1852  return false;
1853  }
1854 
1855  $name = basename($a_dir);
1856  $source = ilUtil::escapeShellArg($name);
1857 
1858  $zipcmd = "-r -J -o ".$a_file." ".$source;
1859  ilUtil::execQuoted($mkisofs, $zipcmd);
1860  chdir($cdir);
1861  return true;
1862  }
1863 
1872  public static function getConvertCmd()
1873  {
1874  return PATH_TO_CONVERT;
1875  }
1876 
1884  public static function execConvert($args)
1885  {
1886  ilUtil::execQuoted(PATH_TO_CONVERT, $args);
1887  }
1888 
1895  public static function isConvertVersionAtLeast($a_version)
1896  {
1897  $current_version = ilUtil::execQuoted(PATH_TO_CONVERT, "--version");
1898  $current_version = self::processConvertVersion($current_version[0]);
1899  $version = self::processConvertVersion($a_version);
1900  if($current_version >= $version)
1901  {
1902  return true;
1903  }
1904  return false;
1905  }
1906 
1913  protected static function processConvertVersion($a_version)
1914  {
1915  if(preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)([\.|\-]([0-9]+))?/", $a_version, $match))
1916  {
1917  $version = str_pad($match[1], 2, 0, STR_PAD_LEFT).
1918  str_pad($match[2], 2, 0, STR_PAD_LEFT).
1919  str_pad($match[3], 2, 0, STR_PAD_LEFT).
1920  str_pad($match[5], 2, 0, STR_PAD_LEFT);
1921  return (int)$version;
1922  }
1923  }
1924 
1934  public static function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
1935  $a_background_color = "")
1936  {
1937  $format_str = ($a_target_format != "")
1938  ? strtoupper($a_target_format).":"
1939  : "";
1940  $geometry = "";
1941  if ($a_geometry != "")
1942  {
1943  if (is_int(strpos($a_geometry, "x")))
1944  {
1945  $geometry = " -geometry ".$a_geometry." ";
1946  }
1947  else
1948  {
1949  $geometry = " -geometry ".$a_geometry."x".$a_geometry." ";
1950  }
1951  }
1952 
1953  $bg_color = ($a_background_color != "")
1954  ? " -background color ".$a_background_color." "
1955  : "";
1956  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
1957 
1958  ilUtil::execConvert($convert_cmd);
1959  }
1960 
1971  public static function resizeImage($a_from, $a_to, $a_width, $a_height, $a_constrain_prop = false)
1972  {
1973  if ($a_constrain_prop)
1974  {
1975  $size = " -geometry ".$a_width."x".$a_height." ";
1976  }
1977  else
1978  {
1979  $size = " -resize ".$a_width."x".$a_height."! ";
1980  }
1981  $convert_cmd = ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
1982 
1983  ilUtil::execConvert($convert_cmd);
1984  }
1985 
1992  public static function img($a_src, $a_alt = "", $a_width = "", $a_height = "", $a_border = 0, $a_id = "")
1993  {
1994  $img = '<img src="'.$a_src.'"';
1995  if ($a_alt != "")
1996  {
1997  $img.= ' alt="'.$a_alt.'" title="'.$a_alt.'"';
1998  }
1999  if ($a_width != "")
2000  {
2001  $img.= ' width="'.$a_width.'"';
2002  }
2003  if ($a_height != "")
2004  {
2005  $img.= ' height="'.$a_height.'"';
2006  }
2007  if ($a_id != "")
2008  {
2009  $img.= ' id="'.$a_id.'"';
2010  }
2011  $img.= ' border="'.(int) $a_border.'"/>';
2012 
2013  return $img;
2014  }
2015 
2023  public static function html2pdf($html, $pdf_file)
2024  {
2025  $html_file = str_replace(".pdf",".html",$pdf_file);
2026 
2027  $fp = fopen( $html_file ,"wb");
2028  fwrite($fp, $html);
2029  fclose($fp);
2030 
2031  ilUtil::htmlfile2pdf($html_file,$pdf_file);
2032  }
2033 
2040  public static function htmlfile2pdf($html_file, $pdf_file)
2041  {
2042  $htmldoc_path = PATH_TO_HTMLDOC;
2043 
2044  $htmldoc = "--no-toc ";
2045  $htmldoc .= "--no-jpeg ";
2046  $htmldoc .= "--webpage ";
2047  $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
2048  $htmldoc .= "--bodyfont Arial ";
2049  $htmldoc .= "--charset iso-8859-15 ";
2050  $htmldoc .= "--color ";
2051  $htmldoc .= "--size A4 "; // --landscape
2052  $htmldoc .= "--format pdf ";
2053  $htmldoc .= "--footer ... ";
2054  $htmldoc .= "--header ... ";
2055  $htmldoc .= "--left 60 ";
2056  // $htmldoc .= "--right 200 ";
2057  $htmldoc .= $html_file;
2058  ilUtil::execQuoted($htmldoc_path, $htmldoc);
2059 
2060  }
2061 
2068  public static function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
2069  {
2070  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
2071  // $mime = "application/octet-stream"; // or whatever the mime type is
2072 
2073  include_once './Services/Http/classes/class.ilHTTPS.php';
2074 
2075  //if($_SERVER['HTTPS'])
2076  if( ilHTTPS::getInstance()->isDetected() )
2077  {
2078 
2079  // Added different handling for IE and HTTPS => send pragma after content informations
2083  #header("Pragma: ");
2084  #header("Cache-Control: ");
2085  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
2086  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
2087  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
2088  #header("Cache-Control: post-check=0, pre-check=0", false);
2089  }
2090  else if ($disposition == "attachment")
2091  {
2092  header("Cache-control: private");
2093  }
2094  else
2095  {
2096  header("Cache-Control: no-cache, must-revalidate");
2097  header("Pragma: no-cache");
2098  }
2099 
2100  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2101 
2102  if (strlen($charset))
2103  {
2104  $charset = "; charset=$charset";
2105  }
2106  header("Content-Type: $mime$charset");
2107  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2108  header("Content-Description: ".$ascii_filename);
2109  header("Content-Length: ".(string)(strlen($a_data)));
2110 
2111  //if($_SERVER['HTTPS'])
2112  if( ilHTTPS::getInstance()->isDetected() )
2113  {
2114  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2115  header('Pragma: public');
2116  }
2117 
2118  header("Connection: close");
2119  echo $a_data;
2120  exit;
2121  }
2122 
2123  // BEGIN WebDAV: Show file in browser or provide it as attachment
2131  public static function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false,
2132  $a_exit_after = true)
2133  {
2134  // should we fail silently?
2135  if(!file_exists($a_file))
2136  {
2137  return false;
2138  }
2139 
2140  if ($isInline) {
2141  $disposition = "inline"; // "inline" to view file in browser
2142  } else {
2143  $disposition = "attachment"; // "attachment" to download to hard disk
2144  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
2145  }
2146  // END WebDAV: Show file in browser or provide it as attachment
2147 
2148  if(strlen($a_mime))
2149  {
2150  $mime = $a_mime;
2151  }
2152  else
2153  {
2154  $mime = "application/octet-stream"; // or whatever the mime type is
2155  }
2156  // BEGIN WebDAV: Removed broken HTTPS code.
2157  // END WebDAV: Removed broken HTTPS code.
2158  if ($disposition == "attachment")
2159  {
2160  header("Cache-control: private");
2161  }
2162  else
2163  {
2164  header("Cache-Control: no-cache, must-revalidate");
2165  header("Pragma: no-cache");
2166  }
2167 
2168  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
2169 
2170  header("Content-Type: $mime");
2171  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
2172  header("Content-Description: ".$ascii_filename);
2173 
2174  // #7271: if notice gets thrown download will fail in IE
2175  $filesize = @filesize($a_file);
2176  if ($filesize)
2177  {
2178  header("Content-Length: ".(string)$filesize);
2179  }
2180 
2181  include_once './Services/Http/classes/class.ilHTTPS.php';
2182  #if($_SERVER['HTTPS'])
2183  if(ilHTTPS::getInstance()->isDetected())
2184  {
2185  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
2186  header('Pragma: public');
2187  }
2188 
2189  header("Connection: close");
2190  ilUtil::readFile( $a_file );
2191  if ($removeAfterDelivery)
2192  {
2193  unlink ($a_file);
2194  }
2195  if ($a_exit_after)
2196  {
2197  exit;
2198  }
2199  }
2200 
2201 
2211  public static function readFile($a_file)
2212  {
2213  $chunksize = 1*(1024*1024); // how many bytes per chunk
2214  $buffer = '';
2215  $handle = fopen($a_file, 'rb');
2216  if ($handle === false)
2217  {
2218  return false;
2219  }
2220  while (!feof($handle))
2221  {
2222  $buffer = fread($handle, $chunksize);
2223  print $buffer;
2224  }
2225  return fclose($handle);
2226  }
2227 
2235  public static function getASCIIFilename($a_filename)
2236  {
2237  // The filename must be converted to ASCII, as of RFC 2183,
2238  // section 2.3.
2239 
2251 
2254 
2255  $ascii_filename = htmlentities($a_filename, ENT_NOQUOTES, 'UTF-8');
2256  $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename);
2257  $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename);
2258 
2259  // OS do not allow the following characters in filenames: \/:*?"<>|
2260  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/', '_', $ascii_filename);
2261 
2262  return $ascii_filename;
2263  }
2264 
2271  public static function htmlentitiesOutsideHTMLTags($htmlText)
2272  {
2273  $matches = Array();
2274  $sep = '###HTMLTAG###';
2275 
2276  preg_match_all("@<[^>]*>@", $htmlText, $matches);
2277  $tmp = preg_replace("@(<[^>]*>)@", $sep, $htmlText);
2278  $tmp = explode($sep, $tmp);
2279 
2280  for ($i=0; $i<count($tmp); $i++)
2281  $tmp[$i] = htmlentities($tmp[$i], ENT_COMPAT, "UTF-8");
2282 
2283  $tmp = join($sep, $tmp);
2284 
2285  for ($i=0; $i<count($matches[0]); $i++)
2286  $tmp = preg_replace("@$sep@", $matches[0][$i], $tmp, 1);
2287 
2288  return $tmp;
2289  }
2290 
2297  public static function getJavaPath()
2298  {
2299  return PATH_TO_JAVA;
2300  //global $ilias;
2301 
2302  //return $ilias->getSetting("java_path");
2303  }
2304 
2312  public static function appendUrlParameterString($a_url, $a_par, $xml_style = false)
2313  {
2314  $amp = $xml_style
2315  ? "&amp;"
2316  : "&";
2317 
2318  $url = (is_int(strpos($a_url, "?")))
2319  ? $a_url.$amp.$a_par
2320  : $a_url."?".$a_par;
2321 
2322  return $url;
2323  }
2324 
2340  public static function makeDir($a_dir)
2341  {
2342  $a_dir = trim($a_dir);
2343 
2344  // remove trailing slash (bugfix for php 4.2.x)
2345  if (substr($a_dir,-1) == "/")
2346  {
2347  $a_dir = substr($a_dir,0,-1);
2348  }
2349 
2350  // check if a_dir comes with a path
2351  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2352  {
2353  $path = ".";
2354  }
2355 
2356  // create directory with file permissions of parent directory
2357  umask(0000);
2358  return @mkdir($a_dir,fileperms($path));
2359  }
2360 
2361 
2376  public static function makeDirParents($a_dir)
2377  {
2378  $dirs = array($a_dir);
2379  $a_dir = dirname($a_dir);
2380  $last_dirname = '';
2381 
2382  while($last_dirname != $a_dir)
2383  {
2384  array_unshift($dirs, $a_dir);
2385  $last_dirname = $a_dir;
2386  $a_dir = dirname($a_dir);
2387  }
2388 
2389  // find the first existing dir
2390  $reverse_paths = array_reverse($dirs, TRUE);
2391  $found_index = -1;
2392  foreach ($reverse_paths as $key => $value)
2393  {
2394  if ($found_index == -1)
2395  {
2396  if (is_dir($value))
2397  {
2398  $found_index = $key;
2399  }
2400  }
2401  }
2402 
2403  umask(0000);
2404  foreach ($dirs as $dirindex => $dir)
2405  {
2406  // starting with the longest existing path
2407  if ($dirindex >= $found_index)
2408  {
2409  if (! file_exists($dir))
2410  {
2411  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2412  {
2413  // on some systems there is an error when there is a slash
2414  // at the end of a directory in mkdir, see Mantis #2554
2415  $dir = substr($dir,0,strlen($dir)-1);
2416  }
2417  if (! mkdir($dir, $umask))
2418  {
2419  error_log("Can't make directory: $dir");
2420  return false;
2421  }
2422  }
2423  elseif (! is_dir($dir))
2424  {
2425  error_log("$dir is not a directory");
2426  return false;
2427  }
2428  else
2429  {
2430  // get umask of the last existing parent directory
2431  $umask = fileperms($dir);
2432  }
2433  }
2434  }
2435  return true;
2436  }
2437 
2447  public static function delDir($a_dir, $a_clean_only = false)
2448  {
2449  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2450  {
2451  return;
2452  }
2453 
2454  $current_dir = opendir($a_dir);
2455 
2456  $files = array();
2457 
2458  // this extra loop has been necessary because of a strange bug
2459  // at least on MacOS X. A looped readdir() didn't work
2460  // correctly with larger directories
2461  // when an unlink happened inside the loop. Getting all files
2462  // into the memory first solved the problem.
2463  while($entryname = readdir($current_dir))
2464  {
2465  $files[] = $entryname;
2466  }
2467 
2468  foreach($files as $file)
2469  {
2470  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2471  {
2472  ilUtil::delDir(${a_dir}."/".${file});
2473  }
2474  elseif ($file != "." and $file != "..")
2475  {
2476  unlink(${a_dir}."/".${file});
2477  }
2478  }
2479 
2480  closedir($current_dir);
2481  if (!$a_clean_only)
2482  {
2483  @rmdir(${a_dir});
2484  }
2485  }
2486 
2487 
2494  public static function getDir($a_dir, $a_rec = false, $a_sub_dir = "")
2495  {
2496  $current_dir = opendir($a_dir.$a_sub_dir);
2497 
2498  $dirs = array();
2499  $files = array();
2500  $subitems = array();
2501  while($entry = readdir($current_dir))
2502  {
2503  if(is_dir($a_dir."/".$entry))
2504  {
2505  $dirs[$entry] = array("type" => "dir", "entry" => $entry,
2506  "subdir" => $a_sub_dir);
2507  if ($a_rec && $entry != "." && $entry != "..")
2508  {
2509  $si = ilUtil::getDir($a_dir, true, $a_sub_dir."/".$entry);
2510  $subitems = array_merge($subitems, $si);
2511  }
2512  }
2513  else
2514  {
2515  if ($entry != "." && $entry != "..")
2516  {
2517  $size = filesize($a_dir.$a_sub_dir."/".$entry);
2518  $files[$entry] = array("type" => "file", "entry" => $entry,
2519  "size" => $size, "subdir" => $a_sub_dir);
2520  }
2521  }
2522  }
2523  ksort($dirs);
2524  ksort($files);
2525 
2526  return array_merge($dirs, $files, $subitems);
2527  }
2528 
2535  public static function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2536  {
2537  if (is_array($a_arr))
2538  {
2539  foreach ($a_arr as $k => $v)
2540  {
2541  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2542  }
2543  }
2544 
2545  return $a_arr;
2546  }
2547 
2554  public static function stripSlashesRecursive($a_data, $a_strip_html = true, $a_allow = "")
2555  {
2556  if (is_array($a_data))
2557  {
2558  foreach ($a_data as $k => $v)
2559  {
2560  if (is_array($v))
2561  {
2562  $a_data[$k] = ilUtil::stripSlashesRecursive($v, $a_strip_html, $a_allow);
2563  }
2564  else
2565  {
2566  $a_data[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2567  }
2568  }
2569  }
2570  else
2571  {
2572  $a_data = ilUtil::stripSlashes($a_data, $a_strip_html, $a_allow);
2573  }
2574 
2575  return $a_data;
2576  }
2577 
2585  public static function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2586  {
2587  if (ini_get("magic_quotes_gpc"))
2588  {
2589  $a_str = stripslashes($a_str);
2590  }
2591 //echo "<br><br>-".$a_strip_html."-".htmlentities($a_str);
2592 //echo "<br>-".htmlentities(ilUtil::secureString($a_str, $a_strip_html, $a_allow));
2593  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2594  }
2595 
2603  public static function stripOnlySlashes($a_str)
2604  {
2605  if (ini_get("magic_quotes_gpc"))
2606  {
2607  $a_str = stripslashes($a_str);
2608  }
2609 
2610  return $a_str;
2611  }
2612 
2619  public static function secureString($a_str, $a_strip_html = true, $a_allow = "")
2620  {
2621  // check whether all allowed tags can be made secure
2622  $only_secure = true;
2623  $allow_tags = explode(">", $a_allow);
2624  $sec_tags = ilUtil::getSecureTags();
2625  $allow_array = array();
2626  foreach($allow_tags as $allow)
2627  {
2628  if ($allow != "")
2629  {
2630  $allow = str_replace("<", "", $allow);
2631 
2632  if (!in_array($allow, $sec_tags))
2633  {
2634  $only_secure = false;
2635  }
2636  $allow_array[] = $allow;
2637  }
2638  }
2639 
2640  // default behaviour: allow only secure tags 1:1
2641  if (($only_secure || $a_allow == "") && $a_strip_html)
2642  {
2643  if ($a_allow == "")
2644  {
2645  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2646  "gap", "sub", "sup", "pre", "strike");
2647  }
2648 
2649  // this currently removes parts of strings like "a <= b"
2650  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2651  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2652  $a_str = strip_tags($a_str); // strip all other tags
2653  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2654 
2655  // a possible solution could be something like:
2656  // $a_str = str_replace("<", "&lt;", $a_str);
2657  // $a_str = str_replace(">", "&gt;", $a_str);
2658  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2659  //
2660  // output would be ok then, but input fields would show
2661  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2662  }
2663  else
2664  {
2665  // only for scripts, that need to allow more/other tags and parameters
2666  if ($a_strip_html)
2667  {
2668  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2669  }
2670  }
2671 
2672  return $a_str;
2673  }
2674 
2675  public static function getSecureTags()
2676  {
2677  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2678  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2679  }
2680 
2681  public static function maskSecureTags($a_str, $allow_array)
2682  {
2683  foreach ($allow_array as $t)
2684  {
2685  switch($t)
2686  {
2687  case "a":
2688  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2689  break;
2690 
2691  case "img":
2692  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2693  break;
2694 
2695  case "p":
2696  case "div":
2697  $a_str = ilUtil::maskTag($a_str, $t, array(
2698  array("param" => "align", "value" => "left"),
2699  array("param" => "align", "value" => "center"),
2700  array("param" => "align", "value" => "justify"),
2701  array("param" => "align", "value" => "right")
2702  ));
2703  break;
2704 
2705  default:
2706  $a_str = ilUtil::maskTag($a_str, $t);
2707  break;
2708  }
2709  }
2710 
2711  return $a_str;
2712  }
2713 
2714  public static function unmaskSecureTags($a_str, $allow_array)
2715  {
2716  foreach ($allow_array as $t)
2717  {
2718  switch($t)
2719  {
2720  case "a":
2721  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2722  break;
2723 
2724  case "img":
2725  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2726  break;
2727 
2728  case "p":
2729  case "div":
2730  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2731  array("param" => "align", "value" => "left"),
2732  array("param" => "align", "value" => "center"),
2733  array("param" => "align", "value" => "justify"),
2734  array("param" => "align", "value" => "right")
2735  ));
2736  break;
2737 
2738  default:
2739  $a_str = ilUtil::unmaskTag($a_str, $t);
2740  break;
2741  }
2742  }
2743 
2744  return $a_str;
2745  }
2746 
2754  public static function securePlainString($a_str)
2755  {
2756  if (ini_get("magic_quotes_gpc"))
2757  {
2758  return stripslashes($a_str);
2759  }
2760  else
2761  {
2762  return $a_str;
2763  }
2764  }
2781  public static function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2782  {
2783  $encoded = "";
2784 
2785  if ($a_make_links_clickable)
2786  {
2787  // Find text sequences in the plain text string which match
2788  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2789  // Encode all other text sequences in the plain text string using
2790  // htmlspecialchars and nl2br.
2791  // The following expressions matches URI's as specified in RFC 2396.
2792  //
2793  // The expression matches URI's, which start with some well known
2794  // schemes, like "http:", or with "www.". This must be followed
2795  // by at least one of the following RFC 2396 expressions:
2796  // - alphanum: [a-zA-Z0-9]
2797  // - reserved: [;\/?:|&=+$,]
2798  // - mark: [\\-_.!~*\'()]
2799  // - escaped: %[0-9a-fA-F]{2}
2800  // - fragment delimiter: #
2801  // - uric_no_slash: [;?:@&=+$,]
2802  $matches = array();
2803  $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);
2804  $pos1 = 0;
2805  $encoded = "";
2806  foreach ($matches as $match)
2807  {
2808  }
2809  foreach ($matches[0] as $match)
2810  {
2811  $matched_text = $match[0];
2812  $pos2 = $match[1];
2813  if ($matched_offset != previous_offset)
2814  {
2815  // encode plain text
2816  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2817  }
2818  // encode URI
2819  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2820 
2821 
2822  $pos1 = $pos2 + strlen($matched_text);
2823  }
2824  if ($pos1 < strlen($a_str))
2825  {
2826  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2827  }
2828  }
2829  else
2830  {
2831  $encoded = nl2br(htmlspecialchars($a_str));
2832  }
2833  return $encoded;
2834  }
2835 
2836 
2837  public static function maskAttributeTag($a_str, $tag, $tag_att)
2838  {
2839  global $ilLog;
2840 
2841  $ws = "[ \t\r\f\v\n]*";
2842  $att = $ws."[^>]*".$ws;
2843 
2844  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2845  $a_str, $found))
2846  {
2847  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2848  $esc = array();
2849  foreach($un as $v)
2850  {
2851  $esc[] = "\\".$v;
2852  }
2853  $ff = str_replace($un, $esc, $found[1]);
2854 
2855  $old_str = $a_str;
2856  $a_str = eregi_replace("<".$ff.">",
2857  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2858  if ($old_str == $a_str)
2859  {
2860  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2861  htmlentities($a_str));
2862  return $a_str;
2863  }
2864  }
2865  $a_str = str_ireplace("</$tag>",
2866  "&lt;/$tag&gt;", $a_str);
2867  return $a_str;
2868  }
2869 
2870  public static function unmaskAttributeTag($a_str, $tag, $tag_att)
2871  {
2872  global $ilLog;
2873 
2874  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2875  $a_str, $found))
2876  {
2877  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2878  $esc = array();
2879  foreach($un as $v)
2880  {
2881  $esc[] = "\\".$v;
2882  }
2883  $ff = str_replace($un, $esc, $found[1]);
2884 
2885  $old_str = $a_str;
2886  $a_str = eregi_replace("&lt;".$ff."&gt;",
2887  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2888  if ($old_str == $a_str)
2889  {
2890  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2891  htmlentities($a_str));
2892  return $a_str;
2893  }
2894  }
2895  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2896  return $a_str;
2897  }
2898 
2899  public static function maskTag($a_str, $t, $fix_param = "")
2900  {
2901  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2902  "&lt;".$t."&gt;", $a_str);
2903  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2904  "&lt;/".$t."&gt;", $a_str);
2905 
2906  if (is_array($fix_param))
2907  {
2908  foreach ($fix_param as $p)
2909  {
2910  $k = $p["param"];
2911  $v = $p["value"];
2912  $a_str = str_replace("<$t $k=\"$v\">",
2913  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2914  }
2915  }
2916 
2917  return $a_str;
2918  }
2919 
2920  public static function unmaskTag($a_str, $t, $fix_param = "")
2921  {
2922  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2923  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2924 
2925  if (is_array($fix_param))
2926  {
2927  foreach ($fix_param as $p)
2928  {
2929  $k = $p["param"];
2930  $v = $p["value"];
2931  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2932  "<"."$t $k=\"$v\"".">", $a_str);
2933  }
2934  }
2935  return $a_str;
2936  }
2937 
2938  public static function secureLink($a_str)
2939  {
2940  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2941  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2942  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2943  return $a_str;
2944  }
2945 
2959  public static function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2960  {
2961  //$a_str = strip_tags($a_str, $a_allow);
2962 
2963  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
2964  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
2965  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
2966  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
2967  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
2968  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
2969  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
2970  "title,tr,tt,u,ul,var";
2971  $a_allow = strtolower ($a_allow);
2972  $negatives = explode(",",$negativestr);
2973  $outer_old_str = "";
2974  while($outer_old_str != $a_str)
2975  {
2976  $outer_old_str = $a_str;
2977  foreach ($negatives as $item)
2978  {
2979  $pos = strpos($a_allow, "<$item>");
2980 
2981  // remove complete tag, if not allowed
2982  if ($pos === false)
2983  {
2984  $old_str = "";
2985  while($old_str != $a_str)
2986  {
2987  $old_str = $a_str;
2988  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2989  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2990  }
2991  }
2992  }
2993  }
2994 
2995  if ($a_rm_js)
2996  {
2997  // remove all attributes if an "on..." attribute is given
2998  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2999 
3000  // remove all attributes if a "javascript" is within tag
3001  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
3002 
3003  // remove all attributes if an "expression" is within tag
3004  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
3005  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
3006  }
3007 
3008  return $a_str;
3009  }
3010 
3011 
3020  public static function addSlashes($a_str)
3021  {
3022  if (ini_get("magic_quotes_gpc"))
3023  {
3024  return $a_str;
3025  }
3026  else
3027  {
3028  return addslashes($a_str);
3029  }
3030  }
3031 
3043  public static function prepareFormOutput($a_str, $a_strip = false)
3044  {
3045  if($a_strip)
3046  {
3047  $a_str = ilUtil::stripSlashes($a_str);
3048  }
3049  $a_str = htmlspecialchars($a_str);
3050  // Added replacement of curly brackets to prevent
3051  // problems with PEAR templates, because {xyz} will
3052  // be removed as unused template variable
3053  $a_str = str_replace("{", "&#123;", $a_str);
3054  $a_str = str_replace("}", "&#125;", $a_str);
3055  // needed for LaTeX conversion \\ in LaTeX is a line break
3056  // but without this replacement, php changes \\ to \
3057  $a_str = str_replace("\\", "&#92;", $a_str);
3058  return $a_str;
3059  }
3060 
3061 
3071  public static function prepareDBString($a_str)
3072  {
3073  return addslashes($a_str);
3074  }
3075 
3076 
3085  public static function removeItemFromDesktops($a_id)
3086  {
3087  return ilObjUser::_removeItemFromDesktops($a_id);
3088  }
3089 
3090 
3100  public static function extractParameterString($a_parstr)
3101  {
3102  // parse parameters in array
3103  $par = array();
3104  $ok=true;
3105  while(($spos=strpos($a_parstr,"=")) && $ok)
3106  {
3107  // extract parameter
3108  $cpar = substr($a_parstr,0,$spos);
3109  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
3110  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
3111  $cpar = substr($cpar,1,strlen($cpar)-1);
3112  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
3113  $cpar = substr($cpar,0,strlen($cpar)-1);
3114 
3115  // parameter name should only
3116  $cpar_old = "";
3117  while($cpar != $cpar_old)
3118  {
3119  $cpar_old = $cpar;
3120  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
3121  }
3122 
3123  // extract value
3124  if ($cpar != "")
3125  {
3126  if($spos=strpos($a_parstr,"\""))
3127  {
3128  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
3129  $spos=strpos($a_parstr,"\"");
3130  if(is_int($spos))
3131  {
3132  $cval = substr($a_parstr,0,$spos);
3133  $par[$cpar]=$cval;
3134  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
3135  }
3136  else
3137  $ok=false;
3138  }
3139  else
3140  $ok=false;
3141  }
3142  }
3143 
3144  if($ok) return $par; else return false;
3145  }
3146 
3147  public static function assembleParameterString($a_par_arr)
3148  {
3149  if (is_array($a_par_arr))
3150  {
3151  $target_arr = array();
3152  foreach ($a_par_arr as $par => $val)
3153  {
3154  $target_arr[] = "$par=\"$val\"";
3155  }
3156  $target_str = implode(", ", $target_arr);
3157  }
3158 
3159  return $target_str;
3160  }
3161 
3168  public static function dumpString($a_str)
3169  {
3170  $ret = $a_str.": ";
3171  for($i=0; $i<strlen($a_str); $i++)
3172  {
3173  $ret.= ord(substr($a_str,$i,1))." ";
3174  }
3175  return $ret;
3176  }
3177 
3178 
3185  public static function yn2tf($a_yn)
3186  {
3187  if(strtolower($a_yn) == "y")
3188  {
3189  return true;
3190  }
3191  else
3192  {
3193  return false;
3194  }
3195  }
3196 
3203  public static function tf2yn($a_tf)
3204  {
3205  if($a_tf)
3206  {
3207  return "y";
3208  }
3209  else
3210  {
3211  return "n";
3212  }
3213  }
3214 
3225  public static function sort_func ($a, $b)
3226  {
3227  global $array_sortby,$array_sortorder;
3228 
3229  // this comparison should give optimal results if
3230  // locale is provided and mb string functions are supported
3231  if ($array_sortorder == "asc")
3232  {
3233  return ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3234  }
3235 
3236  if ($array_sortorder == "desc")
3237  {
3238  return !ilStr::strCmp($a[$array_sortby], $b[$array_sortby]);
3239  return strcoll(ilStr::strToUpper($b[$array_sortby]), ilStr::strToUpper($a[$array_sortby]));
3240  }
3241  }
3242 
3253  public static function sort_func_numeric ($a, $b)
3254  {
3255  global $array_sortby,$array_sortorder;
3256 
3257  if ($array_sortorder == "asc")
3258  {
3259  return $a["$array_sortby"] > $b["$array_sortby"];
3260  }
3261 
3262  if ($array_sortorder == "desc")
3263  {
3264  return $a["$array_sortby"] < $b["$array_sortby"];
3265  }
3266  }
3279  public static function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
3280  $a_keep_keys = false)
3281  {
3282  include_once("./Services/Utilities/classes/class.ilStr.php");
3283 
3284  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3285  if (! $a_keep_keys) {
3286  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
3287  }
3288  // END WebDAV Provide a 'stable' sort algorithm
3289 
3290  global $array_sortby,$array_sortorder;
3291 
3292  $array_sortby = $a_array_sortby;
3293 
3294  if ($a_array_sortorder == "desc")
3295  {
3296  $array_sortorder = "desc";
3297  }
3298  else
3299  {
3300  $array_sortorder = "asc";
3301  }
3302  if($a_numeric)
3303  {
3304  if ($a_keep_keys)
3305  {
3306  uasort($array, array("ilUtil", "sort_func_numeric"));
3307  }
3308  else
3309  {
3310  usort($array, array("ilUtil", "sort_func_numeric"));
3311  }
3312  }
3313  else
3314  {
3315  if ($a_keep_keys)
3316  {
3317  uasort($array, array("ilUtil", "sort_func"));
3318  }
3319  else
3320  {
3321  usort($array, array("ilUtil", "sort_func"));
3322  }
3323  }
3324  //usort($array,"ilUtil::sort_func");
3325 
3326  return $array;
3327  }
3328  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3343  public static function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
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 
3358  // Create a copy of the array values for sorting
3359  $sort_array = array_values($array);
3360 
3361  if($a_numeric)
3362  {
3363  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3364  }
3365  else
3366  {
3367  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3368  }
3369 
3370  return $sort_array;
3371  }
3372  public static function mergesort(&$array, $cmp_function = 'strcmp') {
3373  // Arrays of size < 2 require no action.
3374  if (count($array) < 2) return;
3375 
3376  // Split the array in half
3377  $halfway = count($array) / 2;
3378  $array1 = array_slice($array, 0, $halfway);
3379  $array2 = array_slice($array, $halfway);
3380 
3381  // Recurse to sort the two halves
3382  ilUtil::mergesort($array1, $cmp_function);
3383  ilUtil::mergesort($array2, $cmp_function);
3384 
3385  // If all of $array1 is <= all of $array2, just append them.
3386  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3387  $array = array_merge($array1, $array2);
3388  return;
3389  }
3390 
3391  // Merge the two sorted arrays into a single sorted array
3392  $array = array();
3393  $ptr1 = $ptr2 = 0;
3394  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3395  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3396  $array[] = $array1[$ptr1++];
3397  }
3398  else {
3399  $array[] = $array2[$ptr2++];
3400  }
3401  }
3402 
3403  // Merge the remainder
3404  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3405  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3406 
3407  return;
3408  }
3409  // END WebDAV: Provide a 'stable' sort algorithm
3410 
3422  public static function unique_multi_array($array, $sub_key)
3423  {
3424  $target = array();
3425  $existing_sub_key_values = array();
3426 
3427  foreach ($array as $key=>$sub_array)
3428  {
3429  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3430  {
3431  $existing_sub_key_values[] = $sub_array[$sub_key];
3432  $target[$key] = $sub_array;
3433  }
3434  }
3435 
3436  return $target;
3437  }
3438 
3439 
3449  public static function getGDSupportedImageType($a_desired_type)
3450  {
3451  $a_desired_type = strtolower($a_desired_type);
3452  // get supported Image Types
3453  $im_types = ImageTypes();
3454 
3455  switch($a_desired_type)
3456  {
3457  case "jpg":
3458  if ($im_types & IMG_JPG) return "jpg";
3459  if ($im_types & IMG_GIF) return "gif";
3460  if ($im_types & IMG_PNG) return "png";
3461  break;
3462 
3463  case "gif":
3464  if ($im_types & IMG_GIF) return "gif";
3465  if ($im_types & IMG_JPG) return "jpg";
3466  if ($im_types & IMG_PNG) return "png";
3467  break;
3468 
3469  case "png":
3470  if ($im_types & IMG_PNG) return "png";
3471  if ($im_types & IMG_JPG) return "jpg";
3472  if ($im_types & IMG_GIF) return "gif";
3473  break;
3474  }
3475 
3476  return "";
3477  }
3478 
3488  public static function deducibleSize($a_mime)
3489  {
3490  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3491  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3492  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3493  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3494  {
3495  return true;
3496  }
3497  else
3498  {
3499  return false;
3500  }
3501  }
3502 
3503 
3511  public static function redirect($a_script)
3512  {
3513  global $log, $PHP_SELF;
3514 
3515 //echo "<br>".$a_script;
3516  if (!is_int(strpos($a_script, "://")))
3517  {
3518  if (substr($a_script, 0, 1) != "/" && defined("ILIAS_HTTP_PATH"))
3519  {
3520  if (is_int(strpos($_SERVER["PHP_SELF"], "/setup/")))
3521  {
3522  $a_script = "setup/".$a_script;
3523  }
3524  $a_script = ILIAS_HTTP_PATH."/".$a_script;
3525  }
3526  }
3527 //echo "<br>".$a_script; exit;
3528 
3529  // include the user interface hook
3530  global $ilPluginAdmin;
3531  if (is_object($ilPluginAdmin))
3532  {
3533  $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk");
3534  foreach ($pl_names as $pl)
3535  {
3536  $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl);
3537  $gui_class = $ui_plugin->getUIClassInstance();
3538  $resp = $gui_class->getHTML("Services/Utilities", "redirect", array("html" => $a_script));
3539  if ($resp["mode"] != ilUIHookPluginGUI::KEEP)
3540  {
3541  $a_script = $gui_class->modifyHTML($a_script, $resp);
3542  }
3543  }
3544  }
3545 
3546  header("Location: ".$a_script);
3547  exit();
3548  }
3549 
3558  public static function insertInstIntoID($a_value)
3559  {
3560  if (substr($a_value, 0, 4) == "il__")
3561  {
3562  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3563  }
3564 
3565  return $a_value;
3566  }
3567 
3578  public static function groupNameExists($a_group_name,$a_id = 0)
3579  {
3580  global $ilDB,$ilErr;
3581 
3582  if (empty($a_group_name))
3583  {
3584  $message = __METHOD__.": No groupname given!";
3585  $ilErr->raiseError($message,$ilErr->WARNING);
3586  }
3587 
3588  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3589 
3590  $q = "SELECT obj_id FROM object_data ".
3591  "WHERE title = ".$ilDB->quote($a_group_name, "text")." ".
3592  "AND type = ".$ilDB->quote("grp", "text").
3593  $clause;
3594 
3595  $r = $ilDB->query($q);
3596 
3597  if ($r->numRows())
3598  {
3599  return true;
3600  }
3601  else
3602  {
3603  return false;
3604  }
3605  }
3606 
3613  public static function getMemString()
3614  {
3615  $my_pid = getmypid();
3616  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3617  }
3618 
3625  public static function isWindows()
3626  {
3627  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3628  {
3629  return true;
3630  }
3631  return false;
3632  }
3633 
3634 
3635  public static function escapeShellArg($a_arg)
3636  {
3637  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3638  // see also ilias bug 5630
3639  return escapeshellarg($a_arg);
3640  }
3641 
3651  public static function escapeShellCmd($a_arg)
3652  {
3653  if(ini_get('safe_mode') == 1)
3654  {
3655  return $a_arg;
3656  }
3657  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3658  return escapeshellcmd($a_arg);
3659  }
3660 
3670  public static function execQuoted($cmd, $args = NULL)
3671  {
3672  global $ilLog;
3673 
3674  if(ilUtil::isWindows() && strpos($cmd, " ") !== false && substr($cmd, 0, 1) !== '"')
3675  {
3676  // cmd won't work without quotes
3677  $cmd = '"'.$cmd.'"';
3678  if($args)
3679  {
3680  // args are also quoted, workaround is to quote the whole command AGAIN
3681  // was fixed in php 5.2 (see php bug #25361)
3682  if (version_compare(phpversion(), "5.2", "<") && strpos($args, '"') !== false)
3683  {
3684  $cmd = '"'.$cmd." ".$args.'"';
3685  }
3686  // args are not quoted or php is fixed, just append
3687  else
3688  {
3689  $cmd .= " ".$args;
3690  }
3691  }
3692  }
3693  // nothing todo, just append args
3694  else if($args)
3695  {
3696  $cmd .= " ".$args;
3697  }
3698 //echo "<br>".$cmd;
3699  exec($cmd, $arr);
3700 // $ilLog->write("ilUtil::execQuoted: ".$cmd.".");
3701  return $arr;
3702  }
3703 
3726  public static function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3727  {
3728  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3729  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3730  {
3731  $target_time = time();
3732  }
3733  else
3734  {
3735  if ($year < 1970)
3736  {
3737  return 0;
3738  }
3739  }
3740  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3741  $difference = $target_time - $starting_time;
3742  $days = (($difference - ($difference % 86400)) / 86400);
3743  $difference = $difference - ($days * 86400) + 3600;
3744  return ($days + 25570 + ($difference / 86400));
3745  }
3746 
3753  public static function renameExecutables($a_dir)
3754  {
3755  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3756  foreach ($def_arr as $def)
3757  {
3758  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3759  }
3760 
3761  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3762  foreach ($def_arr as $def)
3763  {
3764  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3765  }
3766  }
3767 
3780  public static function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3781  {
3782  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3783  || trim($a_old_suffix) == "")
3784  {
3785  return false;
3786  }
3787 
3788  // check if argument is directory
3789  if (!@is_dir($a_dir))
3790  {
3791  return false;
3792  }
3793 
3794  // read a_dir
3795  $dir = opendir($a_dir);
3796 
3797  while($file = readdir($dir))
3798  {
3799  if ($file != "." and
3800  $file != "..")
3801  {
3802  // directories
3803  if (@is_dir($a_dir."/".$file))
3804  {
3805  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3806  }
3807 
3808  // files
3809  if (@is_file($a_dir."/".$file))
3810  {
3811  // first check for files with trailing dot
3812  if(strrpos($file,'.') == (strlen($file) - 1))
3813  {
3814  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3815  $file = substr($file,0,-1);
3816  }
3817 
3818  $path_info = pathinfo($a_dir."/".$file);
3819 
3820  if (strtolower($path_info["extension"]) ==
3821  strtolower($a_old_suffix))
3822  {
3823  $pos = strrpos($a_dir."/".$file, ".");
3824  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3825  rename($a_dir."/".$file, $new_name);
3826  }
3827  }
3828  }
3829  }
3830  return true;
3831  }
3832 
3833  public static function isAPICall () {
3834  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3835  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3836  }
3837 
3838  public static function KT_replaceParam($qstring, $paramName, $paramValue) {
3839  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3840  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3841  } else {
3842  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3843  }
3844  }
3845 
3846  public static function replaceUrlParameterString ($url, $parametersArray) {
3847 
3848  foreach ($parametersArray as $paramName => $paramValue ) {
3849  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3850  }
3851  return $url;
3852  }
3853 
3860  public static function generatePasswords ($a_number)
3861  {
3862  $ret = array();
3863  srand((double) microtime()*1000000);
3864 
3865  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
3866  $security = ilSecuritySettings::_getInstance();
3867 
3868  for ($i=1; $i<=$a_number; $i++)
3869  {
3870  $min = ($security->getPasswordMinLength() > 0)
3871  ? $security->getPasswordMinLength()
3872  : 6;
3873  $max = ($security->getPasswordMaxLength() > 0)
3874  ? $security->getPasswordMaxLength()
3875  : 10;
3876  if ($min > $max)
3877  {
3878  $max = $max + 1;
3879  }
3880  $length = rand($min,$max);
3881  $next = rand(1,2);
3882  $vowels = "aeiou";
3883  $consonants = "bcdfghjklmnpqrstvwxyz";
3884  $numbers = "1234567890";
3885  $special = "_.+?#-*@!$%~";
3886  $pw = "";
3887 
3888  // position for number
3889  if ($security->isPasswordCharsAndNumbersEnabled())
3890  {
3891  $num_pos = rand(0, $length - 1);
3892  }
3893 
3894  // position for special character
3895  if ($security->isPasswordSpecialCharsEnabled())
3896  {
3897  $spec_pos = rand(0, $length - 1);
3898  if ($security->isPasswordCharsAndNumbersEnabled())
3899  {
3900  if ($num_pos == $spec_pos) // not same position for number/special
3901  {
3902  if ($spec_pos > 0)
3903  {
3904  $spec_pos -= 1;
3905  }
3906  else
3907  {
3908  $spec_pos += 1;
3909  }
3910  }
3911  }
3912  }
3913  for ($j=0; $j < $length; $j++)
3914  {
3915  if ($security->isPasswordCharsAndNumbersEnabled() && $num_pos == $j)
3916  {
3917  $pw.= $numbers[rand(0,strlen($numbers)-1)];
3918  }
3919  else if ($security->isPasswordSpecialCharsEnabled() && $spec_pos == $j)
3920  {
3921  $pw.= $special[rand(0,strlen($special)-1)];
3922  }
3923  else
3924  {
3925  switch ($next)
3926  {
3927  case 1:
3928  $pw.= $consonants[rand(0,strlen($consonants)-1)];
3929  $next = 2;
3930  break;
3931 
3932  case 2:
3933  $pw.= $vowels[rand(0,strlen($vowels)-1)];
3934  $next = 1;
3935  break;
3936  }
3937  }
3938  }
3939 
3940  $ret[] = $pw;
3941  }
3942  return $ret;
3943  }
3944 
3945  public static function removeTrailingPathSeparators($path)
3946  {
3947  $path = preg_replace("/[\/\\\]+$/", "", $path);
3948  return $path;
3949  }
3950 
3961  public static function array_php2js($data)
3962  {
3963  if (empty($data))
3964  {
3965  $data = array();
3966  }
3967 
3968  foreach($data as $k=>$datum)
3969  {
3970  if(is_null($datum)) $data[$k] = 'null';
3971  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
3972  if(is_array($datum)) $data[$k] = array_php2js($datum);
3973  }
3974 
3975  return "[" . implode(', ', $data) . "]";
3976  }
3977 
3984  public static function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3985  {
3986  global $lng;
3987 
3988  if (IL_VIRUS_SCANNER != "None")
3989  {
3990  require_once("./Services/VirusScanner/classes/class.ilVirusScannerFactory.php");
3992  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3993  {
3994  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
3995  {
3996  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3997  if ($vs->fileCleaned())
3998  {
3999  $vs_txt.= "<br />".$lng->txt("cleaned_file").
4000  "<br />".$clean_txt;
4001  $vs_txt.= "<br />".$lng->txt("repeat_scan");
4002  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
4003  {
4004  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
4005  "<br />".nl2br($vs2_txt));
4006  }
4007  else
4008  {
4009  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
4010  }
4011  }
4012  else
4013  {
4014  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
4015  }
4016  }
4017  else
4018  {
4019  return array(false, nl2br($vs_txt));
4020  }
4021  }
4022  }
4023 
4024  return array(true,"");
4025  }
4026 
4027 
4034  public static function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true,
4035  $a_mode = "move_uploaded")
4036  {
4037  global $lng, $ilias;
4038 //echo "<br>ilUtli::moveuploadedFile($a_name)";
4039 
4040  if (!is_file($a_file))
4041  {
4042  if ($a_raise_errors)
4043  {
4044  $ilias->raiseError($lng->txt("upload_error_file_not_found"), $ilias->error_obj->MESSAGE);
4045  }
4046  else
4047  {
4048  ilUtil::sendFailure($lng->txt("upload_error_file_not_found"), true);
4049  }
4050  return false;
4051  }
4052 
4053  // virus handling
4054  $vir = ilUtil::virusHandling($a_file, $a_name);
4055  if (!$vir[0])
4056  {
4057  unlink($a_file);
4058  if ($a_raise_errors)
4059  {
4060  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
4061  $vir[1],
4062  $ilias->error_obj->MESSAGE);
4063  }
4064  else
4065  {
4066  ilUtil::sendFailure($lng->txt("file_is_infected")."<br />".
4067  $vir[1], true);
4068  }
4069  return false;
4070  }
4071  else
4072  {
4073  if ($vir[1] != "")
4074  {
4075  ilUtil::sendInfo($vir[1], true);
4076  }
4077  switch ($a_mode)
4078  {
4079  case "rename":
4080  return rename($a_file, $a_target);
4081  break;
4082 
4083  case "copy":
4084  return copy($a_file, $a_target);
4085  break;
4086 
4087  default:
4088  return move_uploaded_file($a_file, $a_target);
4089  break;
4090  }
4091  }
4092  }
4093 
4094 
4101  public static function date_mysql2time($mysql_date_time) {
4102  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
4103  list($jahr, $monat, $tag) = explode("-", $datum);
4104  list($std, $min, $sec) = explode(":", $uhrzeit);
4105  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
4106  }
4107 
4114  public static function now()
4115  {
4116  return date("Y-m-d H:i:s");
4117  }
4118 
4134  public static function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
4135  {
4136  $resultarray = array();
4137  foreach ($row as $rowindex => $entry)
4138  {
4139  $surround = FALSE;
4140  if ($quoteAll)
4141  {
4142  $surround = TRUE;
4143  }
4144  if (strpos($entry, "\"") !== FALSE)
4145  {
4146  $entry = str_replace("\"", "\"\"", $entry);
4147  $surround = TRUE;
4148  }
4149  if (strpos($entry, $separator) !== FALSE)
4150  {
4151  $surround = TRUE;
4152  }
4153  if ($compatibleWithMSExcel)
4154  {
4155  // replace all CR LF with LF (for Excel for Windows compatibility
4156  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4157  }
4158  if ($surround)
4159  {
4160  if ($outUTF8)
4161  {
4162  $resultarray[$rowindex] = "\"" . $entry . "\"";
4163  }
4164  else
4165  {
4166  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4167  }
4168  }
4169  else
4170  {
4171  if ($outUTF8)
4172  {
4173  $resultarray[$rowindex] = $entry;
4174  }
4175  else
4176  {
4177  $resultarray[$rowindex] = utf8_decode($entry);
4178  }
4179  }
4180  }
4181  return $resultarray;
4182  }
4183 
4184  // validates a domain name (example: www.ilias.de)
4185  public static function isDN($a_str)
4186  {
4187  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
4188  }
4189 
4190  // validates an IP address (example: 192.168.1.1)
4191  public static function isIPv4($a_str)
4192  {
4193  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])\.".
4194  "(\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));
4195  }
4196 
4197 
4226  public static function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
4227  {
4228  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias,$tree;
4229 
4230  if(!is_array($a_obj_type))
4231  {
4232  $where = "WHERE type = ".$ilDB->quote($a_obj_type, "text")." ";
4233  }
4234  else
4235  {
4236  $where = "WHERE ".$ilDB->in("type", $a_obj_type, false, "text")." ";
4237  }
4238 
4239  // limit number of results default is search result limit
4240  if(!$limit)
4241  {
4242  $limit = $ilias->getSetting('search_max_hits',100);
4243  }
4244  if($limit == -1)
4245  {
4246  $limit = 10000;
4247  }
4248 
4249  // default to logged in usr
4250  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
4251  $a_roles = $rbacreview->assignedRoles($a_usr_id);
4252 
4253  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
4254  // is assigned to the system role
4255  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
4256  {
4257  $query = "SELECT ref_id FROM object_reference obr LEFT JOIN object_data obd ON obr.obj_id = obd.obj_id ".
4258  "LEFT JOIN tree ON obr.ref_id = tree.child ".
4259  $where.
4260  "AND tree = 1";
4261 
4262  $res = $ilDB->query($query);
4263  $counter = 0;
4264  while($row = $ilDB->fetchObject($res))
4265  {
4266  // Filter recovery folder
4267  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4268  {
4269  continue;
4270  }
4271 
4272  if($counter++ >= $limit)
4273  {
4274  break;
4275  }
4276 
4277  $ref_ids[] = $row->ref_id;
4278  }
4279  return $ref_ids ? $ref_ids : array();
4280  } // End Administrators
4281 
4282  // Check ownership if it is not asked for edit_permission or a create permission
4283  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
4284  {
4285  $check_owner = ") ";
4286  }
4287  else
4288  {
4289  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id, "integer").") ";
4290  }
4291 
4292  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
4293  $ops_id = $ops_ids[0];
4294 
4295  $and = "AND ((".$ilDB->in("rol_id", $a_roles, false, "integer")." ";
4296 
4297  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference obr ".
4298  "JOIN object_data obd ON obd.obj_id = obr.obj_id ".
4299  "LEFT JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
4300  $where.
4301  $and.
4302  "AND (".$ilDB->like("ops_id", "text","%i:".$ops_id."%"). " ".
4303  "OR ".$ilDB->like("ops_id", "text", "%:\"".$ops_id."\";%").")) ".
4304  $check_owner;
4305 
4306  $res = $ilDB->query($query);
4307  $counter = 0;
4308  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4309  {
4310  if($counter >= $limit)
4311  {
4312  break;
4313  }
4314 
4315  // Filter objects in recovery folder
4316  if($tree->isGrandChild(RECOVERY_FOLDER_ID, $row->ref_id))
4317  {
4318  continue;
4319  }
4320 
4321  // Check deleted, hierarchical access ...
4322  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
4323  {
4324  $counter++;
4325  $ref_ids[] = $row->ref_id;
4326  }
4327  }
4328  return $ref_ids ? $ref_ids : array();
4329  }
4330 
4340  public static function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]")
4341  {
4342  global $tpl, $lng, $ilUser;
4343 
4344  $cgi = URL_TO_LATEX;
4345 
4346  // - take care of html exports (-> see buildLatexImages)
4347  include_once "./Services/Administration/classes/class.ilSetting.php";
4348  $mathJaxSetting = new ilSetting("MathJax");
4349  $use_mathjax = $mathJaxSetting->get("enable");
4350  if ($use_mathjax)
4351  {
4352  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
4353  $tpl->addJavaScript($mathJaxSetting->get("path_to_mathjax"));
4354  }
4355 
4356  // this is a fix for bug5362
4357  $cpos = 0;
4358  $o_start = $a_start;
4359  $o_end = $a_end;
4360  $a_start = str_replace("\\", "", $a_start);
4361  $a_end = str_replace("\\", "", $a_end);
4362 
4363  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
4364  {
4365  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
4366  {
4367  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
4368 
4369  // replace, if tags do not go across div borders
4370  if (!is_int(strpos($tex, "</div>")))
4371  {
4372  if (!$use_mathjax)
4373  {
4374  $a_text = substr($a_text, 0, $spos).
4375  "<img alt=\"".htmlentities($tex)."\" src=\"".$cgi."?".
4376  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
4377  " />".
4378  substr($a_text, $epos + strlen($a_end));
4379  }
4380  else
4381  {
4382  $tex = $a_start.$tex.$a_end;
4383 
4384  switch ((int) $mathJaxSetting->get("limiter"))
4385  {
4386  case 1:
4387  $mj_start = "[tex]";
4388  $mj_end = "[/tex]";
4389  break;
4390 
4391  case 2:
4392  $mj_start = '<span class="math">';
4393  $mj_end = '</span>';
4394  break;
4395 
4396  default:
4397  $mj_start = "\(";
4398  $mj_end = "\)";
4399  break;
4400  }
4401 
4402  $replacement =
4403  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
4404  "'".$mj_start."' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '".$mj_end."'", $tex);
4405  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
4406  $a_text = substr($a_text, 0, $spos).
4407  $replacement.
4408  substr($a_text, $epos + strlen($a_end));
4409  }
4410  }
4411  }
4412  $cpos = $spos + 1;
4413  }
4414 
4415  $result_text = $a_text;
4416 
4417  return $result_text;
4418  }
4419 
4429  public static function buildLatexImages($a_text, $a_dir)
4430  {
4431  $result_text = $a_text;
4432 
4433  $start = "\[tex\]";
4434  $end = "\[\/tex\]";
4435 
4436  $cgi = URL_TO_LATEX;
4437 
4438  if ($cgi != "")
4439  {
4440  while (preg_match('/' . $start . '(.*?)' . $end . '/ie', $result_text, $found))
4441  {
4442  $cnt = (int) $GLOBALS["teximgcnt"]++;
4443  // get image from cgi and write it to file
4444  $fpr = @fopen($cgi."?".rawurlencode($found[1]), "r");
4445  $lcnt = 0;
4446  if ($fpr)
4447  {
4448  while(!feof($fpr))
4449  {
4450  $buf = fread($fpr, 1024);
4451  if ($lcnt == 0)
4452  {
4453  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4454  {
4455  $suffix = "gif";
4456  }
4457  else
4458  {
4459  $suffix = "png";
4460  }
4461  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4462  }
4463  $lcnt++;
4464  fwrite($fpw, $buf);
4465  }
4466  fclose($fpw);
4467  fclose($fpr);
4468  }
4469 
4470  // replace tex-tag
4471  $img_str = "./teximg/img".$cnt.".".$suffix;
4472  $result_text = str_replace($found[0],
4473  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4474  }
4475  }
4476 
4477  return $result_text;
4478  }
4479 
4488  public static function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE)
4489  {
4490  $result = $txt_output;
4491  $is_html = self::isHTML($result);
4492 
4493  if ($prepare_for_latex_output)
4494  {
4495  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>");
4496  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]");
4497  }
4498 
4499  // removed: did not work with magic_quotes_gpc = On
4500  if (!$is_html)
4501  {
4502  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4503  $result = preg_replace("/[\n]/", "<br />", $result);
4504  }
4505  else
4506  {
4507  // patch for problems with the <pre> tags in tinyMCE
4508  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4509  {
4510  foreach ($matches[0] as $found)
4511  {
4512  $replacement = "";
4513  if (strpos("\n", $found) === FALSE)
4514  {
4515  $replacement = "\n";
4516  }
4517  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4518  $result = str_replace($found, $removed, $result);
4519  }
4520  }
4521  }
4522  if ($prepare_for_latex_output)
4523  {
4524  // replace special characters to prevent problems with the ILIAS template system
4525  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4526  $result = str_replace("{", "&#123;", $result);
4527  $result = str_replace("}", "&#125;", $result);
4528  $result = str_replace("\\", "&#92;", $result);
4529  }
4530  return $result;
4531  }
4532 
4541  public static function isHTML($a_text)
4542  {
4543  if( preg_match("/<[^>]*?>/", $a_text) )
4544  {
4545  return true;
4546  }
4547 
4548  return false;
4549  }
4550 
4559  public static function int2array ($seconds, $periods = null)
4560  {
4561  // Define time periods
4562  if (!is_array($periods))
4563  {
4564  $periods = array (
4565  'years' => 31536000,
4566  'months' => 2592000,
4567  'days' => 86400,
4568  'hours' => 3600,
4569  'minutes' => 60,
4570  'seconds' => 1
4571  );
4572  }
4573 
4574  // Loop
4575  $seconds = (float) $seconds;
4576  foreach ($periods as $period => $value)
4577  {
4578  $count = floor($seconds / $value);
4579 
4580  if ($count == 0)
4581  {
4582  continue;
4583  }
4584 
4585  $values[$period] = $count;
4586  $seconds = $seconds % $value;
4587  }
4588  // Return
4589  if (empty($values))
4590  {
4591  $values = null;
4592  }
4593 
4594  return $values;
4595  }
4596 
4605  public static function timearray2string ($duration)
4606  {
4607  global $lng;
4608 
4609  if (!is_array($duration))
4610  {
4611  return false;
4612  }
4613 
4614  foreach ($duration as $key => $value) {
4615 
4616  // Plural
4617  if ($value > 1)
4618  {
4619  $segment_name = $key;
4620  $segment_name = $lng->txt($segment_name);
4621  $segment = $value . ' ' . $segment_name;
4622  }
4623  else
4624  {
4625  $segment_name = substr($key, 0, -1);
4626  $segment_name = $lng->txt($segment_name);
4627  $segment = $value . ' ' . $segment_name;
4628  }
4629 
4630  $array[] = $segment;
4631  }
4632  $len = count($array);
4633 
4634  if ($len>3)
4635  {
4636  $array=array_slice($array,0,(3-$len));
4637  }
4638 
4639  $str = implode(', ', $array);
4640 
4641  return $str;
4642  }
4643 
4644  public static function getFileSizeInfo()
4645  {
4646  global $lng;
4647 
4648  // get the value for the maximal uploadable filesize from the php.ini (if available)
4649  $umf=get_cfg_var("upload_max_filesize");
4650  // get the value for the maximal post data from the php.ini (if available)
4651  $pms=get_cfg_var("post_max_size");
4652 
4653  // use the smaller one as limit
4654  $max_filesize=min($umf, $pms);
4655  if (!$max_filesize) $max_filesize=max($umf, $pms);
4656 
4657  return $lng->txt("file_notice")." $max_filesize.";
4658  }
4659 
4668  public static function __extractRefId($role_title)
4669  {
4670 
4671  $test_str = explode('_',$role_title);
4672 
4673  if ($test_str[0] == 'il')
4674  {
4675  $test2 = (int) $test_str[3];
4676  return is_numeric ($test2) ? (int) $test2 : false;
4677  }
4678  return false;
4679  }
4680 
4691  public static function __extractId($ilias_id, $inst_id)
4692  {
4693 
4694  $test_str = explode('_',$ilias_id);
4695 
4696  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4697  {
4698  $test2 = (int) $test_str[3];
4699  return is_numeric ($test2) ? (int) $test2 : false;
4700  }
4701  return false;
4702  }
4703 
4718  public static function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4719  {
4720  global $ilDB;
4721 
4722  if(!$a_ids)
4723  {
4724  return array();
4725  }
4726 
4727  // use database to sort user array
4728  $where = "WHERE ".$a_id_name." IN (";
4729  $where .= implode(",", ilUtil::quoteArray($a_ids));
4730  $where .= ") ";
4731 
4732  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4733  $where.
4734  "ORDER BY ".$a_field;
4735 
4736  $res = $ilDB->query($query);
4737  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4738  {
4739  $ids[] = $row->$a_id_name;
4740  }
4741  return $ids ? $ids : array();
4742  }
4743 
4753  public static function getMySQLTimestamp($a_ts)
4754  {
4755  global $ilDB;
4756 
4757  return $a_ts;
4758  }
4759 
4766  public static function quoteArray($a_array)
4767  {
4768  global $ilDB;
4769 
4770 
4771  if(!is_array($a_array) or !count($a_array))
4772  {
4773  return array("''");
4774  }
4775 
4776  foreach($a_array as $k => $item)
4777  {
4778  $a_array[$k] = $ilDB->quote($item);
4779  }
4780 
4781  return $a_array;
4782  }
4783 
4792  public static function sendInfo($a_info = "",$a_keep = false)
4793  {
4794  global $tpl;
4795  $tpl->setMessage("info", $a_info, $a_keep);
4796  }
4797 
4806  public static function sendFailure($a_info = "",$a_keep = false)
4807  {
4808  global $tpl;
4809  $tpl->setMessage("failure", $a_info, $a_keep);
4810  }
4811 
4818  public static function sendQuestion($a_info = "",$a_keep = false)
4819  {
4820  global $tpl;
4821  $tpl->setMessage("question", $a_info, $a_keep);
4822  }
4823 
4832  public static function sendSuccess($a_info = "",$a_keep = false)
4833  {
4834  global $tpl;
4835  $tpl->setMessage("success", $a_info, $a_keep);
4836  }
4837 
4838  public static function infoPanel($a_keep = true)
4839  {
4840  global $tpl,$ilias,$lng;
4841 
4842  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4843  {
4844  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html",
4845  "Services/Utilities");
4846  $tpl->setCurrentBlock("infopanel");
4847 
4848  if (!empty($_SESSION["infopanel"]["text"]))
4849  {
4850  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4851  ilFrameTargetInfo::_getFrame("MainContent").
4852  "\">";
4853  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4854  $link .= "</a>";
4855  }
4856 
4857  // deactivated
4858  if (!empty($_SESSION["infopanel"]["img"]))
4859  {
4860  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4861  ilFrameTargetInfo::_getFrame("MainContent").
4862  "\">";
4863  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4864  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4865  $link .= "</a></td>";
4866  }
4867 
4868  $tpl->setVariable("INFO_ICONS",$link);
4869  $tpl->parseCurrentBlock();
4870  }
4871 
4872  //if (!$a_keep)
4873  //{
4874  ilSession::clear("infopanel");
4875  //}
4876  }
4877 
4878 
4887  public static function dirsize($directory)
4888  {
4889  $size = 0;
4890  if (!is_dir($directory))
4891  {
4892  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4893  // dirsize of non-existing directory
4894  $size = @filesize($directory);
4895  // END DiskQuota Suppress PHP warning.
4896  return ($size === false) ? -1 : $size;
4897  }
4898  if ($DIR = opendir($directory))
4899  {
4900  while (($dirfile = readdir($DIR)) !== false)
4901  {
4902  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4903  continue;
4904  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4905  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4906  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
4907  {
4908  // BEGIN DiskQuota: dirsize is not a global function anymore
4909  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4910  // END DiskQuota: dirsize is not a global function anymore
4911  if ($dirSize >= 0)
4912  $size += $dirSize;
4913  else return -1;
4914  }
4915  }
4916  closedir($DIR);
4917  }
4918  return $size;
4919  }
4920 
4921  public static function randomhash()
4922  {
4923  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
4924  }
4925 
4926  public static function setCookie($a_cookie_name,$a_cookie_value = '', $a_also_set_super_global = true, $a_set_cookie_invalid = false)
4927  {
4928  /*
4929  if(!(bool)$a_set_cookie_invalid) $expire = IL_COOKIE_EXPIRE;
4930  else $expire = time() - (365*24*60*60);
4931  */
4932  // Temporary fix for feed.php
4933  if(!(bool)$a_set_cookie_invalid) $expire = 0;
4934  else $expire = time() - (365*24*60*60);
4935 
4936  // setcookie() supports 5th parameter
4937  // only for php version 5.2.0 and above
4938  if( version_compare(PHP_VERSION, '5.2.0', '>=') )
4939  {
4940  // PHP version >= 5.2.0
4941  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4942  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE, IL_COOKIE_HTTPONLY
4943  );
4944  }
4945  else
4946  {
4947  // PHP version < 5.2.0
4948  setcookie( $a_cookie_name, $a_cookie_value, $expire,
4949  IL_COOKIE_PATH, IL_COOKIE_DOMAIN, IL_COOKIE_SECURE
4950  );
4951  }
4952 
4953  if((bool)$a_also_set_super_global) $_COOKIE[$a_cookie_name] = $a_cookie_value;
4954  }
4955 
4956  public static function _sanitizeFilemame($a_filename)
4957  {
4958  return strip_tags(self::stripSlashes($a_filename));
4959  }
4960 
4961  public static function _getHttpPath()
4962  {
4963  global $ilIliasIniFile;
4964 
4965  if($_SERVER['SHELL'] || php_sapi_name() == 'cli' ||
4966  // fallback for windows systems, useful in crons
4967  (class_exists("ilContext") && !ilContext::usesHTTP()))
4968  {
4969  return $ilIliasIniFile->readVariable('server', 'http_path');
4970  }
4971  else
4972  {
4973  return ILIAS_HTTP_PATH;
4974  }
4975  }
4976 
4985  public static function printBacktrace()
4986  {
4987  $bt = debug_backtrace();
4988  foreach ($bt as $t)
4989  {
4990  echo "<br>".$t["file"].", ".$t["function"]." [".$t["line"]."]";
4991  }
4992  }
4993 
5008  public static function parseImportId($a_import_id)
5009  {
5010  $exploded = explode('_'.$a_import_id);
5011 
5012  $parsed['orig'] = $a_import_id;
5013  if($exploded[0] == 'il')
5014  {
5015  $parsed['prefix'] = $exploded[0];
5016  }
5017  if(is_numeric($exploded[1]))
5018  {
5019  $parsed['inst_id'] = (int) $exploded[1];
5020  }
5021  $parsed['type'] = $exploded[2];
5022 
5023  if(is_numeric($exploded[3]))
5024  {
5025  $parsed['id'] = (int) $exploded[3];
5026  }
5027  return $parsed;
5028  }
5029 
5036  public static function unserializeSession($data)
5037  {
5038  $vars = preg_split(
5039  '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
5040  $data,
5041  -1,
5042  PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
5043  );
5044 
5045  $result = array();
5046 
5047  for($i = 0; $vars[$i]; $i++)
5048  {
5049  $result[$vars[$i++]] = unserialize($vars[$i]);
5050  }
5051 
5052  return $result;
5053  }
5054 } // END class.ilUtil
5055 
5056 
5057 ?>