ILIAS  Release_3_10_x_branch Revision 61812
 All Data Structures Namespaces Files Functions Variables Groups Pages
class.ilUtil.php
Go to the documentation of this file.
1 <?php
2 /*
3 +-----------------------------------------------------------------------------+
4 | ILIAS open source |
5 +-----------------------------------------------------------------------------+
6 | Copyright (c) 1998-2006 ILIAS open source, University of Cologne |
7 | |
8 | This program is free software; you can redistribute it and/or |
9 | modify it under the terms of the GNU General Public License |
10 | as published by the Free Software Foundation; either version 2 |
11 | of the License, or (at your option) any later version. |
12 | |
13 | This program is distributed in the hope that it will be useful, |
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
16 | GNU General Public License for more details. |
17 | |
18 | You should have received a copy of the GNU General Public License |
19 | along with this program; if not, write to the Free Software |
20 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
21 +-----------------------------------------------------------------------------+
22 */
23 
37 class ilUtil
38 {
46  function getImageTagByType($a_type, $a_path, $a_big = false)
47  {
48  global $lng;
49 
50  if ($a_big)
51  {
52  $big = "_b";
53  }
54  $filename = "icon_".$a_type."$big.gif";
55 
56  return "<img src=\"".ilUtil::getImagePath($filename)."\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
57  //return "<img src=\"".$a_path."/images/"."icon_".$a_type."$big.gif\" alt=\"".$lng->txt("obj_".$a_type)."\" title=\"".$lng->txt("obj_".$a_type)."\" border=\"0\" vspace=\"0\"/>";
58  }
59 
71  public function getTypeIconPath($a_type,$a_obj_id,$a_size = 'small')
72  {
73  global $ilSetting;
74 
75  if($ilSetting->get("custom_icons"))
76  {
77  switch($a_type)
78  {
79  case 'cat':
80  case 'crs':
81  case 'grp':
82  include_once('./Services/Container/classes/class.ilContainer.php');
83  if(strlen($path = ilContainer::_lookupIconPath($a_obj_id,$a_size)))
84  {
85  return $path;
86  }
87  }
88  }
89 
90  switch($a_size)
91  {
92  case 'tiny':
93  $postfix = '_s.gif';
94  break;
95  case 'big':
96  $postfix = '_b.gif';
97  break;
98  default:
99  $postfix = '.gif';
100  break;
101  }
102  return ilUtil::getImagePath('icon_'.$a_type.$postfix);
103  }
104 
113  function getImagePath($img, $module_path = "", $mode = "output", $offline = false)
114  {
115  global $ilias, $styleDefinition, $ilCtrl;
116 
117  if ($module_path != "")
118  {
119  $module_path = "/".$module_path;
120  }
121 
122  // default image
123  $default_img = ".".$module_path."/templates/default/images/".$img;
124 
125  if (is_object($styleDefinition))
126  {
127  $image_dir = $styleDefinition->getImageDirectory($ilias->account->prefs["style"]);
128  }
129  if ($ilUser->skin == "default")
130  {
131  $user_img = ".".$module_path."/templates/default/".$image_dir."/".$img;
132  $skin_img = ".".$module_path."/templates/default/images/".$img;
133  }
134  else if (is_object($styleDefinition) && $ilUser->skin != "default")
135  {
136  $user_img = "./Customizing/global/skin/".
137  $ilias->account->skin.$module_path."/".$image_dir."/".$img;
138  $skin_img = "./Customizing/global/skin/".
139  $ilias->account->skin.$module_path."/images/".$img;
140  }
141 
142  if ($offline)
143  {
144  return "./images/".$img;
145  }
146  else if (@file_exists($user_img) && $image_dir != "")
147  {
148  return $user_img; // found image for skin and style
149  }
150  else if (file_exists($skin_img))
151  {
152  return $skin_img; // found image in skin/images
153  }
154 
155  return $default_img; // take image in default
156  }
157 
166  function getHtmlPath($relative_path)
167  {
168  if (substr($relative_path, 0, 2) == './')
169  {
170  $relative_path = (substr($relative_path, 1));
171  }
172  if (substr($relative_path, 0, 1) != '/')
173  {
174  $relative_path = '/' . $relative_path;
175  }
176  $htmlpath = ILIAS_HTTP_PATH . $relative_path;
177  return $htmlpath;
178  }
179 
190  function getStyleSheetLocation($mode = "output", $a_css_name = "", $a_css_location = "")
191  {
192  global $ilias;
193 
194  // add version as parameter to force reload for new releases
195  $stylesheet_name = (strlen($a_css_name)) ? $a_css_name : $ilias->account->prefs["style"].".css";
196  if (strlen($a_css_location) && (strcmp(substr($a_css_location, -1), "/") != 0)) $a_css_location = $a_css_location . "/";
197 
198  $filename = "";
199  if ($ilias->account->skin != "default")
200  {
201  $filename = "./Customizing/global/skin/".$ilias->account->skin."/".$a_css_location.$stylesheet_name;
202  }
203  if (strlen($filename) == 0 || !file_exists($filename))
204  {
205  $filename = "./" . $a_css_location . "templates/default/".$stylesheet_name;
206  }
207  $vers = "";
208  if ($mode != "filesystem")
209  {
210  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
211  $vers = "?vers=".str_replace(".", "-", $vers);
212  }
213  return $filename . $vers;
214  }
215 
224  function getJSLocation($a_js_name, $a_js_location = "", $add_version = FALSE)
225  {
226  global $ilias;
227 
228  // add version as parameter to force reload for new releases
229  $js_name = $a_js_name;
230  if (strlen($a_js_location) && (strcmp(substr($a_js_location, -1), "/") != 0)) $a_js_location = $a_js_location . "/";
231 
232  $filename = "";
233  if ($ilias->account->skin != "default")
234  {
235  $filename = "./Customizing/global/skin/".$ilias->account->skin."/".$a_js_location.$js_name;
236  }
237  if (strlen($filename) == 0 || !file_exists($filename))
238  {
239  $filename = "./" . $a_js_location . "templates/default/".$js_name;
240  }
241  $vers = "";
242  if ($add_version)
243  {
244  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
245  $vers = "?vers=".str_replace(".", "-", $vers);
246  }
247  return $filename . $vers;
248  }
249 
255  function getP3PLocation()
256  {
257  global $ilias;
258 
259  if (defined("ILIAS_MODULE"))
260  {
261  $base = '';
262  for($i = 0;$i < count(explode('/',ILIAS_MODULE));$i++)
263  {
264  $base .= "../Services/Privacy/";
265  }
266  }
267  else
268  {
269  $base = "./Services/Privacy/";
270  }
271 
272  if (is_file($base."w3c/p3p.xml"))
273  {
274  return ILIAS_HTTP_PATH."w3c/p3p.xml";
275  }
276  else
277  {
278  return ILIAS_HTTP_PATH."/w3c/p3p_template.xml";
279  }
280  }
281 
287  function getNewContentStyleSheetLocation($mode = "output")
288  {
289  global $ilias;
290 
291  // add version as parameter to force reload for new releases
292  if ($mode != "filesystem")
293  {
294  $vers = str_replace(" ", "-", $ilias->getSetting("ilias_version"));
295  $vers = "?vers=".str_replace(".", "-", $vers);
296  }
297 
298  if ($ilias->account->skin == "default")
299  {
300  $in_style = "./templates/".$ilias->account->skin."/".$ilias->account->prefs["style"]."_cont.css";
301  }
302  else
303  {
304  $in_style = "./Customizing/global/skin/".$ilias->account->skin."/".$ilias->account->prefs["style"]."_cont.css";
305  }
306 
307  if (is_file("./".$in_style))
308  {
309  return $base.$in_style.$vers;
310  }
311  else
312  {
313  return $base."templates/default/delos_cont.css".$vers;
314  }
315  }
316 
333  function formSelect($selected,$varname,$options,$multiple = false,$direct_text = false, $size = "0",
334  $style_class = "", $attribs = "",$disabled = false)
335  {
336  global $lng;
337 
338  if ($multiple == true)
339  {
340  $multiple = " multiple=\"multiple\"";
341  }
342  else
343  {
344  $multiple = "";
345  $size = 0;
346  }
347 
348  if ($style_class != "")
349  {
350  $class = " class=\"".$style_class."\"";
351  }
352  else
353  {
354  $class = "";
355  }
356 
357  if (is_array($attribs))
358  {
359  foreach ($attribs as $key => $val)
360  {
361  $attributes .= " ".$key."=\"".$val."\"";
362  }
363  }
364  if($disabled)
365  {
366  $disabled = ' disabled=\"disabled\"';
367  }
368 
369  $str = "<select name=\"".$varname ."\"".$multiple." $class size=\"".$size."\" $attributes $disabled>\n";
370 
371  foreach ($options as $key => $val)
372  {
373  if ($direct_text)
374  {
375  $str .= " <option value=\"".$key."\"";
376  }
377  else
378  {
379  $str .= " <option value=\"".$val."\"";
380  }
381  if (is_array($selected) )
382  {
383  if (in_array($key,$selected))
384  {
385  $str .= " selected=\"selected\"";
386  }
387  }
388  else if ($selected == $key)
389  {
390  $str .= " selected=\"selected\"";
391  }
392 
393  if ($direct_text)
394  {
395  $str .= ">".$val."</option>\n";
396  }
397  else
398  {
399  $str .= ">".$lng->txt($val)."</option>\n";
400  }
401  }
402 
403  $str .= "</select>\n";
404 
405  return $str;
406  }
407 
415  function getSelectName ($selected,$values)
416  {
417  return($values[$selected]);
418  }
419 
429  function formCheckbox ($checked,$varname,$value,$disabled = false)
430  {
431  $str = "<input type=\"checkbox\" name=\"".$varname."\"";
432 
433  if ($checked == 1)
434  {
435  $str .= " checked=\"checked\"";
436  }
437 
438  if ($disabled)
439  {
440  $str .= " disabled=\"disabled\"";
441  }
442 
443  $array_var = false;
444 
445  if (substr($varname,-2) == "[]")
446  {
447  $array_var = true;
448  }
449 
450  // if varname ends with [], use varname[-2] + _ + value as id tag (e.g. "user_id[]" => "user_id_15")
451  if ($array_var)
452  {
453  $varname_id = substr($varname,0,-2)."_".$value;
454  }
455  else
456  {
457  $varname_id = $varname;
458  }
459 
460  // dirty removal of other "[]" in string
461  $varname_id = ereg_replace("\[","_",$varname_id);
462  $varname_id = ereg_replace("\]","",$varname_id);
463 
464  $str .= " value=\"".$value."\" id=\"".$varname_id."\" />\n";
465 
466  return $str;
467  }
468 
478  function formDisabledRadioButton($checked,$varname,$value,$disabled)
479  {
480  if ($disabled) {
481  $str = "<input disabled type=\"radio\" name=\"".$varname."\"";
482  }
483  else {
484  $str = "<input type=\"radio\" name=\"".$varname."\"";
485  }
486  if ($checked == 1)
487  {
488  $str .= " checked=\"checked\"";
489  }
490 
491  $str .= " value=\"".$value."\"";
492  $str .= " id=\"".$value."\" />\n";
493 
494  return $str;
495 
496  }
497 
498 
507  function formRadioButton($checked,$varname,$value)
508  {
509  $str = "<input type=\"radio\" name=\"".$varname."\"";
510  if ($checked == 1)
511  {
512  $str .= " checked=\"checked\"";
513  }
514 
515  $str .= " value=\"".$value."\"";
516 
517  $str .= " id=\"".$value."\" />\n";
518 
519  return $str;
520  }
521 
522 
531  function formInput($varname,$value,$disabled = false)
532  {
533 
534  $str = "<input type=\"input\" name=\"".$varname."\"";
535  if ($disabled)
536  {
537  $str .= " disabled";
538  }
539 
540  $str .= " value=\"".$value."\"";
541 
542  $str .= " id=\"".$value."\" />\n";
543 
544  return $str;
545  }
546 
547 
552  function checkInput ($vars)
553  {
554  // TO DO:
555  // Diese Funktion soll Formfeldeingaben berprfen (empty und required)
556  }
557 
563  function setPathStr ($a_path)
564  {
565  if ("" != $a_path && "/" != substr($a_path, -1))
566  {
567  $a_path .= "/";
568  //$a_path = substr($a_path,1);
569  }
570 
571  //return getcwd().$a_path;
572  return $a_path;
573  }
574 
585  function switchColor ($a_num,$a_css1,$a_css2)
586  {
587  if (!($a_num % 2))
588  {
589  return $a_css1;
590  }
591  else
592  {
593  return $a_css2;
594  }
595  }
596 
606  function showTabs($a_hl, $a_o)
607  {
608  global $lng;
609 
610  $tpltab = new ilTemplate("tpl.tabs.html", true, true);
611 
612  for ($i=1; $i<=4; $i++)
613  {
614  $tpltab->setCurrentBlock("tab");
615  if ($a_hl == $i)
616  {
617  $tabtype = "tabactive";
618  $tab = $tabtype;
619  }
620  else
621  {
622  $tabtype = "tabinactive";
623  $tab = "tab";
624  }
625 
626  switch ($i)
627  {
628  case 1:
629  $txt = $lng->txt("view_content");
630  break;
631  case 2:
632  $txt = $lng->txt("edit_properties");
633  break;
634  case 3:
635  $txt = $lng->txt("perm_settings");
636  break;
637  case 4:
638  $txt = $lng->txt("show_owner");
639  break;
640  } // switch
641  $tpltab->setVariable("CONTENT", $txt);
642  $tpltab->setVariable("TABTYPE", $tabtype);
643  $tpltab->setVariable("TAB", $tab);
644  $tpltab->setVariable("LINK", $a_o["LINK".$i]);
645  $tpltab->parseCurrentBlock();
646  }
647 
648  return $tpltab->get();
649  }
650 
651 
652 
659  function checkFormEmpty ($emptyFields)
660  {
661 
662  $feedback = "";
663 
664  foreach ($emptyFields as $key => $val)
665  {
666  if ($val == "") {
667  if ($feedback != "") $feedback .= ", ";
668  $feedback .= $key;
669  }
670  }
671 
672  return $feedback;
673  }
674 
697  function Linkbar ($AScript,$AHits,$ALimit,$AOffset,$AParams = array(),$ALayout = array(), $prefix = '')
698  {
699  $LinkBar = "";
700 
701  $layout_link = "";
702  $layout_prev = "&lt;&lt;";
703  $layout_next = "&gt;&gt;";
704 
705  // layout options
706  if (count($ALayout > 0))
707  {
708  if ($ALayout["link"])
709  {
710  $layout_link = " class=\"".$ALayout["link"]."\"";
711  }
712 
713  if ($ALayout["prev"])
714  {
715  $layout_prev = $ALayout["prev"];
716  }
717 
718  if ($ALayout["next"])
719  {
720  $layout_next = $ALayout["next"];
721  }
722  }
723 
724  // show links, if hits greater limit
725  // or offset > 0 (can be > 0 due to former setting)
726  if ($AHits > $ALimit || $AOffset > 0)
727  {
728  if (!empty($AParams))
729  {
730  foreach ($AParams as $key => $value)
731  {
732  $params.= $key."=".$value."&";
733  }
734  }
735  // if ($params) $params = substr($params,0,-1);
736  if(strpos($AScript,'&'))
737  {
738  $link = $AScript."&".$params.$prefix."offset=";
739  }
740  else
741  {
742  $link = $AScript."?".$params.$prefix."offset=";
743  }
744 
745  // ?bergehe "zurck"-link, wenn offset 0 ist.
746  if ($AOffset >= 1)
747  {
748  $prevoffset = $AOffset - $ALimit;
749  if ($prevoffset < 0) $prevoffset = 0;
750  $LinkBar .= "<a".$layout_link." href=\"".$link.$prevoffset."\">".$layout_prev."&nbsp;</a>";
751  }
752 
753  // Ben?tigte Seitenzahl kalkulieren
754  $pages=intval($AHits/$ALimit);
755 
756  // Wenn ein Rest bleibt, addiere eine Seite
757  if (($AHits % $ALimit))
758  $pages++;
759 
760  // Bei Offset = 0 keine Seitenzahlen anzeigen : DEAKTIVIERT
761  // if ($AOffset != 0) {
762 
763  // ansonsten zeige Links zu den anderen Seiten an
764  for ($i = 1 ;$i <= $pages ; $i++)
765  {
766  $newoffset=$ALimit*($i-1);
767 
768  if ($newoffset == $AOffset)
769  {
770  $LinkBar .= "[".$i."] ";
771  }
772  else
773  {
774  $LinkBar .= '<a '.$layout_link.' href="'.
775  $link.$newoffset.'">['.$i.']</a> ';
776  }
777  }
778  // }
779 
780  // Checken, ob letze Seite erreicht ist
781  // Wenn nicht, gebe einen "Weiter"-Link aus
782  if (! ( ($AOffset/$ALimit)==($pages-1) ) && ($pages!=1) )
783  {
784  $newoffset=$AOffset+$ALimit;
785  $LinkBar .= "<a".$layout_link." href=\"".$link.$newoffset."\">&nbsp;".$layout_next."</a>";
786  }
787 
788  return $LinkBar;
789  }
790  else
791  {
792  return false;
793  }
794  }
795 
805  function makeClickable($a_text, $detectGotoLinks = false)
806  {
807  // New code, uses MediaWiki Sanitizer
808  $ret = $a_text;
809 
810  // www-URL ohne ://-Angabe
811  $ret = eregi_replace("(^|[[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
812  "\\1http://\\2\\3", $ret);
813 
814  // ftp-URL ohne ://-Angabe
815  $ret = eregi_replace("(^|[[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
816  "\\1ftp://\\2\\3", $ret);
817 
818  // E-Mail (this does not work as expected, users must add mailto: manually)
819  //$ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
820  // "mailto:\\1", $ret);
821 
822  include_once("./Services/Utilities/classes/class.ilMWParserAdapter.php");
823  $parser = new ilMWParserAdapter();
824  $ret = $parser->replaceFreeExternalLinks($ret);
825 
826  //
827  // Old Behaviour is unsafe, Thanks to L4teral
828  //
829  /*
830  // URL mit ://-Angabe
831  $ret = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=-])",
832  "<a href=\"\\1://\\2\\3\" target=\"_blank\">\\1://\\2\\3</a>", $a_text);
833 
834  // www-URL ohne ://-Angabe
835  $ret = eregi_replace("([[:space:]]+)(www\.)([[:alnum:]#?/&=\.-]+)",
836  "\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>", $ret);
837 
838  // ftp-URL ohne ://-Angabe
839  $ret = eregi_replace("([[:space:]]+)(ftp\.)([[:alnum:]#?/&=\.-]+)",
840  "\\1<a href=\"ftp://\\2\\3\" target=\"_blank\">\\2\\3</a>", $ret);
841 
842  // E-Mail
843  $ret = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
844  "<a href=\"mailto:\\1\">\\1</a>", $ret);
845  }
846  */
847 
848  // Should be Safe
849 
850  if ($detectGotoLinks)
851  // replace target blank with self and text with object title.
852  {
853  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto.php\?target=\w+_(\d+)[^\"]*)\"[^>]*>[^<]*<\/a>";
854 // echo htmlentities($regExp);
855  $ret = preg_replace_callback(
856  "/".$regExp."/i",
857  array("ilUtil", "replaceLinkProperties"),
858  $ret);
859 
860  // Static links
861  $regExp = "<a[^>]*href=\"(".str_replace("/","\/",ILIAS_HTTP_PATH)."\/goto_.*[a-z0-9]+_([0-9]+)\.html)\"[^>]*>[^<]*<\/a>";
862 // echo htmlentities($regExp);
863  $ret = preg_replace_callback(
864  "/".$regExp."/i",
865  array("ilUtil", "replaceLinkProperties"),
866  $ret);
867  }
868 
869  return($ret);
870  }
871 
883  function replaceLinkProperties ($matches)
884  {
885  $link = $matches[0];
886  $ref_id = $matches[2];
887 
888  if ($ref_id > 0)
889  {
890  $obj_id = ilObject::_lookupObjId($ref_id);
891  if ($obj_id > 0)
892  {
893  $title = ilObject::_lookupTitle($obj_id);
894  $link = "<a href=".$matches[1]." target=\"_self\">".$title."</a>";
895  }
896  }
897  return $link;
898  }
899 
916  function StopWatch($begin = -1)
917  {
918  $m = explode(" ",microtime());
919  $m = $m[0] + $m[1];
920 
921  if ($begin != -1)
922  {
923  $m = $m - $begin;
924  }
925 
926  return($m);
927  }
928 
945  function makeDateSelect($prefix, $year = "", $month = "", $day = "", $startyear = "",$a_long_month = true,$a_further_options = array())
946  {
947  global $lng;
948 
949  $disabled = '';
950  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
951  {
952  $disabled = 'disabled="disabled" ';
953  }
954 
955  $now = getdate();
956  if (!strlen($year)) $year = $now["year"];
957  if (!strlen($month)) $month = $now["mon"];
958  if (!strlen($day)) $day = $now["mday"];
959 
960  $year = (int) $year;
961  $month = (int) $month;
962  $day = (int) $day;
963 
964  // build day select
965  $sel_day .= "<select ".$disabled."name=\"".$prefix."[d]\" id=\"".$prefix."_d\">\n";
966 
967  for ($i = 1; $i <= 31; $i++)
968  {
969  $sel_day .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
970  }
971  $sel_day .= "</select>\n";
972  $sel_day = preg_replace("/(value\=\"$day\")/", "$1 selected=\"selected\"", $sel_day);
973 
974  // build month select
975  $sel_month .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
976 
977  for ($i = 1; $i <= 12; $i++)
978  {
979  if($a_long_month)
980  {
981  $sel_month .= "<option value=\"$i\">" . $lng->txt("month_" . sprintf("%02d", $i) . "_long") . "</option>\n";
982  }
983  else
984  {
985  $sel_month .= "<option value=\"$i\">" . $i . "</option>\n";
986  }
987  }
988  $sel_month .= "</select>\n";
989  $sel_month = preg_replace("/(value\=\"$month\")/", "$1 selected=\"selected\"", $sel_month);
990 
991  // build year select
992  $sel_year .= "<select ".$disabled."name=\"".$prefix."[y]\" id=\"".$prefix."_y\">\n";
993  if ((strlen($startyear) == 0) || ($startyear > $year))
994  {
995  $startyear = $year - 5;
996  }
997 
998  if(($year + 5) < (date('Y',time()) + 5))
999  {
1000  $end_year = date('Y',time()) + 5;
1001  }
1002  else
1003  {
1004  $end_year = $year + 5;
1005  }
1006 
1007  for ($i = $startyear; $i <= $end_year; $i++)
1008  {
1009  $sel_year .= "<option value=\"$i\">" . sprintf("%04d", $i) . "</option>\n";
1010  }
1011  $sel_year .= "</select>\n";
1012  $sel_year = preg_replace("/(value\=\"$year\")/", "$1 selected=\"selected\"", $sel_year);
1013 
1014  //$dateformat = $lng->text["lang_dateformat"];
1015  $dateformat = "d-m-Y";
1016  $dateformat = strtolower(preg_replace("/\W/", "", $dateformat));
1017  $dateformat = strtolower(preg_replace("/(\w)/", "%%$1", $dateformat));
1018  $dateformat = preg_replace("/%%d/", $sel_day, $dateformat);
1019  $dateformat = preg_replace("/%%m/", $sel_month, $dateformat);
1020  $dateformat = preg_replace("/%%y/", $sel_year, $dateformat);
1021  return $dateformat;
1022  }
1023 
1040  function makeTimeSelect($prefix, $short = true, $hour = "", $minute = "", $second = "",$a_use_default = true,$a_further_options = array())
1041  {
1042  global $lng;
1043 
1044  $minute_steps = 1;
1045  $disabled = '';
1046  if(count($a_further_options))
1047  {
1048  if(isset($a_further_options['minute_steps']))
1049  {
1050  $minute_steps = $a_further_options['minute_steps'];
1051  }
1052  if(isset($a_further_options['disabled']) and $a_further_options['disabled'])
1053  {
1054  $disabled = 'disabled="disabled" ';
1055  }
1056  }
1057 
1058  if ($a_use_default and !strlen("$hour$minute$second")) {
1059  $now = localtime();
1060  $hour = $now[2];
1061  $minute = $now[1];
1062  $second = $now[0];
1063  } else {
1064  $hour = (int)$hour;
1065  $minute = (int)$minute;
1066  $second = (int)$second;
1067  }
1068  // build hour select
1069  $sel_hour .= "<select ".$disabled."name=\"".$prefix."[h]\" id=\"".$prefix."_h\">\n";
1070 
1071  for ($i = 0; $i <= 23; $i++)
1072  {
1073  $sel_hour .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1074  }
1075  $sel_hour .= "</select>\n";
1076  $sel_hour = preg_replace("/(value\=\"$hour\")/", "$1 selected=\"selected\"", $sel_hour);
1077 
1078  // build minutes select
1079  $sel_minute .= "<select ".$disabled."name=\"".$prefix."[m]\" id=\"".$prefix."_m\">\n";
1080 
1081  for ($i = 0; $i <= 59; $i = $i + $minute_steps)
1082  {
1083  $sel_minute .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1084  }
1085  $sel_minute .= "</select>\n";
1086  $sel_minute = preg_replace("/(value\=\"$minute\")/", "$1 selected=\"selected\"", $sel_minute);
1087 
1088  if (!$short) {
1089  // build seconds select
1090  $sel_second .= "<select ".$disabled."name=\"".$prefix."[s]\" id=\"".$prefix."_s\">\n";
1091 
1092  for ($i = 0; $i <= 59; $i++)
1093  {
1094  $sel_second .= "<option value=\"$i\">" . sprintf("%02d", $i) . "</option>\n";
1095  }
1096  $sel_second .= "</select>\n";
1097  $sel_second = preg_replace("/(value\=\"$second\")/", "$1 selected=\"selected\"", $sel_second);
1098  }
1099  $timeformat = $lng->text["lang_timeformat"];
1100  if (strlen($timeformat) == 0) $timeformat = "H:i:s";
1101  $timeformat = strtolower(preg_replace("/\W/", "", $timeformat));
1102  $timeformat = preg_replace("/(\w)/", "%%$1", $timeformat);
1103  $timeformat = preg_replace("/%%h/", $sel_hour, $timeformat);
1104  $timeformat = preg_replace("/%%i/", $sel_minute, $timeformat);
1105  if ($short) {
1106  $timeformat = preg_replace("/%%s/", "", $timeformat);
1107  } else {
1108  $timeformat = preg_replace("/%%s/", $sel_second, $timeformat);
1109  }
1110  return $timeformat;
1111  }
1112 
1113  /*
1114  * This preg-based function checks whether an e-mail address is formally valid.
1115  * It works with all top level domains including the new ones (.biz, .info, .museum etc.)
1116  * and the special ones (.arpa, .int etc.)
1117  * as well as with e-mail addresses based on IPs (e.g. webmaster@123.45.123.45)
1118  * Valid top level domains: http://data.iana.org/TLD/tlds-alpha-by-domain.txt
1119  * @author Unknown <mail@philipp-louis.de> (source: http://www.php.net/preg_match)
1120  * @access public
1121  * @param string email address
1122  * @return boolean true if valid
1123  */
1124  function is_email($a_email)
1125  {
1126  // BEGIN Mail: If possible, use PearMail to validate e-mail address
1127  global $ilErr, $ilias;
1128 
1129  // Note the use of @include_once here. We need this, because
1130  // inclusion fails when the function is_email is called from setup.php.
1131  $successfulInclude = @include_once ('Services/Mail/classes/class.ilMail.php');
1132 
1133  // additional checks for include and ilias object are needed,
1134  // otherwise setup will fail with this if branch
1135  if ($successfulInclude && is_object($ilias) && ilMail::_usePearMail())
1136  {
1137  require_once 'Mail/RFC822.php';
1138  $parser = &new Mail_RFC822();
1139  PEAR::setErrorHandling(PEAR_ERROR_EXCEPTION);
1140  try {
1141  $addresses = $parser->parseAddressList($a_email, 'ilias', false, true);
1142  if (! is_a($addresses, 'PEAR_Error') &&
1143  count($addresses) == 1 && $addresses[0]->host != 'ilias')
1144  {
1145  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1146  return true;
1147  }
1148  } catch (Exception $e) {
1149  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1150  return false;
1151  }
1152  PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr, "errorHandler"));
1153  return false;
1154  }
1155  else
1156  {
1157  $tlds = strtolower(
1158  "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|".
1159  "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|".
1160  "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|".
1161  "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|".
1162  "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|".
1163  "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|".
1164  "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|".
1165  "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|".
1166  "WF|WS|XN|YE|YT|YU|ZA|ZM|ZW");
1167 
1168  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));
1169  }
1170  // END Mail: If possible, use PearMail to validate e-mail address
1171  }
1172 
1173  /*
1174  * validates a password
1175  * @access public
1176  * @param string password
1177  * @return boolean true if valid
1178  */
1179  function isPassword($a_passwd,&$custom_error = null)
1180  {
1181  global $lng;
1182  $a_custom_error = '';
1183 
1184 
1185  include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php');
1186  $security = ilSecuritySettings::_getInstance();
1187 
1188  // differentiate the account security mode (ilias standard/customized)
1189  if( $security->getAccountSecurityMode() == ilSecuritySettings::ACCOUNT_SECURITY_MODE_CUSTOMIZED )
1190  {
1191  // check if passwd not empty
1192  if( $a_passwd == '' )
1193  {
1194  $custom_error = $lng->txt('password_empty');
1195  return false;
1196  }
1197  // check if passwd not to short
1198  if( $security->getPasswordMinLength() > 0 &&
1199  strlen($a_passwd) < $security->getPasswordMinLength() )
1200  {
1201  $custom_error = sprintf( $lng->txt('password_to_short'), $security->getPasswordMinLength() );
1202  return false;
1203  }
1204  // check if passwd not to long
1205  elseif( $security->getPasswordMaxLength() > 0 &&
1206  strlen($a_passwd) > $security->getPasswordMaxLength() )
1207  {
1208  $custom_error = sprintf( $lng->txt('password_to_long'), $security->getPasswordMaxLength() );
1209  return false;
1210  }
1211  else
1212  {
1213  // if passwd must contains Chars and Numbers
1214  if( $security->isPasswordCharsAndNumbersEnabled() )
1215  {
1216  $reg = '/[A-Za-z]+/';
1217  if( !preg_match($reg,$a_passwd) )
1218  {
1219  $custom_error = $lng->txt('password_must_chars_and_numbers');
1220  return false;
1221  }
1222 
1223  $reg = '/[0-9]+/';
1224  if( !preg_match($reg,$a_passwd) )
1225  {
1226  $custom_error = $lng->txt('password_must_chars_and_numbers');
1227  return false;
1228  }
1229 
1230  }
1231  // if passwd must contains Special-Chars
1232  if( $security->isPasswordSpecialCharsEnabled() )
1233  {
1234  $reg = '/[_\.\+\?\#\-\*\@!\$\%\~]+/';
1235  if( !preg_match($reg,$a_passwd) )
1236  {
1237  $custom_error = $lng->txt('password_must_special_chars');
1238  return false;
1239  }
1240  }
1241  }
1242  }
1243  else
1244  {
1245  if (empty($a_passwd))
1246  {
1247  return false;
1248  }
1249  if (strlen($a_passwd) < 6)
1250  {
1251  return false;
1252  }
1253  // due to bug in php does not work
1254  //if (!ereg("^[A-Za-z0-9_\.\+\-\*\@!\$\%\~]+$", $a_passwd))
1255 
1256  if (!preg_match("/^[A-Za-z0-9_\.\+\?\#\-\*\@!\$\%\~]+$/", $a_passwd))
1257  {
1258  return false;
1259  }
1260  }
1261 
1262  return true;
1263  }
1264 
1265  /*
1266  * validates a login
1267  * @access public
1268  * @param string login
1269  * @return boolean true if valid
1270  */
1271  function isLogin($a_login)
1272  {
1273  if (empty($a_login))
1274  {
1275  return false;
1276  }
1277 
1278  if (strlen($a_login) < 3)
1279  {
1280  return false;
1281  }
1282 
1283  // FIXME - If ILIAS is configured to use RFC 822
1284  // compliant mail addresses we should not
1285  // allow the @ character.
1286  if (!ereg("^[A-Za-z0-9_\.\+\*\@!\$\%\~\-]+$", $a_login))
1287  {
1288  return false;
1289  }
1290 
1291  return true;
1292  }
1293 
1305  function shortenText ($a_str, $a_len, $a_dots = false, $a_next_blank = false)
1306  {
1307  include_once("./Services/Utilities/classes/class.ilStr.php");
1308  if (ilStr::strLen($a_str) > $a_len)
1309  {
1310  if ($a_next_blank)
1311  {
1312  $len = ilStr::strPos($a_str, " ", $a_len);
1313  }
1314  else
1315  {
1316  $len = $a_len;
1317  }
1318  // BEGIN WebDAV
1319  // - Shorten names in the middle, before the filename extension
1320  // Workaround for Windows WebDAV Client:
1321  // Use the unicode ellipsis symbol for shortening instead of
1322  // three full stop characters.
1323  $p = strrpos($a_str, '.');
1324  if ($p === false || $p == 0 || strlen($a_str) - $p > $a_len)
1325  {
1326  $a_str = ilStr::subStr($a_str,0,$len);
1327  if ($a_dots)
1328  {
1329  $a_str .= "\xe2\x80\xa6"; // UTF-8 encoding for Unicode ellipsis character.
1330  }
1331  }
1332  else
1333  {
1334  if ($a_dots)
1335  {
1336  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1))."\xe2\x80\xa6".substr($a_str, $p);
1337  }
1338  else
1339  {
1340  $a_str = ilStr::subStr($a_str,0,$len - (strlen($a_str) - $p + 1)).substr($a_str, $p);
1341  }
1342  }
1343  }
1344 
1345  return $a_str;
1346  }
1347 
1356  function shortenWords($a_str, $a_len = 30, $a_dots = true)
1357  {
1358  include_once("./Services/Utilities/classes/class.ilStr.php");
1359  $str_arr = explode(" ", $a_str);
1360 
1361  for ($i = 0; $i < count($str_arr); $i++)
1362  {
1363  if (ilStr::strLen($str_arr[$i]) > $a_len)
1364  {
1365  $str_arr[$i] = ilStr::subStr($str_arr[$i], 0, $a_len);
1366  if ($a_dots)
1367  {
1368  $str_arr[$i].= "...";
1369  }
1370  }
1371  }
1372 
1373  return implode($str_arr, " ");
1374  }
1375 
1383  function attribsToArray($a_str)
1384  {
1385  $attribs = array();
1386  while (is_int(strpos($a_str, "=")))
1387  {
1388  $eq_pos = strpos($a_str, "=");
1389  $qu1_pos = strpos($a_str, "\"");
1390  $qu2_pos = strpos(substr($a_str, $qu1_pos + 1), "\"") + $qu1_pos + 1;
1391  if (is_int($eq_pos) && is_int($qu1_pos) && is_int($qu2_pos))
1392  {
1393  $var = trim(substr($a_str, 0, $eq_pos));
1394  $val = trim(substr($a_str, $qu1_pos + 1, ($qu2_pos - $qu1_pos) - 1));
1395  $attribs[$var] = $val;
1396  $a_str = substr($a_str, $qu2_pos + 1);
1397  }
1398  else
1399  {
1400  $a_str = "";
1401  }
1402  }
1403  return $attribs;
1404  }
1405 
1415  function rCopy ($a_sdir, $a_tdir, $preserveTimeAttributes = false)
1416  {
1417  // check if arguments are directories
1418  if (!@is_dir($a_sdir) or
1419  !@is_dir($a_tdir))
1420  {
1421  return FALSE;
1422  }
1423 
1424  // read a_sdir, copy files and copy directories recursively
1425  $dir = opendir($a_sdir);
1426 
1427  while($file = readdir($dir))
1428  {
1429  if ($file != "." and
1430  $file != "..")
1431  {
1432  // directories
1433  if (@is_dir($a_sdir."/".$file))
1434  {
1435  if (!@is_dir($a_tdir."/".$file))
1436  {
1437  if (!ilUtil::makeDir($a_tdir."/".$file))
1438  return FALSE;
1439 
1440  //chmod($a_tdir."/".$file, 0775);
1441  }
1442 
1443  if (!ilUtil::rCopy($a_sdir."/".$file,$a_tdir."/".$file))
1444  {
1445  return FALSE;
1446  }
1447  }
1448 
1449  // files
1450  if (@is_file($a_sdir."/".$file))
1451  {
1452  if (!copy($a_sdir."/".$file,$a_tdir."/".$file))
1453  {
1454  return FALSE;
1455  }
1456  if ($preserveTimeAttributes)
1457  touch($a_tdir."/".$file, filectime($a_sdir."/".$file));
1458  }
1459  }
1460  }
1461  return TRUE;
1462  }
1463 
1471  function getWebspaceDir($mode = "filesystem")
1472  {
1473  global $ilias;
1474 
1475  if ($mode == "filesystem")
1476  {
1477  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1478  }
1479  else
1480  {
1481  if (defined("ILIAS_MODULE"))
1482  {
1483  return "../".ILIAS_WEB_DIR."/".$ilias->client_id;
1484  }
1485  else
1486  {
1487  return "./".ILIAS_WEB_DIR."/".$ilias->client_id;
1488  }
1489  }
1490 
1491  //return $ilias->ini->readVariable("server","webspace_dir");
1492  }
1493 
1497  function getDataDir()
1498  {
1499  return CLIENT_DATA_DIR;
1500  //global $ilias;
1501 
1502  //return $ilias->ini->readVariable("server", "data_dir");
1503  }
1504 
1512  function getUsersOnline($a_user_id = 0)
1513  {
1514  global $ilias, $ilDB;
1515 
1516  $pd_set = new ilSetting("pd");
1517  $atime = $pd_set->get("user_activity_time") * 60;
1518  $ctime = time();
1519 
1520  if ($a_user_id == 0)
1521  {
1522  $where = "WHERE user_id != 0 AND agree_date != '0000-00-00 00:00:00'";
1523  }
1524  else
1525  {
1526  $where = "WHERE user_id = ".$ilDB->quote($a_user_id)." ";
1527  }
1528 
1529  // BEGIN WebDAV: Fetch max(ctime) of a user
1530  $q = "SELECT count(user_id) as num,user_id,firstname,lastname,title,login,last_login,max(ctime) AS ctime FROM usr_session ".
1531  "LEFT JOIN usr_data ON user_id=usr_id ".$where.
1532  "AND expires>UNIX_TIMESTAMP() ".
1533  "GROUP BY user_id ".
1534  "ORDER BY lastname, firstname";
1535  // ENDWebDAV: Fetch max(ctime) of a user
1536  $r = $ilias->db->query($q);
1537 
1538  while ($user = $r->fetchRow(DB_FETCHMODE_ASSOC))
1539  {
1540  if ($atime <= 0
1541  || $user["ctime"] + $atime > $ctime)
1542  {
1543  $users[$user["user_id"]] = $user;
1544  }
1545  }
1546 
1547  return $users ? $users : array();
1548  }
1549 
1558  function getAssociatedUsersOnline($a_user_id)
1559  {
1560  global $ilias, $ilDB;
1561 
1562  $pd_set = new ilSetting("pd");
1563  $atime = $pd_set->get("user_activity_time") * 60;
1564  $ctime = time();
1565 
1566  // The difference between active time and session time
1567  $time_diff = 0;
1568 
1569  // Get a list of object id's of all courses and groups for which
1570  // the current user has local roles.
1571  // Note: we have to use DISTINCT here, because a user may assume
1572  // multiple roles in a group or a course.
1573  $q = "SELECT DISTINCT dat.obj_id as obj_id ".
1574  "FROM rbac_ua AS ua ".
1575  "JOIN rbac_fa AS fa ON fa.rol_id = ua.rol_id ".
1576  "JOIN object_reference AS r1 ON r1.ref_id = fa.parent ".
1577  "JOIN tree ON tree.child = r1.ref_id ".
1578  "JOIN object_reference AS r2 ON r2.ref_id = tree.parent ".
1579  "JOIN object_data AS dat ON dat.obj_id = r2.obj_id ".
1580  "WHERE ua.usr_id = ".$ilDB->quote($a_user_id)." ".
1581  "AND fa.assign = 'y' ".
1582  "AND dat.type IN ('grp','crs')";
1583  $r = $ilias->db->query($q);
1584  while ($row = $r->fetchRow(DB_FETCHMODE_ASSOC))
1585  {
1586  $groups_and_courses_of_user[] = $row["obj_id"];
1587  }
1588 
1589  // If the user is not in a course or a group, he has no associated users.
1590  if (count($groups_and_courses_of_user) == 0)
1591  {
1592  $q = "SELECT count(user_id) as num,ctime,user_id,firstname,lastname,title,login,last_login ".
1593  "FROM usr_session ".
1594  "JOIN usr_data ON user_id=usr_id ".
1595  "WHERE user_id = ".$ilDB->quote($a_user_id)." ".
1596  " AND agree_date != '0000-00-00 00:00:00' ".
1597  "AND expires > UNIX_TIMESTAMP() - ".$time_diff." ".
1598  "GROUP BY user_id";
1599  }
1600  else
1601  {
1602  $q = "SELECT count(user_id) as num,s.ctime,s.user_id,ud.firstname,ud.lastname,ud.title,ud.login,ud.last_login ".
1603  "FROM usr_session AS s ".
1604  "JOIN usr_data AS ud ON ud.usr_id = s.user_id ".
1605  "JOIN rbac_ua AS ua ON ua.usr_id = s.user_id ".
1606  "JOIN rbac_fa AS fa ON fa.rol_id = ua.rol_id ".
1607  "JOIN tree ON tree.child = fa.parent ".
1608  "JOIN object_reference AS or1 ON or1.ref_id = tree.parent ".
1609  "JOIN object_data AS od ON od.obj_id = or1.obj_id ".
1610  "WHERE s.user_id != 0 ".
1611  "AND s.expires > UNIX_TIMESTAMP() - ".$time_diff." ".
1612  "AND fa.assign = 'y' ".
1613  " AND ud.agree_date != '0000-00-00 00:00:00' ".
1614  "AND od.obj_id IN (".implode(",",ilUtil::quoteArray($groups_and_courses_of_user)).") ".
1615  "GROUP BY s.user_id ".
1616  "ORDER BY ud.lastname, ud.firstname";
1617  }
1618  $r = $ilias->db->query($q);
1619 
1620  while ($user = $r->fetchRow(DB_FETCHMODE_ASSOC))
1621  {
1622  if ($atime <= 0
1623  || $user["ctime"] + $atime > $ctime)
1624  {
1625  $users[$user["user_id"]] = $user;
1626  }
1627  }
1628 
1629  return $users ? $users : array();
1630  }
1631 
1637  function ilTempnam()
1638  {
1639  $temp_path = ilUtil::getDataDir() . "/temp";
1640  if (!is_dir($temp_path))
1641  {
1642  ilUtil::createDirectory($temp_path);
1643  }
1644  $temp_name = tempnam($temp_path, "tmp");
1645  // --->
1646  // added the following line because tempnam creates a backslash on some
1647  // Windows systems which leads to problems, because the "...\tmp..." can be
1648  // interpreted as "...{TAB-CHARACTER}...". The normal slash works fine
1649  // even under windows (Helmut Schottmüller, 2005-08-31)
1650  $temp_name = str_replace("\\", "/", $temp_name);
1651  // --->
1652  unlink($temp_name);
1653  return $temp_name;
1654  }
1655 
1661  function createDirectory($a_dir, $a_mod = 0755)
1662  {
1663  ilUtil::makeDir($a_dir);
1664  //@mkdir($a_dir);
1665  //@chmod($a_dir, $a_mod);
1666  }
1667 
1668 
1675  function unzip($a_file, $overwrite = false)
1676  {
1677  //global $ilias;
1678 
1679  $pathinfo = pathinfo($a_file);
1680  $dir = $pathinfo["dirname"];
1681  $file = $pathinfo["basename"];
1682 
1683  // unzip
1684  $cdir = getcwd();
1685  chdir($dir);
1686  $unzip = PATH_TO_UNZIP;
1687  //$unzip = $ilias->getSetting("unzip_path");
1688 
1689  // workaround for unzip problem (unzip of subdirectories fails, so
1690  // we create the subdirectories ourselves first)
1691  // get list
1692  $unzipcmd = $unzip." -Z -1 ".ilUtil::escapeShellArg($file);
1693  exec($unzipcmd, $arr);
1694  $zdirs = array();
1695 
1696  foreach($arr as $line)
1697  {
1698  if(is_int(strpos($line, "/")))
1699  {
1700  $zdir = substr($line, 0, strrpos($line, "/"));
1701  $nr = substr_count($zdir, "/");
1702  //echo $zdir." ".$nr."<br>";
1703  while ($zdir != "")
1704  {
1705  $nr = substr_count($zdir, "/");
1706  $zdirs[$zdir] = $nr; // collect directories
1707  //echo $dir." ".$nr."<br>";
1708  $zdir = substr($zdir, 0, strrpos($zdir, "/"));
1709  }
1710  }
1711  }
1712 
1713  asort($zdirs);
1714 
1715  foreach($zdirs as $zdir => $nr) // create directories
1716  {
1717  ilUtil::createDirectory($zdir);
1718  }
1719 
1720  // real unzip
1721  if ($overvwrite)
1722  {
1723  $unzipcmd = $unzip." ".ilUtil::escapeShellArg($file);
1724  }
1725  else
1726  {
1727  $unzipcmd = $unzip." -o ".ilUtil::escapeShellArg($file);
1728  }
1729  exec($unzipcmd);
1730 
1731  chdir($cdir);
1732  }
1733 
1737  function zip($a_dir, $a_file)
1738  {
1739  //global $ilias;
1740 
1741  $pathinfo = pathinfo($a_file);
1742  $dir = $pathinfo["dirname"];
1743 
1744  // unzip
1745  $cdir = getcwd();
1746  chdir($dir);
1747 
1748  $zip = PATH_TO_ZIP;
1749  //$zip = $ilias->getSetting("zip_path");
1750 
1751  if(!$zip)
1752  {
1753  chdir($cdir);
1754  return false;
1755  }
1756 
1757  if (is_array($a_dir))
1758  {
1759  $source = "";
1760  foreach($a_dir as $dir)
1761  {
1762  $name = basename($dir);
1763  $source.= " ".ilUtil::escapeShellArg($name);
1764  }
1765  }
1766  else
1767  {
1768  $name = basename($a_dir);
1769  $source = ilUtil::escapeShellArg($name);
1770  }
1771 
1772  $zipcmd = $zip." -r ".ilUtil::escapeShellArg($a_file)." ".$source;
1773  exec($zipcmd);
1774 //echo htmlentities($zipcmd);
1775  chdir($cdir);
1776  return true;
1777  }
1778 
1782  function getConvertCmd()
1783  {
1784  return PATH_TO_CONVERT;
1785  //global $ilias;
1786 
1787  //return $ilias->getSetting("convert_path");
1788  }
1789 
1797  function convertImage($a_from, $a_to, $a_target_format = "", $a_geometry = "",
1798  $a_background_color = "")
1799  {
1800  $format_str = ($a_target_format != "")
1801  ? strtoupper($a_target_format).":"
1802  : "";
1803  $geometry = ($a_geometry != "")
1804  ? " -geometry ".$a_geometry."x".$a_geometry." "
1805  : "";
1806  $bg_color = ($a_background_color != "")
1807  ? " -background color ".$a_background_color." "
1808  : "";
1809  $convert_cmd = ilUtil::getConvertCmd()." ".
1810  ilUtil::escapeShellArg($a_from)." ".$bg_color.$geometry.ilUtil::escapeShellArg($format_str.$a_to);
1811  system($convert_cmd);
1812  }
1813 
1822  function resizeImage($a_from, $a_to, $a_width, $a_height)
1823  {
1824  $size = " -resize ".$a_width."x".$a_height."! ";
1825  $convert_cmd = ilUtil::getConvertCmd()." ".
1826  ilUtil::escapeShellArg($a_from)." ".$size.ilUtil::escapeShellArg($a_to);
1827  system($convert_cmd);
1828  }
1829 
1835  function html2pdf($html, $pdf_file)
1836  {
1837  //global $ilias;
1838 
1839  $html_file = str_replace(".pdf",".html",$pdf_file);
1840 
1841  $fp = fopen( $html_file ,"wb");
1842  fwrite($fp, $html);
1843  fclose($fp);
1844 
1845  $htmldoc_path = PATH_TO_HTMLDOC;
1846  //$htmldoc_path = $ilias->getSetting("htmldoc_path");
1847 
1848  $htmldoc = $htmldoc_path." ";
1849  $htmldoc .= "--no-toc ";
1850  $htmldoc .= "--no-jpeg ";
1851  $htmldoc .= "--webpage ";
1852  $htmldoc .= "--outfile " . ilUtil::escapeShellArg($pdf_file) . " ";
1853  $htmldoc .= "--bodyfont Arial ";
1854  $htmldoc .= "--charset iso-8859-15 ";
1855  $htmldoc .= "--color ";
1856  $htmldoc .= "--size A4 "; // --landscape
1857  $htmldoc .= "--format pdf ";
1858  $htmldoc .= "--footer ... ";
1859  $htmldoc .= "--header ... ";
1860  $htmldoc .= "--left 60 ";
1861  // $htmldoc .= "--right 200 ";
1862  $htmldoc .= $html_file;
1863  exec($htmldoc);
1864 
1865  }
1866 
1870  function deliverData($a_data, $a_filename, $mime = "application/octet-stream", $charset = "")
1871  {
1872  $disposition = "attachment"; // "inline" to view file in browser or "attachment" to download to hard disk
1873  // $mime = "application/octet-stream"; // or whatever the mime type is
1874 
1875  if (isset($_SERVER["HTTPS"])) {
1876 
1877  // Added different handling for IE and HTTPS => send pragma after content informations
1881  #header("Pragma: ");
1882  #header("Cache-Control: ");
1883  #header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1884  #header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
1885  #header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
1886  #header("Cache-Control: post-check=0, pre-check=0", false);
1887  }
1888  else if ($disposition == "attachment")
1889  {
1890  header("Cache-control: private");
1891  }
1892  else
1893  {
1894  header("Cache-Control: no-cache, must-revalidate");
1895  header("Pragma: no-cache");
1896  }
1897 
1898  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
1899 
1900  if (strlen($charset))
1901  {
1902  $charset = "; charset=$charset";
1903  }
1904  header("Content-Type: $mime$charset");
1905  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
1906  header("Content-Description: ".$ascii_filename);
1907  header("Content-Length: ".(string)(strlen($a_data)));
1908 
1909  if($_SERVER['HTTPS'])
1910  {
1911  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1912  header('Pragma: public');
1913  }
1914 
1915  header("Connection: close");
1916  echo $a_data;
1917  exit;
1918  }
1919 
1920  // BEGIN WebDAV: Show file in browser or provide it as attachment
1926  function deliverFile($a_file, $a_filename,$a_mime = '', $isInline = false, $removeAfterDelivery = false)
1927  {
1928  if ($isInline) {
1929  $disposition = "inline"; // "inline" to view file in browser
1930  } else {
1931  $disposition = "attachment"; // "attachment" to download to hard disk
1932  //$a_mime = "application/octet-stream"; // override mime type to ensure that no browser tries to show the file anyway.
1933  }
1934  // END WebDAV: Show file in browser or provide it as attachment
1935 
1936  if(strlen($a_mime))
1937  {
1938  $mime = $a_mime;
1939  }
1940  else
1941  {
1942  $mime = "application/octet-stream"; // or whatever the mime type is
1943  }
1944  // BEGIN WebDAV: Removed broken HTTPS code.
1945  // END WebDAV: Removed broken HTTPS code.
1946  if ($disposition == "attachment")
1947  {
1948  header("Cache-control: private");
1949  }
1950  else
1951  {
1952  header("Cache-Control: no-cache, must-revalidate");
1953  header("Pragma: no-cache");
1954  }
1955 
1956  $ascii_filename = ilUtil::getASCIIFilename($a_filename);
1957 
1958  header("Content-Type: $mime");
1959  header("Content-Disposition:$disposition; filename=\"".$ascii_filename."\"");
1960  header("Content-Description: ".$ascii_filename);
1961  header("Content-Length: ".(string)(filesize($a_file)));
1962 
1963  if($_SERVER['HTTPS'])
1964  {
1965  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1966  header('Pragma: public');
1967  }
1968 
1969  header("Connection: close");
1970  ilUtil::readFile( $a_file );
1971  if ($removeAfterDelivery)
1972  {
1973  unlink ($a_file);
1974  }
1975  exit;
1976  }
1977 
1978 
1985  function readFile($a_file)
1986  {
1987  $chunksize = 1*(1024*1024); // how many bytes per chunk
1988  $buffer = '';
1989  $handle = fopen($a_file, 'rb');
1990  if ($handle === false)
1991  {
1992  return false;
1993  }
1994  while (!feof($handle))
1995  {
1996  $buffer = fread($handle, $chunksize);
1997  print $buffer;
1998  }
1999  return fclose($handle);
2000  }
2001 
2007  function getASCIIFilename($a_filename)
2008  {
2009  // The filename must be converted to ASCII, as of RFC 2183,
2010  // section 2.3.
2011  // Despite the RFC, Internet Explorer on Windows supports
2012  // ISO 8895-1 encoding for the file name. We use this fact, to
2013  // produce a better result, if the user uses IE.
2014 
2026 
2027  $user_agent = strtolower($_SERVER["HTTP_USER_AGENT"]);
2028  if ((is_integer(strpos($user_agent, "msie"))) && is_integer(strpos($user_agent, "win")))
2029  {
2032 
2033  $ascii_filename = utf8_decode($a_filename);
2034  }
2035  else
2036  {
2039 
2040  $ascii_filename = htmlentities($a_filename,ENT_NOQUOTES,'UTF-8');
2041  $ascii_filename = preg_replace('/\&(.)[^;]*;/','\\1', $ascii_filename);
2042  $ascii_filename = preg_replace('/[\x7f-\xff]/','_', $ascii_filename);
2043  }
2044 
2045  // OS do not allow the following characters in filenames:
2046  // \/:*?"<>|
2047  //if (is_integer(strpos($user_agent, "win")))
2048  {
2049  $ascii_filename = preg_replace('/[:\x5c\/\*\?\"<>\|]/','_', $ascii_filename);
2050  }
2051 
2052  return $ascii_filename;
2053  }
2054 
2058  function getJavaPath()
2059  {
2060  return PATH_TO_JAVA;
2061  //global $ilias;
2062 
2063  //return $ilias->getSetting("java_path");
2064  }
2065 
2070  function appendUrlParameterString($a_url, $a_par)
2071  {
2072  $url = (is_int(strpos($a_url, "?")))
2073  ? $a_url."&".$a_par
2074  : $a_url."?".$a_par;
2075 
2076  return $url;
2077  }
2078 
2093  function makeDir($a_dir)
2094  {
2095  $a_dir = trim($a_dir);
2096 
2097  // remove trailing slash (bugfix for php 4.2.x)
2098  if (substr($a_dir,-1) == "/")
2099  {
2100  $a_dir = substr($a_dir,0,-1);
2101  }
2102 
2103  // check if a_dir comes with a path
2104  if (!($path = substr($a_dir,0, strrpos($a_dir,"/") - strlen($a_dir))))
2105  {
2106  $path = ".";
2107  }
2108 
2109  // create directory with file permissions of parent directory
2110  umask(0000);
2111  return @mkdir($a_dir,fileperms($path));
2112  }
2113 
2114 
2127  function makeDirParents($a_dir)
2128  {
2129  $dirs = array($a_dir);
2130  $a_dir = dirname($a_dir);
2131  $last_dirname = '';
2132  while($last_dirname != $a_dir)
2133  {
2134  array_unshift($dirs, $a_dir);
2135  $last_dirname = $a_dir;
2136  $a_dir = dirname($a_dir);
2137  }
2138 
2139  // find the first existing dir
2140  $reverse_paths = array_reverse($dirs, TRUE);
2141  $found_index = -1;
2142  foreach ($reverse_paths as $key => $value)
2143  {
2144  if ($found_index == -1)
2145  {
2146  if (is_dir($value))
2147  {
2148  $found_index = $key;
2149  }
2150  }
2151  }
2152 
2153  umask(0000);
2154  foreach ($dirs as $dirindex => $dir)
2155  {
2156  // starting with the longest existing path
2157  if ($dirindex >= $found_index)
2158  {
2159  if (! file_exists($dir))
2160  {
2161  if (strcmp(substr($dir,strlen($dir)-1,1),"/") == 0)
2162  {
2163  // on some systems there is an error when there is a slash
2164  // at the end of a directory in mkdir, see Mantis #2554
2165  $dir = substr($dir,0,strlen($dir)-1);
2166  }
2167  if (! mkdir($dir, $umask))
2168  {
2169  error_log("Can't make directory: $dir");
2170  return false;
2171  }
2172  }
2173  elseif (! is_dir($dir))
2174  {
2175  error_log("$dir is not a directory");
2176  return false;
2177  }
2178  else
2179  {
2180  // get umask of the last existing parent directory
2181  $umask = fileperms($dir);
2182  }
2183  }
2184  }
2185  return true;
2186  }
2187 
2195  function delDir($a_dir)
2196  {
2197  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
2198  {
2199  return;
2200  }
2201 
2202  $current_dir = opendir($a_dir);
2203 
2204  $files = array();
2205 
2206  // this extra loop has been necessary because of a strange bug
2207  // at least on MacOS X. A looped readdir() didn't work
2208  // correctly with larger directories
2209  // when an unlink happened inside the loop. Getting all files
2210  // into the memory first solved the problem.
2211  while($entryname = readdir($current_dir))
2212  {
2213  $files[] = $entryname;
2214  }
2215 
2216  foreach($files as $file)
2217  {
2218  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
2219  {
2220  ilUtil::delDir(${a_dir}."/".${file});
2221  }
2222  elseif ($file != "." and $file != "..")
2223  {
2224  unlink(${a_dir}."/".${file});
2225  }
2226  }
2227 
2228  closedir($current_dir);
2229  @rmdir(${a_dir});
2230  }
2231 
2232 
2236  function getDir($a_dir)
2237  {
2238  $current_dir = opendir($a_dir);
2239 
2240  $dirs = array();
2241  $files = array();
2242  while($entry = readdir($current_dir))
2243  {
2244  if(is_dir($a_dir."/".$entry))
2245  {
2246  $dirs[$entry] = array("type" => "dir", "entry" => $entry);
2247  }
2248  else
2249  {
2250  if ($entry != "." && $entry != "..")
2251  {
2252  $size = filesize($a_dir."/".$entry);
2253  $files[$entry] = array("type" => "file", "entry" => $entry,
2254  "size" => $size);
2255  }
2256  }
2257  }
2258  ksort($dirs);
2259  ksort($files);
2260 
2261  return array_merge($dirs, $files);
2262  }
2263 
2264 
2272  function getGroupId($a_parent_ref)
2273  {
2274  return false;
2275 
2276  global $ilias, $ilDB;
2277 
2278  $q = "SELECT DISTINCT tree FROM grp_tree WHERE child=".
2279  $ilDB->quote($a_parent_ref);
2280  $r = $ilias->db->query($q);
2281  $row = $r->fetchRow();
2282 
2283  return $row[0] ? $row[0] : false;
2284  }
2285 
2289  function stripSlashesArray($a_arr, $a_strip_html = true, $a_allow = "")
2290  {
2291  if (is_array($a_arr))
2292  {
2293  foreach ($a_arr as $k => $v)
2294  {
2295  $a_arr[$k] = ilUtil::stripSlashes($v, $a_strip_html, $a_allow);
2296  }
2297  }
2298 
2299  return $a_arr;
2300  }
2301 
2307  function stripSlashes($a_str, $a_strip_html = true, $a_allow = "")
2308  {
2309  if (ini_get("magic_quotes_gpc"))
2310  {
2311  $a_str = stripslashes($a_str);
2312  }
2313 
2314  return ilUtil::secureString($a_str, $a_strip_html, $a_allow);
2315  }
2316 
2320  function secureString($a_str, $a_strip_html = true, $a_allow = "")
2321  {
2322  // check whether all allowed tags can be made secure
2323  $only_secure = true;
2324  $allow_tags = explode(">", $a_allow);
2325  $sec_tags = ilUtil::getSecureTags();
2326  $allow_array = array();
2327  foreach($allow_tags as $allow)
2328  {
2329  if ($allow != "")
2330  {
2331  $allow = str_replace("<", "", $allow);
2332 
2333  if (!in_array($allow, $sec_tags))
2334  {
2335  $only_secure = false;
2336  }
2337  $allow_array[] = $allow;
2338  }
2339  }
2340 
2341  // default behaviour: allow only secure tags 1:1
2342  if (($only_secure || $a_allow == "") && $a_strip_html)
2343  {
2344  if ($a_allow == "")
2345  {
2346  $allow_array = array ("b", "i", "strong", "em", "code", "cite",
2347  "gap", "sub", "sup", "pre", "strike");
2348  }
2349 
2350  // this currently removes parts of strings like "a <= b"
2351  // because "a <= b" is treated like "<spam onclick='hurt()'>ss</spam>"
2352  $a_str = ilUtil::maskSecureTags($a_str, $allow_array);
2353  $a_str = strip_tags($a_str); // strip all other tags
2354  $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2355 
2356  // a possible solution could be something like:
2357  // $a_str = str_replace("<", "&lt;", $a_str);
2358  // $a_str = str_replace(">", "&gt;", $a_str);
2359  // $a_str = ilUtil::unmaskSecureTags($a_str, $allow_array);
2360  //
2361  // output would be ok then, but input fields would show
2362  // "a &lt;= b" for input "a <= b" if data is brought back to a form
2363  }
2364  else
2365  {
2366  // only for scripts, that need to allow more/other tags and parameters
2367  if ($a_strip_html)
2368  {
2369  $a_str = ilUtil::stripScriptHTML($a_str, $a_allow);
2370  }
2371  }
2372 
2373  return $a_str;
2374  }
2375 
2376  function getSecureTags()
2377  {
2378  return array("strong", "em", "u", "strike", "ol", "li", "ul", "p", "div",
2379  "i", "b", "code", "sup", "sub", "pre", "gap", "a", "img");
2380  }
2381 
2382  function maskSecureTags($a_str, $allow_array)
2383  {
2384  foreach ($allow_array as $t)
2385  {
2386  switch($t)
2387  {
2388  case "a":
2389  $a_str = ilUtil::maskAttributeTag($a_str, "a", "href");
2390  break;
2391 
2392  case "img":
2393  $a_str = ilUtil::maskAttributeTag($a_str, "img", "src");
2394  break;
2395 
2396  case "p":
2397  case "div":
2398  $a_str = ilUtil::maskTag($a_str, $t, array(
2399  array("param" => "align", "value" => "left"),
2400  array("param" => "align", "value" => "center"),
2401  array("param" => "align", "value" => "justify"),
2402  array("param" => "align", "value" => "right")
2403  ));
2404  break;
2405 
2406  default:
2407  $a_str = ilUtil::maskTag($a_str, $t);
2408  break;
2409  }
2410  }
2411 
2412  return $a_str;
2413  }
2414 
2415  function unmaskSecureTags($a_str, $allow_array)
2416  {
2417  foreach ($allow_array as $t)
2418  {
2419  switch($t)
2420  {
2421  case "a":
2422  $a_str = ilUtil::unmaskAttributeTag($a_str, "a", "href");
2423  break;
2424 
2425  case "img":
2426  $a_str = ilUtil::unmaskAttributeTag($a_str, "img", "src");
2427  break;
2428 
2429  case "p":
2430  case "div":
2431  $a_str = ilUtil::unmaskTag($a_str, $t, array(
2432  array("param" => "align", "value" => "left"),
2433  array("param" => "align", "value" => "center"),
2434  array("param" => "align", "value" => "justify"),
2435  array("param" => "align", "value" => "right")
2436  ));
2437  break;
2438 
2439  default:
2440  $a_str = ilUtil::unmaskTag($a_str, $t);
2441  break;
2442  }
2443  }
2444 
2445  return $a_str;
2446  }
2447 
2452  function securePlainString($a_str)
2453  {
2454  if (ini_get("magic_quotes_gpc"))
2455  {
2456  return stripslashes($a_str);
2457  }
2458  else
2459  {
2460  return $a_str;
2461  }
2462  }
2477  function htmlencodePlainString($a_str, $a_make_links_clickable, $a_detect_goto_links = false)
2478  {
2479  $encoded = "";
2480 
2481  if ($a_make_links_clickable)
2482  {
2483  // Find text sequences in the plain text string which match
2484  // the URI syntax rules, and pass them to ilUtil::makeClickable.
2485  // Encode all other text sequences in the plain text string using
2486  // htmlspecialchars and nl2br.
2487  // The following expressions matches URI's as specified in RFC 2396.
2488  //
2489  // The expression matches URI's, which start with some well known
2490  // schemes, like "http:", or with "www.". This must be followed
2491  // by at least one of the following RFC 2396 expressions:
2492  // - alphanum: [a-zA-Z0-9]
2493  // - reserved: [;\/?:|&=+$,]
2494  // - mark: [\\-_.!~*\'()]
2495  // - escaped: %[0-9a-fA-F]{2}
2496  // - fragment delimiter: #
2497  // - uric_no_slash: [;?:@&=+$,]
2498  $matches = array();
2499  $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);
2500  $pos1 = 0;
2501  $encoded = "";
2502  foreach ($matches as $match)
2503  {
2504  }
2505  foreach ($matches[0] as $match)
2506  {
2507  $matched_text = $match[0];
2508  $pos2 = $match[1];
2509  if ($matched_offset != previous_offset)
2510  {
2511  // encode plain text
2512  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1, $pos2 - $pos1)));
2513  }
2514  // encode URI
2515  $encoded .= ilUtil::makeClickable($matched_text, $a_detect_goto_links);
2516 
2517 
2518  $pos1 = $pos2 + strlen($matched_text);
2519  }
2520  if ($pos1 < strlen($a_str))
2521  {
2522  $encoded .= nl2br(htmlspecialchars(substr($a_str, $pos1)));
2523  }
2524  }
2525  else
2526  {
2527  $encoded = nl2br(htmlspecialchars($a_str));
2528  }
2529  return $encoded;
2530  }
2531 
2532 
2533  function maskAttributeTag($a_str, $tag, $tag_att)
2534  {
2535  global $ilLog;
2536 
2537  $ws = "[ \t\r\f\v\n]*";
2538  $att = $ws."[^>]*".$ws;
2539 
2540  while (eregi("<($tag$att($tag_att$ws=$ws\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")$att)>",
2541  $a_str, $found))
2542  {
2543  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2544  $esc = array();
2545  foreach($un as $v)
2546  {
2547  $esc[] = "\\".$v;
2548  }
2549  $ff = str_replace($un, $esc, $found[1]);
2550 
2551  $old_str = $a_str;
2552  $a_str = eregi_replace("<".$ff.">",
2553  "&lt;$tag $tag_att$tag_att=\"".$found[3]."\"&gt;", $a_str);
2554  if ($old_str == $a_str)
2555  {
2556  $ilLog->write("ilUtil::maskA-".htmlentities($old_str)." == ".
2557  htmlentities($a_str));
2558  return $a_str;
2559  }
2560  }
2561  $a_str = str_ireplace("</$tag>",
2562  "&lt;/$tag&gt;", $a_str);
2563  return $a_str;
2564  }
2565 
2566  function unmaskAttributeTag($a_str, $tag, $tag_att)
2567  {
2568  global $ilLog;
2569 
2570  while (eregi("&lt;($tag $tag_att$tag_att=\"(([\$@!*()~;,_0-9A-z/:=%\\.&#?+\\-])*)\")&gt;",
2571  $a_str, $found))
2572  {
2573  $un = array(".", "-", "+", "?", '$', "*", "(", ")");
2574  $esc = array();
2575  foreach($un as $v)
2576  {
2577  $esc[] = "\\".$v;
2578  }
2579  $ff = str_replace($un, $esc, $found[1]);
2580 
2581  $old_str = $a_str;
2582  $a_str = eregi_replace("&lt;".$ff."&gt;",
2583  "<$tag $tag_att=\"".ilUtil::secureLink($found[2])."\">", $a_str);
2584  if ($old_str == $a_str)
2585  {
2586  $ilLog->write("ilUtil::unmaskA-".htmlentities($old_str)." == ".
2587  htmlentities($a_str));
2588  return $a_str;
2589  }
2590  }
2591  $a_str = str_replace("&lt;/$tag&gt;", "</$tag>", $a_str);
2592  return $a_str;
2593  }
2594 
2595  function maskTag($a_str, $t, $fix_param = "")
2596  {
2597  $a_str = str_replace(array("<$t>", "<".strtoupper($t).">"),
2598  "&lt;".$t."&gt;", $a_str);
2599  $a_str = str_replace(array("</$t>", "</".strtoupper($t).">"),
2600  "&lt;/".$t."&gt;", $a_str);
2601 
2602  if (is_array($fix_param))
2603  {
2604  foreach ($fix_param as $p)
2605  {
2606  $k = $p["param"];
2607  $v = $p["value"];
2608  $a_str = str_replace("<$t $k=\"$v\">",
2609  "&lt;"."$t $k=\"$v\""."&gt;", $a_str);
2610  }
2611  }
2612 
2613  return $a_str;
2614  }
2615 
2616  function unmaskTag($a_str, $t, $fix_param = "")
2617  {
2618  $a_str = str_replace("&lt;".$t."&gt;", "<".$t.">", $a_str);
2619  $a_str = str_replace("&lt;/".$t."&gt;", "</".$t.">", $a_str);
2620 
2621  if (is_array($fix_param))
2622  {
2623  foreach ($fix_param as $p)
2624  {
2625  $k = $p["param"];
2626  $v = $p["value"];
2627  $a_str = str_replace("&lt;$t $k=\"$v\"&gt;",
2628  "<"."$t $k=\"$v\"".">", $a_str);
2629  }
2630  }
2631  return $a_str;
2632  }
2633 
2634  function secureLink($a_str)
2635  {
2636  $a_str = str_ireplace("javascript", "jvscrpt", $a_str);
2637  $a_str = str_ireplace(array("%00", "%0a", "%0d", "%1a", "&#00;", "&#x00;",
2638  "&#0;", "&#x0;", "&#x0a;", "&#x0d;", "&#10;", "&#13;"), "-", $a_str);
2639  return $a_str;
2640  }
2641 
2653  function stripScriptHTML($a_str, $a_allow = "", $a_rm_js = true)
2654  {
2655  //$a_str = strip_tags($a_str, $a_allow);
2656 
2657  $negativestr = "a,abbr,acronym,address,applet,area,b,base,basefont,".
2658  "bdo,big,blockquote,body,br,button,caption,center,cite,code,col,".
2659  "colgroup,dd,del,dfn,dir,div,dl,dt,em,fieldset,font,form,frame,".
2660  "frameset,h1,h2,h3,h4,h5,h6,head,hr,html,i,iframe,img,input,ins,isindex,kbd,".
2661  "label,legend,li,link,map,menu,meta,noframes,noscript,object,ol,".
2662  "optgroup,option,p,param,q,s,samp,script,select,small,span,".
2663  "strike,strong,style,sub,sup,table,tbody,td,textarea,tfoot,th,thead,".
2664  "title,tr,tt,u,ul,var";
2665  $a_allow = strtolower ($a_allow);
2666  $negatives = split (",",$negativestr);
2667  $outer_old_str = "";
2668  while($outer_old_str != $a_str)
2669  {
2670  $outer_old_str = $a_str;
2671  foreach ($negatives as $item)
2672  {
2673  $pos = strpos($a_allow, "<$item>");
2674 
2675  // remove complete tag, if not allowed
2676  if ($pos === false)
2677  {
2678  $old_str = "";
2679  while($old_str != $a_str)
2680  {
2681  $old_str = $a_str;
2682  $a_str = preg_replace("/<\/?\s*$item(\/?)\s*>/i", "", $a_str);
2683  $a_str = preg_replace("/<\/?\s*$item(\/?)\s+([^>]*)>/i", "", $a_str);
2684  }
2685  }
2686  }
2687  }
2688 
2689  if ($a_rm_js)
2690  {
2691  // remove all attributes if an "on..." attribute is given
2692  $a_str = preg_replace("/<\s*\w*(\/?)(\s+[^>]*)?(\s+on[^>]*)>/i", "", $a_str);
2693 
2694  // remove all attributes if a "javascript" is within tag
2695  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*javascript[^>]*>/i", "", $a_str);
2696 
2697  // remove all attributes if an "expression" is within tag
2698  // (IE allows something like <b style='width:expression(alert(1))'>test</b>)
2699  $a_str = preg_replace("/<\s*\w*(\/?)\s+[^>]*expression[^>]*>/i", "", $a_str);
2700  }
2701 
2702  return $a_str;
2703  }
2704 
2705 
2711  function addSlashes($a_str)
2712  {
2713  if (ini_get("magic_quotes_gpc"))
2714  {
2715  return $a_str;
2716  }
2717  else
2718  {
2719  return addslashes($a_str);
2720  }
2721  }
2722 
2732  function prepareFormOutput($a_str, $a_strip = false)
2733  {
2734  if($a_strip)
2735  {
2736  $a_str = ilUtil::stripSlashes($a_str);
2737  }
2738  $a_str = htmlspecialchars($a_str);
2739  // Added replacement of curly brackets to prevent
2740  // problems with PEAR templates, because {xyz} will
2741  // be removed as unused template variable
2742  $a_str = str_replace("{", "&#123;", $a_str);
2743  $a_str = str_replace("}", "&#125;", $a_str);
2744  // needed for LaTeX conversion \\ in LaTeX is a line break
2745  // but without this replacement, php changes \\ to \
2746  $a_str = str_replace("\\", "&#92;", $a_str);
2747  return $a_str;
2748  }
2749 
2750 
2758  function prepareDBString($a_str)
2759  {
2760  return addslashes($a_str);
2761  }
2762 
2763 
2770  function removeItemFromDesktops($a_id)
2771  {
2772  global $ilDB;
2773 
2774  $q = "SELECT user_id FROM desktop_item WHERE item_id = ".$ilDB->quote($a_id);
2775  $r = $ilDB->query($q);
2776 
2777  $users = array();
2778 
2779  while ($row = $r->fetchRow(DB_FETCHMODE_OBJECT))
2780  {
2781  $users[] = $row->user_id;
2782  } // while
2783 
2784  if (count($users) > 0)
2785  {
2786  $q = "DELETE FROM desktop_item WHERE item_id = ".
2787  $ilDB->quote($a_id);
2788  $ilDB->query($q);
2789  }
2790 
2791  return $users;
2792  }
2793 
2794 
2802  function extractParameterString($a_parstr)
2803  {
2804  // parse parameters in array
2805  $par = array();
2806  $ok=true;
2807  while(($spos=strpos($a_parstr,"=")) && $ok)
2808  {
2809  // extract parameter
2810  $cpar = substr($a_parstr,0,$spos);
2811  $a_parstr = substr($a_parstr,$spos,strlen($a_parstr)-$spos);
2812  while(substr($cpar,0,1)=="," ||substr($cpar,0,1)==" " || substr($cpar,0,1)==chr(13) || substr($cpar,0,1)==chr(10))
2813  $cpar = substr($cpar,1,strlen($cpar)-1);
2814  while(substr($cpar,strlen($cpar)-1,1)==" " || substr($cpar,strlen($cpar)-1,1)==chr(13) || substr($cpar,strlen($cpar)-1,1)==chr(10))
2815  $cpar = substr($cpar,0,strlen($cpar)-1);
2816 
2817  // parameter name should only
2818  $cpar_old = "";
2819  while($cpar != $cpar_old)
2820  {
2821  $cpar_old = $cpar;
2822  $cpar = eregi_replace("[^a-zA-Z0-9_]", "", $cpar);
2823  }
2824 
2825  // extract value
2826  if ($cpar != "")
2827  {
2828  if($spos=strpos($a_parstr,"\""))
2829  {
2830  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos);
2831  $spos=strpos($a_parstr,"\"");
2832  if(is_int($spos))
2833  {
2834  $cval = substr($a_parstr,0,$spos);
2835  $par[$cpar]=$cval;
2836  $a_parstr = substr($a_parstr,$spos+1,strlen($a_parstr)-$spos-1);
2837  }
2838  else
2839  $ok=false;
2840  }
2841  else
2842  $ok=false;
2843  }
2844  }
2845 
2846  if($ok) return $par; else return false;
2847  }
2848 
2849  function assembleParameterString($a_par_arr)
2850  {
2851  if (is_array($a_par_arr))
2852  {
2853  $target_arr = array();
2854  foreach ($a_par_arr as $par => $val)
2855  {
2856  $target_arr[] = "$par=\"$val\"";
2857  }
2858  $target_str = implode(", ", $target_arr);
2859  }
2860 
2861  return $target_str;
2862  }
2863 
2867  function dumpString($a_str)
2868  {
2869  $ret = $a_str.": ";
2870  for($i=0; $i<strlen($a_str); $i++)
2871  {
2872  $ret.= ord(substr($a_str,$i,1))." ";
2873  }
2874  return $ret;
2875  }
2876 
2877 
2881  function yn2tf($a_yn)
2882  {
2883  if(strtolower($a_yn) == "y")
2884  {
2885  return true;
2886  }
2887  else
2888  {
2889  return false;
2890  }
2891  }
2892 
2896  function tf2yn($a_tf)
2897  {
2898  if($a_tf)
2899  {
2900  return "y";
2901  }
2902  else
2903  {
2904  return "n";
2905  }
2906  }
2907 
2916  function sort_func ($a, $b)
2917  {
2918  global $array_sortby,$array_sortorder;
2919 
2920  if ($array_sortorder == "asc")
2921  {
2922  return strnatcasecmp($a[$array_sortby], $b[$array_sortby]);
2923  }
2924 
2925  if ($array_sortorder == "desc")
2926  {
2927  return strnatcasecmp($b[$array_sortby], $a[$array_sortby]);
2928  }
2929  }
2930 
2939  function sort_func_numeric ($a, $b)
2940  {
2941  global $array_sortby,$array_sortorder;
2942 
2943  if ($array_sortorder == "asc")
2944  {
2945  return $a["$array_sortby"] > $b["$array_sortby"];
2946  }
2947 
2948  if ($array_sortorder == "desc")
2949  {
2950  return $a["$array_sortby"] < $b["$array_sortby"];
2951  }
2952  }
2963  function sortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false,
2964  $a_keep_keys = false)
2965  {
2966  // BEGIN WebDAV: Provide a 'stable' sort algorithm
2967  if (! $a_keep_keys) {
2968  return self::stableSortArray($array,$a_array_sortby,$a_array_sortorder,$a_numeric,$a_keep_keys);
2969  }
2970  // END WebDAV Provide a 'stable' sort algorithm
2971 
2972  global $array_sortby,$array_sortorder;
2973 
2974  $array_sortby = $a_array_sortby;
2975 
2976  if ($a_array_sortorder == "desc")
2977  {
2978  $array_sortorder = "desc";
2979  }
2980  else
2981  {
2982  $array_sortorder = "asc";
2983  }
2984  if($a_numeric)
2985  {
2986  if ($a_keep_keys)
2987  {
2988  uasort($array, array("ilUtil", "sort_func_numeric"));
2989  }
2990  else
2991  {
2992  usort($array, array("ilUtil", "sort_func_numeric"));
2993  }
2994  }
2995  else
2996  {
2997  if ($a_keep_keys)
2998  {
2999  uasort($array, array("ilUtil", "sort_func"));
3000  }
3001  else
3002  {
3003  usort($array, array("ilUtil", "sort_func"));
3004  }
3005  }
3006  //usort($array,"ilUtil::sort_func");
3007 
3008  return $array;
3009  }
3010  // BEGIN WebDAV: Provide a 'stable' sort algorithm
3023  function stableSortArray($array,$a_array_sortby,$a_array_sortorder = 0,$a_numeric = false)
3024  {
3025  global $array_sortby,$array_sortorder;
3026 
3027  $array_sortby = $a_array_sortby;
3028 
3029  if ($a_array_sortorder == "desc")
3030  {
3031  $array_sortorder = "desc";
3032  }
3033  else
3034  {
3035  $array_sortorder = "asc";
3036  }
3037 
3038  // Create a copy of the array values for sorting
3039  $sort_array = array_values($array);
3040 
3041  if($a_numeric)
3042  {
3043  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func_numeric"));
3044  }
3045  else
3046  {
3047  ilUtil::mergesort($sort_array, array("ilUtil", "sort_func"));
3048  }
3049  return $sort_array;
3050  }
3051  function mergesort(&$array, $cmp_function = 'strcmp') {
3052  // Arrays of size < 2 require no action.
3053  if (count($array) < 2) return;
3054 
3055  // Split the array in half
3056  $halfway = count($array) / 2;
3057  $array1 = array_slice($array, 0, $halfway);
3058  $array2 = array_slice($array, $halfway);
3059 
3060  // Recurse to sort the two halves
3061  ilUtil::mergesort($array1, $cmp_function);
3062  ilUtil::mergesort($array2, $cmp_function);
3063 
3064  // If all of $array1 is <= all of $array2, just append them.
3065  if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
3066  $array = array_merge($array1, $array2);
3067  return;
3068  }
3069 
3070  // Merge the two sorted arrays into a single sorted array
3071  $array = array();
3072  $ptr1 = $ptr2 = 0;
3073  while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
3074  if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
3075  $array[] = $array1[$ptr1++];
3076  }
3077  else {
3078  $array[] = $array2[$ptr2++];
3079  }
3080  }
3081 
3082  // Merge the remainder
3083  while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
3084  while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
3085 
3086  return;
3087  }
3088  // END WebDAV: Provide a 'stable' sort algorithm
3089 
3099  function unique_multi_array($array, $sub_key)
3100  {
3101  $target = array();
3102  $existing_sub_key_values = array();
3103 
3104  foreach ($array as $key=>$sub_array)
3105  {
3106  if (!in_array($sub_array[$sub_key], $existing_sub_key_values))
3107  {
3108  $existing_sub_key_values[] = $sub_array[$sub_key];
3109  $target[$key] = $sub_array;
3110  }
3111  }
3112 
3113  return $target;
3114  }
3115 
3116 
3124  function getGDSupportedImageType($a_desired_type)
3125  {
3126  $a_desired_type = strtolower($a_desired_type);
3127  // get supported Image Types
3128  $im_types = ImageTypes();
3129 
3130  switch($a_desired_type)
3131  {
3132  case "jpg":
3133  if ($im_types & IMG_JPG) return "jpg";
3134  if ($im_types & IMG_GIF) return "gif";
3135  if ($im_types & IMG_PNG) return "png";
3136  break;
3137 
3138  case "gif":
3139  if ($im_types & IMG_GIF) return "gif";
3140  if ($im_types & IMG_JPG) return "jpg";
3141  if ($im_types & IMG_PNG) return "png";
3142  break;
3143 
3144  case "png":
3145  if ($im_types & IMG_PNG) return "png";
3146  if ($im_types & IMG_JPG) return "jpg";
3147  if ($im_types & IMG_GIF) return "gif";
3148  break;
3149  }
3150 
3151  return "";
3152  }
3153 
3161  function deducibleSize($a_mime)
3162  {
3163  if (($a_mime == "image/gif") || ($a_mime == "image/jpeg") ||
3164  ($a_mime == "image/png") || ($a_mime == "application/x-shockwave-flash") ||
3165  ($a_mime == "image/tiff") || ($a_mime == "image/x-ms-bmp") ||
3166  ($a_mime == "image/psd") || ($a_mime == "image/iff"))
3167  {
3168  return true;
3169  }
3170  else
3171  {
3172  return false;
3173  }
3174  }
3175 
3176 
3182  function redirect($a_script)
3183  {
3184  global $log, $PHP_SELF;
3185 //$log->write("redirect FROM:".$PHP_SELF." to ".$a_script);
3186  //vd($a_script);
3187  header("Location: ".$a_script);
3188  exit();
3189  }
3190 
3196  function insertInstIntoID($a_value)
3197  {
3198  if (substr($a_value, 0, 4) == "il__")
3199  {
3200  $a_value = "il_".IL_INST_ID."_".substr($a_value, 4, strlen($a_value) - 4);
3201  }
3202 
3203  return $a_value;
3204  }
3205 
3214  function groupNameExists($a_group_name,$a_id = 0)
3215  {
3216  global $ilDB,$ilErr;
3217 
3218  if (empty($a_group_name))
3219  {
3220  $message = get_class($this)."::_NameExists(): No groupname given!";
3221  $ilErr->raiseError($message,$ilErr->WARNING);
3222  }
3223 
3224  $clause = ($a_id) ? " AND obj_id != ".$ilDB->quote($a_id)." " : "";
3225 
3226  $q = "SELECT obj_id FROM object_data ".
3227  "WHERE title = ".$ilDB->quote($a_group_name)." ".
3228  "AND type = 'grp'".
3229  $clause;
3230 
3231  $r = $ilDB->query($q);
3232 
3233  if ($r->numRows())
3234  {
3235  return true;
3236  }
3237  else
3238  {
3239  return false;
3240  }
3241  }
3242 
3243  /*
3244  * get the user_ids which correspond a search string
3245  * static function
3246  * @param string search string
3247  * @access public
3248  */
3249  function searchGroups($a_search_str)
3250  {
3251  global $ilDB;
3252 
3253  $q = "SELECT * ".
3254  "FROM object_data ,object_reference ".
3255  "WHERE (object_data.title LIKE ".$ilDB->quote("%".$a_search_str."%")." ".
3256  "OR object_data.description LIKE ".$ilDB->quote("%".$a_search_str."%").") ".
3257  "AND object_data.type = 'grp' ".
3258  "AND object_data.obj_id = object_reference.obj_id ".
3259  "ORDER BY title ";
3260 
3261  $res = $ilDB->query($q);
3262 
3263  while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3264  {
3265  // STORE DATA IN ARRAY WITH KEY obj_id
3266  // SO DUPLICATE ENTRIES ( LINKED OBJECTS ) ARE UNIQUE
3267  $ids[$row->obj_id] = array(
3268  "ref_id" => $row->ref_id,
3269  "title" => $row->title,
3270  "description" => $row->description);
3271  }
3272 
3273  return $ids ? $ids : array();
3274  }
3275 
3279  function getMemString()
3280  {
3281  $my_pid = getmypid();
3282  return ("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
3283  }
3284 
3288  function isWindows()
3289  {
3290  if (strtolower(substr(php_uname(), 0, 3)) == "win")
3291  {
3292  return true;
3293  }
3294  return false;
3295  }
3296 
3297 
3298  function escapeShellArg($a_arg)
3299  {
3300  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3301  return escapeshellarg($a_arg);
3302  }
3303 
3311  public function escapeShellCmd($a_arg)
3312  {
3313  if(ini_get('safe_mode') == 1)
3314  {
3315  return $a_arg;
3316  }
3317  setlocale(LC_CTYPE, "UTF8", "en_US.UTF-8"); // fix for PHP escapeshellcmd bug. See: http://bugs.php.net/bug.php?id=45132
3318  return escapeshellcmd($a_arg);
3319  }
3320 
3321 
3322  /*
3323  * Calculates a Microsoft Excel date/time value
3324  *
3325  * Calculates a Microsoft Excel date/time value (nr of days after 1900/1/1 0:00) for
3326  * a given date and time. The function only accepts dates after 1970/1/1, because the
3327  * unix timestamp functions used in the function are starting with that date.
3328  * If you don't enter parameters the date/time value for the actual date/time
3329  * will be calculated.
3330  *
3331  * static function
3332  *
3333  * @param integer $year Year
3334  * @param integer $month Month
3335  * @param integer $day Day
3336  * @param integer $hour Hour
3337  * @param integer $minute Minute
3338  * @param integer $second Second
3339  * @return float The Microsoft Excel date/time value
3340  * @access public
3341  */
3342  function excelTime($year = "", $month = "", $day = "", $hour = "", $minute = "", $second = "")
3343  {
3344  $starting_time = mktime(0, 0, 0, 1, 2, 1970);
3345  if (strcmp("$year$month$day$hour$minute$second", "") == 0)
3346  {
3347  $target_time = time();
3348  }
3349  else
3350  {
3351  if ($year < 1970)
3352  {
3353  return 0;
3354  }
3355  }
3356  $target_time = mktime($hour, $minute, $second, $month, $day, $year);
3357  $difference = $target_time - $starting_time;
3358  $days = (($difference - ($difference % 86400)) / 86400);
3359  $difference = $difference - ($days * 86400) + 3600;
3360  return ($days + 25570 + ($difference / 86400));
3361  }
3362 
3366  function renameExecutables($a_dir)
3367  {
3368  $def_arr = explode(",", SUFFIX_REPL_DEFAULT);
3369  foreach ($def_arr as $def)
3370  {
3371  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3372  }
3373 
3374  $def_arr = explode(",", SUFFIX_REPL_ADDITIONAL);
3375  foreach ($def_arr as $def)
3376  {
3377  ilUtil::rRenameSuffix($a_dir, trim($def), "sec");
3378  }
3379  }
3380 
3391  function rRenameSuffix ($a_dir, $a_old_suffix, $a_new_suffix)
3392  {
3393  if ($a_dir == "/" || $a_dir == "" || is_int(strpos($a_dir, ".."))
3394  || trim($a_old_suffix) == "")
3395  {
3396  return false;
3397  }
3398 
3399  // check if argument is directory
3400  if (!@is_dir($a_dir))
3401  {
3402  return false;
3403  }
3404 
3405  // read a_dir
3406  $dir = opendir($a_dir);
3407 
3408  while($file = readdir($dir))
3409  {
3410  if ($file != "." and
3411  $file != "..")
3412  {
3413  // directories
3414  if (@is_dir($a_dir."/".$file))
3415  {
3416  ilUtil::rRenameSuffix($a_dir."/".$file, $a_old_suffix, $a_new_suffix);
3417  }
3418 
3419  // files
3420  if (@is_file($a_dir."/".$file))
3421  {
3422  // first check for files with trailing dot
3423  if(strrpos($file,'.') == (strlen($file) - 1))
3424  {
3425  rename($a_dir.'/'.$file,substr($a_dir.'/'.$file,0,-1));
3426  $file = substr($file,0,-1);
3427  }
3428 
3429  $path_info = pathinfo($a_dir."/".$file);
3430 
3431  if (strtolower($path_info["extension"]) ==
3432  strtolower($a_old_suffix))
3433  {
3434  $pos = strrpos($a_dir."/".$file, ".");
3435  $new_name = substr($a_dir."/".$file, 0, $pos).".".$a_new_suffix;
3436  rename($a_dir."/".$file, $new_name);
3437  }
3438  }
3439  }
3440  }
3441  return true;
3442  }
3443 
3444  function isAPICall () {
3445  return strpos($_SERVER["SCRIPT_FILENAME"],"api") !== false ||
3446  strpos($_SERVER["SCRIPT_FILENAME"],"dummy") !== false;
3447  }
3448 
3449  function KT_replaceParam($qstring, $paramName, $paramValue) {
3450  if (preg_match("/&" . $paramName . "=/", $qstring)) {
3451  return preg_replace("/&" . $paramName . "=[^&]+/", "&" . $paramName . "=" . urlencode($paramValue), $qstring);
3452  } else {
3453  return $qstring . "&" . $paramName . "=" . urlencode($paramValue);
3454  }
3455  }
3456 
3457  function replaceUrlParameterString ($url, $parametersArray) {
3458 
3459  foreach ($parametersArray as $paramName => $paramValue ) {
3460  $url = ilUtil::KT_replaceParam($url, $paramName, $paramValue);
3461  }
3462  return $url;
3463  }
3464 
3465  function generatePasswords ($a_number)
3466  {
3467  $ret = array();
3468  srand((double) microtime()*1000000);
3469 
3470  for ($i=1; $i<=$a_number; $i++)
3471  {
3472  $length = rand(6,10);
3473  $next = rand(1,2);
3474  //$chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3475  $vowels = "aeiou";
3476  $consonants = "bcdfghjklmnpqrstvwxyz";
3477  $pw = "";
3478 
3479  for ($j=0; $j < $length; $j++)
3480  {
3481  switch ($next)
3482  {
3483  case 1:
3484  $pw.= $consonants[rand(0,strlen($consonants)-1)];
3485  $next = 2;
3486  break;
3487 
3488  case 2:
3489  $pw.= $vowels[rand(0,strlen($vowels)-1)];
3490  $next = 1;
3491  break;
3492  }
3493  }
3494 
3495  $ret[] = $pw;
3496  }
3497 
3498  return $ret;
3499  }
3500 
3502  {
3503  $path = preg_replace("/[\/\\\]+$/", "", $path);
3504  return $path;
3505  }
3506 
3516  {
3517  if (empty($data))
3518  {
3519  $data = array();
3520  }
3521 
3522  foreach($data as $k=>$datum)
3523  {
3524  if(is_null($datum)) $data[$k] = 'null';
3525  if(is_string($datum)) $data[$k] = "'" . $datum . "'";
3526  if(is_array($datum)) $data[$k] = array_php2js($datum);
3527  }
3528 
3529  return "[" . implode(', ', $data) . "]";
3530  }
3531 
3536  function virusHandling($a_file, $a_orig_name = "", $a_clean = true)
3537  {
3538  global $lng;
3539 
3540  if (IL_VIRUS_SCANNER != "None")
3541  {
3542  require_once("classes/class.ilVirusScannerFactory.php");
3544  if (($vs_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3545  {
3546  if ($a_clean && (IL_VIRUS_CLEAN_COMMAND != ""))
3547  {
3548  $clean_txt = $vs->cleanFile($a_file, $a_orig_name);
3549  if ($vs->fileCleaned())
3550  {
3551  $vs_txt.= "<br />".$lng->txt("cleaned_file").
3552  "<br />".$clean_txt;
3553  $vs_txt.= "<br />".$lng->txt("repeat_scan");
3554  if (($vs2_txt = $vs->scanFile($a_file, $a_orig_name)) != "")
3555  {
3556  return array(false, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_failed").
3557  "<br />".nl2br($vs2_txt));
3558  }
3559  else
3560  {
3561  return array(true, nl2br($vs_txt)."<br />".$lng->txt("repeat_scan_succeded"));
3562  }
3563  }
3564  else
3565  {
3566  return array(false, nl2br($vs_txt)."<br />".$lng->txt("cleaning_failed"));
3567  }
3568  }
3569  else
3570  {
3571  return array(false, nl2br($vs_txt));
3572  }
3573  }
3574  }
3575 
3576  return array(true,"");
3577  }
3578 
3579 
3583  function moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors = true)
3584  {
3585  global $lng, $ilias;
3586 //echo "<br>ilUtli::moveuploadedFile($a_name)";
3587  if (!is_file($a_file))
3588  {
3589  $lng->txt("upload_error_file_not_found");
3590  }
3591 
3592  // virus handling
3593  $vir = ilUtil::virusHandling($a_file, $a_name);
3594  if (!$vir[0])
3595  {
3596  unlink($a_file);
3597  if ($a_raise_errors)
3598  {
3599  $ilias->raiseError($lng->txt("file_is_infected")."<br />".
3600  $vir[1],
3601  $ilias->error_obj->MESSAGE);
3602  }
3603  else
3604  {
3605  ilUtil::sendInfo($lng->txt("file_is_infected")."<br />".
3606  $vir[1], true);
3607  }
3608  return false;
3609  }
3610  else
3611  {
3612  if ($vir[1] != "")
3613  {
3614  ilUtil::sendInfo($vir[1], true);
3615  }
3616  return move_uploaded_file($a_file, $a_target);
3617  }
3618  }
3619 
3620 
3624  function date_mysql2time($mysql_date_time) {
3625  list($datum, $uhrzeit) = explode (" ",$mysql_date_time);
3626  list($jahr, $monat, $tag) = explode("-", $datum);
3627  list($std, $min, $sec) = explode(":", $uhrzeit);
3628  return mktime ((int) $std, (int) $min, (int) $sec, (int) $monat, (int) $tag, (int) $jahr);
3629  }
3630 
3634  function now()
3635  {
3636  return date("Y-m-d H:i:s");
3637  }
3638 
3652  function &processCSVRow(&$row, $quoteAll = FALSE, $separator = ";", $outUTF8 = FALSE, $compatibleWithMSExcel = TRUE)
3653  {
3654  $resultarray = array();
3655  foreach ($row as $rowindex => $entry)
3656  {
3657  $surround = FALSE;
3658  if ($quoteAll)
3659  {
3660  $surround = TRUE;
3661  }
3662  if (strpos($entry, "\"") !== FALSE)
3663  {
3664  $entry = str_replace("\"", "\"\"", $entry);
3665  $surround = TRUE;
3666  }
3667  if (strpos($entry, $separator) !== FALSE)
3668  {
3669  $surround = TRUE;
3670  }
3671  if ($compatibleWithMSExcel)
3672  {
3673  // replace all CR LF with LF (for Excel for Windows compatibility
3674  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
3675  }
3676  if ($surround)
3677  {
3678  if ($outUTF8)
3679  {
3680  $resultarray[$rowindex] = "\"" . $entry . "\"";
3681  }
3682  else
3683  {
3684  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
3685  }
3686  }
3687  else
3688  {
3689  if ($outUTF8)
3690  {
3691  $resultarray[$rowindex] = $entry;
3692  }
3693  else
3694  {
3695  $resultarray[$rowindex] = utf8_decode($entry);
3696  }
3697  }
3698  }
3699  return $resultarray;
3700  }
3701 
3702  // validates a domain name (example: www.ilias.de)
3703  function isDN($a_str)
3704  {
3705  return(preg_match("/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/",$a_str));
3706  }
3707 
3708  // validates an IP address (example: 192.168.1.1)
3709  function isIPv4($a_str)
3710  {
3711  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])\.".
3712  "(\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));
3713  }
3714 
3715 
3742  function _getObjectsByOperations($a_obj_type,$a_operation,$a_usr_id = 0,$limit = 0)
3743  {
3744  global $ilDB,$rbacreview,$ilAccess,$ilUser,$ilias;
3745 
3746  if(!is_array($a_obj_type))
3747  {
3748  $where = "WHERE type = ".$ilDB->quote($a_obj_type)." ";
3749  }
3750  else
3751  {
3752  $where = "WHERE type IN(";
3753  $where .= implode(",",ilUtil::quoteArray($a_obj_type));
3754  $where .= ") ";
3755  }
3756 
3757  // limit number of results default is search result limit
3758  if(!$limit)
3759  {
3760  $limit = $ilias->getSetting('search_max_hits',100);
3761  }
3762  if($limit == -1)
3763  {
3764  $limit = 10000;
3765  }
3766 
3767  // default to logged in usr
3768  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
3769  $a_roles = $rbacreview->assignedRoles($a_usr_id);
3770 
3771  // Since no rbac_pa entries are available for the system role. This function returns !all! ref_ids in the case the user
3772  // is assigned to the system role
3773  if($rbacreview->isAssigned($a_usr_id,SYSTEM_ROLE_ID))
3774  {
3775  $query = "SELECT ref_id FROM object_reference AS obr LEFT JOIN object_data AS obd USING(obj_id) ".
3776  "LEFT JOIN tree ON obr.ref_id = tree.child ".
3777  $where.
3778  "AND tree = 1";
3779 
3780  $res = $ilDB->query($query);
3781  $counter = 0;
3782  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3783  {
3784 
3785  if($counter++ >= $limit)
3786  {
3787  break;
3788  }
3789  $ref_ids[] = $row->ref_id;
3790  }
3791  return $ref_ids ? $ref_ids : array();
3792  } // End Administrators
3793 
3794  // Check ownership if it is not asked for edit_permission or a create permission
3795  if($a_operation == 'edit_permissions' or strpos($a_operation,'create') !== false)
3796  {
3797  $check_owner = ") ";
3798  }
3799  else
3800  {
3801  $check_owner = "OR owner = ".$ilDB->quote($a_usr_id).") ";
3802  }
3803 
3804  $ops_ids = ilRbacReview::_getOperationIdsByName(array($a_operation));
3805  $ops_id = $ops_ids[0];
3806 
3807  $and = "AND ((rol_id IN(".implode(",",ilUtil::quoteArray($a_roles)).") ";
3808 
3809  $query = "SELECT DISTINCT(obr.ref_id),obr.obj_id,type FROM object_reference AS obr ".
3810  "JOIN object_data AS obd ON obd.obj_id = obr.obj_id ".
3811  "JOIN rbac_pa ON obr.ref_id = rbac_pa.ref_id ".
3812  $where.
3813  $and.
3814  "AND (ops_id LIKE ".$ilDB->quote("%i:".$ops_id."%"). " ".
3815  "OR ops_id LIKE".$ilDB->quote("%:\"".$ops_id."\";%").")) ".
3816  $check_owner;
3817 
3818  $res = $ilDB->query($query);
3819  $counter = 0;
3820  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
3821  {
3822  if($counter >= $limit)
3823  {
3824  break;
3825  }
3826  // Check deleted, hierarchical access ...
3827  if($ilAccess->checkAccessOfUser($a_usr_id,$a_operation,'',$row->ref_id,$row->type,$row->obj_id))
3828  {
3829  $counter++;
3830  $ref_ids[] = $row->ref_id;
3831  }
3832  }
3833  return $ref_ids ? $ref_ids : array();
3834  }
3835 
3842  function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
3843  {
3844  global $tpl, $lng, $ilUser;
3845 
3846 //echo "<br><br>".htmlentities($a_text);
3847 //echo "<br>-".htmlentities($a_start)."-".htmlentities($a_end)."-";
3848 
3849  // - take care of html exports (-> see buildLatexImages)
3850  include_once "./Services/Administration/classes/class.ilSetting.php";
3851  $jsMathSetting = new ilSetting("jsMath");
3852  $use_jsmath =
3853  $jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault"))));
3854 
3855  if ($use_jsmath)
3856  {
3857  $info = "";
3858  if (!$tpl->out_jsmath_info)
3859  {
3860  include_once "./classes/class.ilTemplate.php";
3861  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
3862  $lng->loadLanguageModule("jsmath");
3863  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
3864  $info = $template->get();
3865  $tpl->out_jsmath_info = TRUE;
3866  }
3867  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
3868  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
3869  }
3870 
3871  // this is a fix for bug5362
3872  $cpos = 0;
3873  $o_start = $a_start;
3874  $o_end = $a_end;
3875  $a_start = str_replace("\\", "", $a_start);
3876  $a_end = str_replace("\\", "", $a_end);
3877  /*$a_start = str_replace("\]", "]", $a_start);
3878  $a_start = str_replace("\[", "[", $a_start);
3879  $a_end = str_replace("\]", "]", $a_end);
3880  $a_end = str_replace("\[", "[", $a_end);
3881  $a_end = str_replace("\/", "/", $a_end);*/
3882 
3883  while (is_int($spos = stripos($a_text, $a_start, $cpos))) // find next start
3884  {
3885  if (is_int ($epos = stripos($a_text, $a_end, $spos + 1)))
3886  {
3887  $tex = substr($a_text, $spos + strlen($a_start), $epos - $spos - strlen($a_start));
3888 
3889  // replace, if tags do not go across div borders
3890  if (!is_int(strpos($tex, "</div>")))
3891  {
3892  if (!$use_jsmath)
3893  {
3894  $a_text = substr($a_text, 0, $spos).
3895  "<img alt=\"".htmlentities($tex)."\" src=\"".$a_cgi."?".
3896  rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', $tex))))."\" ".
3897  " />".
3898  substr($a_text, $epos + strlen($a_end));
3899  }
3900  else
3901  {
3902  $tex = $a_start.$tex.$a_end;
3903 //echo "<br>1:".$tex;
3904  $replacement =
3905  preg_replace('/' . $o_start . '(.*?)' . $o_end . '/ie',
3906  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $tex);
3907  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
3908 //echo "<br>2:".htmlentities($replacement);
3909  $a_text = substr($a_text, 0, $spos).
3910  $replacement.
3911  substr($a_text, $epos + strlen($a_end));
3912  }
3913  }
3914  }
3915  $cpos = $spos + 1;
3916  }
3917 
3918  if ($use_jsmath)
3919  {
3920  $a_text = str_replace("[[info]]", $info, $a_text);
3921  }
3922 
3923  $result_text = $a_text;
3924 
3925 // $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
3926 // "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
3927 // " />'", $a_text);
3928 
3929 //echo "<br>".htmlentities($a_text);
3930 
3931  return $result_text;
3932  }
3933 
3934 
3941 /* function insertLatexImages($a_text, $a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
3942  {
3943  global $tpl, $lng, $ilUser;
3944 
3945 //echo "<br><br>".htmlentities($a_text);
3946 //echo "<br>-".htmlentities($a_start)."-".htmlentities($a_end)."-";
3947 
3948  // - take care of html exports (-> see buildLatexImages)
3949  include_once "./Services/Administration/classes/class.ilSetting.php";
3950  $jsMathSetting = new ilSetting("jsMath");
3951  if ($jsMathSetting->get("enable") && ($ilUser->getPref("js_math") || ($ilUser->getPref("js_math") === FALSE && ($jsMathSetting->get("makedefault")))))
3952  {
3953  $info = "";
3954  if (!$tpl->out_jsmath_info)
3955  {
3956  include_once "./classes/class.ilTemplate.php";
3957  $template = new ilTemplate("tpl.jsmath_warning.html", TRUE, TRUE);
3958  $lng->loadLanguageModule("jsmath");
3959  $template->setVariable("TEXT_JSMATH_NO_JAVASCRIPT", $lng->txt("jsmath_no_javascript"));
3960  $info = $template->get();
3961  $tpl->out_jsmath_info = TRUE;
3962  }
3963  $a_text = preg_replace("/\\\\([RZN])([^a-zA-Z]|<\/span>)/", "\\mathbb{"."$1"."}"."$2", $a_text);
3964  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
3965  "'<span class=\"math\">' . preg_replace('/[\\\\\\\\\\]{2}/', '\\cr', str_replace('<', '&lt;', str_replace('<br/>', '', str_replace('<br />', '', str_replace('<br>', '', '$1'))))) . '</span>[[info]]'", $a_text);
3966  // added special handling for \\ -> \cr, < -> $lt; and removal of <br/> tags in jsMath expressions, H. Schottmüller, 2007-09-09
3967  $result_text = str_replace("[[info]]", $info, $result_text);
3968  $tpl->addJavaScript($jsMathSetting->get("path_to_jsmath") . "/easy/load.js");
3969  }
3970  else
3971  {
3972  $result_text = preg_replace('/' . $a_start . '(.*?)' . $a_end . '/ie',
3973  "'<img alt=\"'.htmlentities('$1').'\" src=\"$a_cgi?'.rawurlencode(str_replace('&amp;', '&', str_replace('&gt;', '>', str_replace('&lt;', '<', '$1')))).'\" ".
3974  " />'", $a_text);
3975  }
3976 
3977 echo "<br>".htmlentities($result_text);
3978 
3979  return $result_text;
3980  }
3981 */
3982 
3983 
3990  function buildLatexImages($a_text, $a_dir ,$a_start = "\[tex\]", $a_end = "\[\/tex\]", $a_cgi = URL_TO_LATEX)
3991  {
3992  $result_text = $a_text;
3993 
3994  if ($a_cgi != "")
3995  {
3996  while (preg_match('/' . $a_start . '(.*?)' . $a_end . '/ie', $result_text, $found))
3997  {
3998  $cnt = (int) $GLOBALS["teximgcnt"]++;
3999  // get image from cgi and write it to file
4000  $fpr = @fopen($a_cgi."?".rawurlencode($found[1]), "r");
4001  $lcnt = 0;
4002  if ($fpr)
4003  {
4004  while(!feof($fpr))
4005  {
4006  $buf = fread($fpr, 1024);
4007  if ($lcnt == 0)
4008  {
4009  if (is_int(strpos(strtoupper(substr($buf, 0, 5)), "GIF")))
4010  {
4011  $suffix = "gif";
4012  }
4013  else
4014  {
4015  $suffix = "png";
4016  }
4017  $fpw = fopen($a_dir."/teximg/img".$cnt.".".$suffix, "w");
4018  }
4019  $lcnt++;
4020  fwrite($fpw, $buf);
4021  }
4022  fclose($fpw);
4023  fclose($fpr);
4024  }
4025 
4026  // replace tex-tag
4027  $img_str = "./teximg/img".$cnt.".".$suffix;
4028  $result_text = str_replace($found[0],
4029  '<img alt="'.$found[1].'" src="'.$img_str.'" />', $result_text);
4030  }
4031  }
4032 
4033  return $result_text;
4034  }
4035 
4043  function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE)
4044  {
4045  $result = $txt_output;
4046  $is_html = $this->isHTML($result);
4047  if ($prepare_for_latex_output)
4048  {
4049  $result = ilUtil::insertLatexImages($result, "<span class\=\"latex\">", "<\/span>", URL_TO_LATEX);
4050  $result = ilUtil::insertLatexImages($result, "\[tex\]", "\[\/tex\]", URL_TO_LATEX);
4051  }
4052 
4053  // removed: did not work with magic_quotes_gpc = On
4054  if (!$is_html)
4055  {
4056  // if the string does not contain HTML code, replace the newlines with HTML line breaks
4057  $result = preg_replace("/[\n]/", "<br />", $result);
4058  }
4059  else
4060  {
4061  // patch for problems with the <pre> tags in tinyMCE
4062  if (preg_match_all("/(<pre>.*?<\/pre>)/ims", $result, $matches))
4063  {
4064  foreach ($matches[0] as $found)
4065  {
4066  $replacement = "";
4067  if (strpos("\n", $found) === FALSE)
4068  {
4069  $replacement = "\n";
4070  }
4071  $removed = preg_replace("/<br\s*?\/>/ims", $replacement, $found);
4072  $result = str_replace($found, $removed, $result);
4073  }
4074  }
4075  }
4076  if ($prepare_for_latex_output)
4077  {
4078  // replace special characters to prevent problems with the ILIAS template system
4079  // eg. if someone uses {1} as an answer, nothing will be shown without the replacement
4080  $result = str_replace("{", "&#123;", $result);
4081  $result = str_replace("}", "&#125;", $result);
4082  $result = str_replace("\\", "&#92;", $result);
4083  }
4084  return $result;
4085  }
4086 
4087 
4094  function int2array ($seconds, $periods = null)
4095  {
4096  // Define time periods
4097  if (!is_array($periods))
4098  {
4099  $periods = array (
4100  'years' => 31536000,
4101  'months' => 2592000,
4102  'days' => 86400,
4103  'hours' => 3600,
4104  'minutes' => 60,
4105  'seconds' => 1
4106  );
4107  }
4108 
4109  // Loop
4110  $seconds = (float) $seconds;
4111  foreach ($periods as $period => $value)
4112  {
4113  $count = floor($seconds / $value);
4114 
4115  if ($count == 0)
4116  {
4117  continue;
4118  }
4119 
4120  $values[$period] = $count;
4121  $seconds = $seconds % $value;
4122  }
4123  // Return
4124  if (empty($values))
4125  {
4126  $values = null;
4127  }
4128 
4129  return $values;
4130  }
4131 
4138  function timearray2string ($duration)
4139  {
4140  global $lng;
4141 
4142  if (!is_array($duration))
4143  {
4144  return false;
4145  }
4146 
4147  foreach ($duration as $key => $value) {
4148 
4149  // Plural
4150  if ($value > 1)
4151  {
4152  $segment_name = $key;
4153  $segment_name = $lng->txt($segment_name);
4154  $segment = $value . ' ' . $segment_name;
4155  }
4156  else
4157  {
4158  $segment_name = substr($key, 0, -1);
4159  $segment_name = $lng->txt($segment_name);
4160  $segment = $value . ' ' . $segment_name;
4161  }
4162 
4163  $array[] = $segment;
4164  }
4165  $len = count($array);
4166 
4167  if ($len>3)
4168  {
4169  $array=array_slice($array,0,(3-$len));
4170  }
4171 
4172  $str = implode(', ', $array);
4173 
4174  return $str;
4175  }
4176 
4177  function getFileSizeInfo()
4178  {
4179  global $lng;
4180 
4181  // get the value for the maximal uploadable filesize from the php.ini (if available)
4182  $umf=get_cfg_var("upload_max_filesize");
4183  // get the value for the maximal post data from the php.ini (if available)
4184  $pms=get_cfg_var("post_max_size");
4185 
4186  // use the smaller one as limit
4187  $max_filesize=min($umf, $pms);
4188  if (!$max_filesize) $max_filesize=max($umf, $pms);
4189 
4190  return $lng->txt("file_notice")." $max_filesize.";
4191  }
4192 
4199  function __extractRefId($role_title)
4200  {
4201 
4202  $test_str = explode('_',$role_title);
4203 
4204  if ($test_str[0] == 'il')
4205  {
4206  $test2 = (int) $test_str[3];
4207  return is_numeric ($test2) ? (int) $test2 : false;
4208  }
4209  return false;
4210  }
4211 
4221  function __extractId($ilias_id, $inst_id)
4222  {
4223 
4224  $test_str = explode('_',$ilias_id);
4225 
4226  if ($test_str[0] == 'il' && $test_str[1] == $inst_id && count($test_str) == 4)
4227  {
4228  $test2 = (int) $test_str[3];
4229  return is_numeric ($test2) ? (int) $test2 : false;
4230  }
4231  return false;
4232  }
4233 
4246  function _sortIds($a_ids,$a_table,$a_field,$a_id_name)
4247  {
4248  global $ilDB;
4249 
4250  if(!$a_ids)
4251  {
4252  return array();
4253  }
4254 
4255  // use database to sort user array
4256  $where = "WHERE ".$a_id_name." IN (";
4257  $where .= implode(",", ilUtil::quoteArray($a_ids));
4258  $where .= ") ";
4259 
4260  $query = "SELECT ".$a_id_name." FROM ".$a_table." ".
4261  $where.
4262  "ORDER BY ".$a_field;
4263 
4264  $res = $ilDB->query($query);
4265  while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
4266  {
4267  $ids[] = $row->$a_id_name;
4268  }
4269  return $ids ? $ids : array();
4270  }
4271 
4279  function getMySQLTimestamp($a_ts)
4280  {
4281  global $ilDB;
4282 
4283  if ($ilDB->isMysql4_1OrHigher())
4284  {
4285  return $a_ts;
4286  }
4287  else
4288  {
4289  $t = $a_ts;
4290  $ts = substr($t, 0, 4)."-".substr($t, 4, 2)."-".substr($t, 6, 2).
4291  " ".substr($t, 8, 2).":".substr($t, 10, 2).":".substr($t, 12, 2);
4292  return $ts;
4293  }
4294  }
4295 
4299  function quoteArray($a_array)
4300  {
4301  global $ilDB;
4302 
4303 
4304  if(!is_array($a_array) or !count($a_array))
4305  {
4306  return array("''");
4307  }
4308 
4309  foreach($a_array as $k => $item)
4310  {
4311  $a_array[$k] = $ilDB->quote($item);
4312  }
4313 
4314  return $a_array;
4315  }
4316 
4325  function sendInfo($a_info = "",$a_keep = false)
4326  {
4327  global $tpl;
4328 
4329  if (!empty($a_info))
4330  {
4331  $_SESSION["info"] = $a_info;
4332  }
4333  if (!empty($_SESSION["info"]))
4334  {
4335  $tpl->addBlockFile("MESSAGE", "message", "tpl.message.html");
4336  # $tpl->setCurrentBlock("message");
4337  $tpl->setVariable("INFO",$_SESSION["info"]);
4338  # $tpl->parseCurrentBlock();
4339  }
4340 
4341  if (!$a_keep)
4342  {
4343  session_unregister("info");
4344  }
4345  }
4346 
4347  function infoPanel($a_keep = true)
4348  {
4349  global $tpl,$ilias,$lng;
4350 
4351  if (!empty($_SESSION["infopanel"]) and is_array($_SESSION["infopanel"]))
4352  {
4353  $tpl->addBlockFile("INFOPANEL", "infopanel", "tpl.infopanel.html");
4354  $tpl->setCurrentBlock("infopanel");
4355 
4356  if (!empty($_SESSION["infopanel"]["text"]))
4357  {
4358  $link = "<a href=\"".$dir.$_SESSION["infopanel"]["link"]."\" target=\"".
4359  ilFrameTargetInfo::_getFrame("MainContent").
4360  "\">";
4361  $link .= $lng->txt($_SESSION["infopanel"]["text"]);
4362  $link .= "</a>";
4363  }
4364 
4365  // deactivated
4366  if (!empty($_SESSION["infopanel"]["img"]))
4367  {
4368  $link .= "<td><a href=\"".$_SESSION["infopanel"]["link"]."\" target=\"".
4369  ilFrameTargetInfo::_getFrame("MainContent").
4370  "\">";
4371  $link .= "<img src=\"".$ilias->tplPath.$ilias->account->prefs["skin"]."/images/".
4372  $_SESSION["infopanel"]["img"]."\" border=\"0\" vspace=\"0\"/>";
4373  $link .= "</a></td>";
4374  }
4375 
4376  $tpl->setVariable("INFO_ICONS",$link);
4377  $tpl->parseCurrentBlock();
4378  }
4379 
4380  //if (!$a_keep)
4381  //{
4382  session_unregister("infopanel");
4383  //}
4384  }
4385 
4386 
4393  function dirsize($directory)
4394  {
4395  $size = 0;
4396  if (!is_dir($directory))
4397  {
4398  // BEGIN DiskQuota Suppress PHP warning when attempting to determine
4399  // dirsize of non-existing directory
4400  $size = @filesize($directory);
4401  // END DiskQuota Suppress PHP warning.
4402  return ($size === false) ? -1 : $size;
4403  }
4404  if ($DIR = opendir($directory))
4405  {
4406  while (($dirfile = readdir($DIR)) !== false)
4407  {
4408  if (is_link($directory . DIRECTORY_SEPARATOR . $dirfile) || $dirfile == '.' || $dirfile == '..')
4409  continue;
4410  if (is_file($directory . DIRECTORY_SEPARATOR . $dirfile))
4411  $size += filesize($directory . DIRECTORY_SEPARATOR . $dirfile);
4412  else if (is_dir($directory . DIRECTORY_SEPARATOR . $dirfile))
4413  {
4414  // BEGIN DiskQuota: dirsize is not a global function anymore
4415  $dirSize = ilUtil::dirsize($directory . DIRECTORY_SEPARATOR . $dirfile);
4416  // END DiskQuota: dirsize is not a global function anymore
4417  if ($dirSize >= 0)
4418  $size += $dirSize;
4419  else return -1;
4420  }
4421  }
4422  closedir($DIR);
4423  }
4424  return $size;
4425  }
4426 
4427  function randomhash()
4428  {
4429  return md5(rand(1,9999999) + str_replace(" ", "", (string) microtime()));
4430  }
4431 
4432  public static function _sanitizeFilemame($a_filename)
4433  {
4434  return strip_tags($a_filename);
4435  }
4436 } // END class.ilUtil
4437 
4438 
4439 ?>