EGOCMS  18.0
EGOTEC Content-Managament-System
Ego_System.php
gehe zur Dokumentation dieser Datei
1 <?php
15 {
20  // Für die Verwendung ohne Delimiter
21  const REGEX_EMAIL = '^[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$';
22  // Für die Verwendung ohne Delimiter (und optional)
23  const REGEX_EMAIL_OPTIONAL = '^(|[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$';
24  // Für die Verwendung mit / Delimiter
25  const REGEX_EMAIL_ESCAPED = '^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$';
26 
27  // Das Admin Design
28  const ADMIN_SKIN = 'egotec';
29 
30  // Maximale Anzahl an Clusterservern
31  const MAX_CLUSTER = 10;
32 
33  // Alle zum System gehörigen Dateien
34  public static $fileList = array(
35  'admin.php',
36  'favicon.ico',
37  'rewrite.php',
38  'json.php',
39  'url.php',
40  'robots.txt'
41  );
42 
49  private static $includedHtml = array();
50 
57  public static function isEmail($email) {
58  return (bool) preg_match('/'.self::REGEX_EMAIL_ESCAPED.'/msi', $email);
59  }
60 
69  public static function escape($string, $esc_type = 'html', $char_set = 'UTF-8') {
70  switch ($esc_type) {
71  case 'html':
72  return htmlspecialchars($string, ENT_QUOTES, $char_set);
73 
74  case 'htmlall':
75  return htmlentities($string, ENT_QUOTES, $char_set);
76 
77  case 'url':
78  return rawurlencode($string);
79 
80  case 'urlpathinfo':
81  return str_replace('%2F','/',rawurlencode($string));
82 
83  case 'quotes':
84  // escape unescaped single quotes
85  return preg_replace("%(?<!\\\\)'%", "\\'", $string);
86 
87  case 'hex':
88  // escape every character into hex
89  $return = '';
90  for ($x=0; $x < strlen($string); $x++) {
91  $return .= '%' . bin2hex($string[$x]);
92  }
93  return $return;
94 
95  case 'hexentity':
96  $return = '';
97  for ($x=0; $x < strlen($string); $x++) {
98  $return .= '&#x' . bin2hex($string[$x]) . ';';
99  }
100  return $return;
101 
102  case 'decentity':
103  $return = '';
104  for ($x=0; $x < strlen($string); $x++) {
105  $return .= '&#' . ord($string[$x]) . ';';
106  }
107  return $return;
108 
109  case 'javascript':
110  // escape quotes and backslashes, newlines, etc.
111  return strtr($string, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
112 
113  case 'mail':
114  // safe way to display e-mail address on a web page
115  return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $string);
116 
117  case 'nonstd':
118  // escape non-standard chars, such as ms document quotes
119  $_res = '';
120  for($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) {
121  $_ord = ord(substr($string, $_i, 1));
122  // non-standard char, escape it
123  if($_ord >= 126){
124  $_res .= '&#' . $_ord . ';';
125  }
126  else {
127  $_res .= substr($string, $_i, 1);
128  }
129  }
130  return $_res;
131  }
132  return $string;
133  }
134 
135  public static $allSites = array();
136 
143  public static function clearTypeCache($site_name = '') {
144  Ego_System::mkdir($GLOBALS['egotec_conf']['cache_dir']); // Falls das Cache Verzeichnis noch nicht existiert erzeugen.
145  $cache_dir = dir($GLOBALS['egotec_conf']['cache_dir']);
146  if ($cache_dir) {
147  while ($dir = $cache_dir->read()) {
148  if (
149  $dir[0] != '.'
150  && is_dir($cache_dir->path.$dir)
151  && (!$site_name || $dir == $site_name)
152  ) {
153  foreach (glob($cache_dir->path.$dir.'/types*') as $file) {
154  @unlink($file);
155  }
156  @unlink($cache_dir->path.$dir.'/classes.cache');
157  }
158  }
159  $cache_dir->close();
160  }
161  }
162 
166  public static function clearCache()
167  {
168  Ego_System::deldir($GLOBALS['egotec_conf']['cache_dir'], false);
170  Ego_System::mkdir($GLOBALS['egotec_conf']['cache_dir'].'compiled'.DIRECTORY_SEPARATOR.'_admin');
171  $path = '/';
172  switch ($GLOBALS['egotec_conf']['site_cache_type'])
173  {
174  case 'apcu':
175  require_once('base/Ego_Cache_apcu.php');
176  $cache = new Ego_Cache_apcu($path);
177 
178  $cache->reset();
179  break;
180  case 'apc':
181  require_once('base/Ego_Cache_apc.php');
182  $cache = new Ego_Cache_apc($path);
183 
184  $cache->reset();
185  break;
186  case 'shm':
187  require_once('base/Ego_Cache_shm.php');
188  $cache = new Ego_Cache_shm($path);
189  $cache->reset();
190  break;
191  default:
192  require_once('base/Ego_Cache_file.php');
193  $cache = new Ego_Cache_file($path);
194  $cache->reset();
195  }
196 
197  // Allgemeine Cache löschen
198  $cache = self::getCache();
199  $cache->reset();
200  }
201 
205  public static function clearNginxCache()
206  {
207  Ego_System::deldir($GLOBALS['egotec_conf']['var_dir'].'cachenginx', false);
208  }
209 
210  public static function clearMediaCache()
211  {
212  Ego_System::deldir($GLOBALS['egotec_conf']['cachemedia_dir'], false);
213  Ego_System::mkdir($GLOBALS['egotec_conf']['cachemedia_dir']);
214  $path = '/';
215  switch ($GLOBALS['egotec_conf']['site_cache_type'])
216  {
217  case 'apc':
218  require_once('base/Ego_Cache_apc.php');
219  $cache = new Ego_Cache_apc($path);
220  $cache->reset();
221  break;
222  case 'apcu':
223  require_once('base/Ego_Cache_apcu.php');
224  $cache = new Ego_Cache_apcu($path);
225  $cache->reset();
226  break;
227  case 'shm':
228  require_once('base/Ego_Cache_shm.php');
229  $cache = new Ego_Cache_shm($path);
230  $cache->reset();
231  break;
232  default:
233  require_once('base/Ego_Cache_file.php');
234  $cache = new Ego_Cache_file($path);
235  $cache->reset();
236  }
237  }
238 
239 
243  public static function clearCacheAllSites()
244  {
245  require_once('base/Site.php');
246  $dir = dir($GLOBALS['egotec_conf']['site_dir']);
247  while ($file = $dir->read())
248  {
249  if ($file['0']!='.' && is_dir($dir->path.$file))
250  {
251  try {
252  $site = new Site($file);
253  foreach ($site->getLanguages() as $lang)
254  {
255  $site->setLanguage($lang);
256  $site->clearCache();
257  }
258  } catch (Exception $e)
259  { // Verzeichnisse, die keinen Mandanten repräsentieren, ignorieren.
260  ;
261  }
262  }
263  }
265  }
266 
275  public static function pathinfo($string)
276  {
277  // pathinfo macht Probleme bei Umlauten als erstes Zeichen im Dateinamen.
278  $pos = strrpos($string, '/');
279  if ($pos === false)
280  {
281  $pos = strrpos($string, DIRECTORY_SEPARATOR);
282  }
283 
284  if ($pos === false)
285  {// Es taucht weder / noch \ auf
286  $string = ' '.$string;
287  } else {
288  $pos = ((int)$pos)+1;
289  $string = substr($string, 0, $pos).' '.substr($string, $pos);
290  }
291 
292  $result = pathinfo($string);
293  foreach($result as $key => $value)
294  {
295  $result[$key] = ltrim($value);
296  }
297  return $result;
298  }
299 
306  public static function basename($path)
307  {
308  $pathinfo = Ego_System::pathinfo($path);
309  return $pathinfo['basename'];
310  }
311 
320  public static function filterNonUtf8($s, $substitute = "", $strict = false)
321  {
322  if (!$substitute) {
323  $substitute = "\xEF\xBF\xBD";
324  }
325 
326  // Diese Funktion ist nicht Oracle kompatibel
327  if (
328  Ego_System::getDbDriver() == 'oci'
329  || $GLOBALS['egotec_conf']['noutf8filter'] == 1
330  ) {
331  return $s;
332  }
333 
334  if ($strict) {
335  // From http://stackoverflow.com/a/13695364 (ohne \xF0, \xE1)
336  $utf8_pattern = '/
337 ([\n\r\t\x20-\x7F]
338 |[\xC2-\xDF][\x80-\xBF]
339 | \xE0[\xA0-\xBF][\x80-\xBF]
340 | \xED[\x80-\x9F][\x80-\xBF]
341 |[\xF1-\xF3][\x80-\xBF]{3}
342 | \xF4[\x80-\x8F][\x80-\xBF]{2})
343 |(\xE0[\xA0-\xBF]
344 | \xED[\x80-\x9F]
345 |[\xF1-\xF3][\x80-\xBF]{1,2}
346 | \xF4[\x80-\x8F][\x80-\xBF]?)
347 /xs';
348  } else {
349  // From http://stackoverflow.com/a/13695364
350  $utf8_pattern = '/
351 ([\n\r\t\x20-\x7F]
352 |[\xC2-\xDF][\x80-\xBF]
353 | \xE0[\xA0-\xBF][\x80-\xBF]
354 |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
355 | \xED[\x80-\x9F][\x80-\xBF]
356 | \xF0[\x90-\xBF][\x80-\xBF]{2}
357 |[\xF1-\xF3][\x80-\xBF]{3}
358 | \xF4[\x80-\x8F][\x80-\xBF]{2})
359 |(\xE0[\xA0-\xBF]
360 |[\xE1-\xEC\xEE\xEF][\x80-\xBF]
361 | \xED[\x80-\x9F]
362 | \xF0[\x90-\xBF][\x80-\xBF]?
363 |[\xF1-\xF3][\x80-\xBF]{1,2}
364 | \xF4[\x80-\x8F][\x80-\xBF]?)
365 /xs';
366  }
367 
368  // String der nur Utf8 Zeichen beinhaltet
369  $utf8_string = '';
370 
371  do {
372  $s2 = mb_substr($s, 0, 1000);
373  preg_replace_callback($utf8_pattern, function($matches) use ($substitute, &$utf8_string) {
374  if (isset($matches[2]) || isset($matches[3])) {
375  $utf8_string .= $substitute;
376  }
377  $utf8_string .= $matches[1];
378  return '';
379  }, $s2);
380  $s = mb_substr($s, 1000);
381  } while ($s);
382  return str_replace("\xe2\x80".chr(168), " ", $utf8_string);
383  }
384 
391  public static function filterData($data)
392  {
393  if(is_array($data))
394  {
395  foreach($data as $key => $value)
396  {
397  if(is_array($value) || is_string($value))
398  {
399  $data[$key] = is_array($value) ? self::filterData($value) : self::filterNonUtf8($value);
400  }
401  }
402 
403  return $data;
404  }
405  else
406  {
407  return (is_string($data) ? self::filterNonUtf8($data) : $data);
408  }
409  }
410 
420  public static function checkEncoding($from='CP1252', $to='UTF-8', $original, $converted)
421  {
422  $converted2 = iconv($to, $from, $converted);
423  $converted2 = Ego_System::filterNonUtf8($converted2);
424  $original = Ego_System::filterNonUtf8($original);
425  if ($original === $converted2)
426  {
427  return true;
428  } else {
429  return false;
430  }
431  }
432 
448  public static function stringEncode($string, $from='UTF-8', $to='UTF-8')
449  {
450  if ($string == '') return $string;
451 
452  $source_encoding = array(
453  'CP1250','CP1251','CP1252','CP1253','CP1254','CP1255','CP1256','CP1257', //Weitere gängige Windows-Zeichensätze
454  'ISO-8859-2','ISO-8859-5','ISO-8859-1','ISO-8859-7','ISO-8859-9','ISO-8859-8','ISO-8859-6','ISO-8859-4', //Weitere gängige ISO-Zeichensätze
455  );
456 
457  $original = $string;
458  $converted = iconv($from, $to, $string);
459  $converted = Ego_System::filterNonUtf8($converted);
460 
461  if (Ego_System::checkEncoding($from, $to, $original, $converted))
462  {
463  return $converted;
464  } else {
465  foreach($source_encoding as $from)
466  {
467  $converted = iconv($from, $to, $string);
468  $converted = Ego_System::filterNonUtf8($converted);
469  if (Ego_System::checkEncoding($from, $to, $original, $converted))
470  {
471  return $converted;
472  }
473  }
474  return "Die Zeichenkette konnte leider nicht korrekt in UTF-8 umgewandelt werden.";
475  }
476  }
477 
484  public static function dateEncode($string) {
485  return strtotime($string);
486  }
487 
497  public static function mkdir($dir, $mode = 0755, $recursive = true)
498  {
499  $mode = $GLOBALS['egotec_conf']['chmod'] ? octdec($GLOBALS['egotec_conf']['chmod']) : $mode;
500  $dir = strtr($dir, '\\/', DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR);
501  $dir = str_replace('/./', '/', $dir);
502  clearstatcache();
503  if (!is_dir($dir))
504  {
505  if (@mkdir($dir, $mode, $recursive))
506  {
507  @chmod($dir, $mode);
508  clearstatcache();
509  return true;
510  } else {
511  if ($GLOBALS['egotec_conf']['mkdir_warning']) {
512  egotec_warning_log('Filesystem-Fehler beim Anlegen von '.$dir."\n\n".get_backtrace(0));
513  } else {
514  throw new Exception('Filesystem-Fehler beim Anlegen von '.$dir);
515  }
516  }
517  }
518  return false;
519  }
520 
546  public static function parseUrl($url)
547  {
548  $info = array();
549 
550  $parse_url = @parse_url($url);
551  $info['protokoll'] = $parse_url['scheme'];
552  $info['host'] = $parse_url['host'];
553  $info['port'] = $parse_url['port'];
554  $info['pfad'] = dirname($parse_url['path']);
555  $info['datei'] = basename($parse_url['path']);
556  $info['query'] = str_replace('&amp;','&',$parse_url['query']);
557  $info['mark'] = $parse_url['fragment'];
558  foreach (explode('&',$info['query']) as $param_pair)
559  {
560  $key = strtok($param_pair,'=');
561  $value = strtok('=');
562  $info['parameter'][$key] = $value;
563  }
564  $info['parse_url'] = $parse_url;
565 
566  return $info;
567  }
568 
593  public static function deldir($location, $del=true, $without='',$rename=true)
594  {
595  if (!$location)
596  {
597  throw new Exception('deldir needs location not to be empty.');
598  }
599  set_time_limit(0);
600  if (substr($location,-1) != '/')
601  {
602  $location = $location.'/';
603  }
604  $location = strtr($location, '/', DIRECTORY_SEPARATOR);
605  if (is_dir($location))
606  {
607  $error = "Filesystem-Fehler beim Löschen von ".$location;
608 
609  if ($without)
610  { // Wenn Dateien oder Verzeichnisse beim löschen ausgelassen werden sollen,
611  $rename = false; // dann kann kein rename vorgenommen werden.
612  }
613 
614  $location = strtr($location, '/', DIRECTORY_SEPARATOR);
615  if (substr($location,-1) != DIRECTORY_SEPARATOR)
616  {
617  $location.= DIRECTORY_SEPARATOR;
618  }
619 
620  if (!Ego_System::file_exists($location))
621  {
622  return false;
623  }
624  if ($rename)
625  {
626  $tmp = $GLOBALS['egotec_conf']['tmp_dir'].'deldir_'.md5(microtime()).DIRECTORY_SEPARATOR;
627  while (Ego_System::file_exists($tmp))
628  {
629  $tmp = $GLOBALS['egotec_conf']['tmp_dir'].'deldir_'.md5(microtime()).DIRECTORY_SEPARATOR;
630  }
631  if (@rename($location,$tmp) === false)
632  { // Wenn verschieben nicht klappt, Unterverzeichnisse direkt löschen
633  if (is_dir($location))
634  {
635  $dir = dir($location);
636  while ($file = $dir->read())
637  {
638  if ($file[0]!='.')
639  {
640  if (is_dir($dir->path.$file)) {
641  self::deldir($dir->path.$file, true, '', false);
642  } else {
643  @unlink($dir->path.$file);
644  }
645  }
646  }
647  @rmdir($location);
648  return true;
649  }
650  }
651  if (!$del)
652  {//Soll das Verzeichnis selbst nicht gelöscht werden, muss es wieder erstellt werden
653  Ego_System::mkdir($location);
654  }
655  $location = $tmp;
656  }
657  $directory = dir($location);
658  $without_nodel = false; // Falls eine Ausnahme im Verzeichnis zurückbleibt, kann das Verzeichnis nicht gelöscht werden.
659  while (is_object($directory) && false !== ($file = $directory->read())) // #144288 : Hotfix, da es hier zu Abbrüchen kam, wegen fehlendem Objekt
660  {
661  set_time_limit(0);
662  if (! ( $without && $without[$file] ))
663  {
664  if (is_dir($directory->path.$file) && $file != '..' && $file != '.')
665  {
666  Ego_System::deldir($directory->path.$file, true, $without, false);
667  unset($file);
668  } elseif (is_file($directory->path.DIRECTORY_SEPARATOR.$file))
669  {
670  if (unlink($directory->path.$file) === false) throw new Exception($error);
671  unset($file);
672  }
673  } else {
674  $without_nodel = true; // Falls eine Ausnahme im Verzeichnis zurückbleibt, kann das Verzeichnis nicht gelöscht werden.
675  }
676  }
677  if (is_object($directory)) $directory->close(); // #144288 : Hotfix, da es hier zu Abbrüchen kam, wegen fehlendem Objekt
678  if ( !$without_nodel && false !== $del )
679  {
680  if ($rename)
681  {
682  Ego_System::deldir($location, true, '', false);
683  } else {
684  $pwd = getcwd();
685  chdir($GLOBALS['egotec_conf']['egotec_dir']);
686  $result = @rmdir($location);
687  @chdir($pwd);
688  if ($result)
689  {
690  return true;
691  } else {
692  throw new Exception($error);
693  }
694  }
695  }
696  } elseif (is_file($location)) {
697  @unlink($location);
698  return true;
699  }
700  return false;
701  }
702 
709  public static function flushHeaders($headers)
710  {
711  foreach ($headers as $key => $value)
712  {
713  header($key.': '.$value);
714  $GLOBALS['egotec']['response_headers'][$key] = $value;
715  }
716  }
717 
724  public static function flush($string = '') {
725  if ($GLOBALS['live_system_migrate']) {
726  // Bei system_migrate über SOAP wird die Ausgabe zwischengespeichert
727  $GLOBALS['_output'] .= $string;
728  } else {
729  while (ob_get_level()) {
730  ob_end_flush();
731  }
732  ob_start();
733  if ($string) {
734  echo $string;
735  }
736  ob_end_flush();
737  flush();
738  }
739  }
740 
748  public static function endless($string = '', $flush = true) {
749  if (php_sapi_name() == 'fpm-fcgi') {
750  @self::header('X-Accel-Buffering: no'); // Buffering für Nginx deaktivieren
751  }
752  set_time_limit(0); // Endlose PHP Ausführungszeit
753  ignore_user_abort(true); // Skript weiter ausführen wenn Verbindung unterbrochen wird
754  @session_write_close(); // Session schließen
755  if ($flush) {
756  self::flush($string); // Kein Browser Timeout
757  }
758  }
759 
767  public static function write_ini_file($path, $assoc_array = array()) {
776  $clean = function($array) use (&$clean) {
777  foreach ($array as $key => $value) {
778  if (is_array($value)) {
779  $array[$key] = $clean($value);
780  } else {
781  $value = mb_strtolower($value);
782  if ($value === 'null' || $value === 'false') {
783  $array[$key] = '';
784  } else if ($value === 'true') {
785  $array[$key] = '1';
786  }
787  $array[$key] = str_replace('"', '\"', str_replace('\"', '"', $array[$key]));
788  }
789  }
790  return $array;
791  };
792  $assoc_array = $clean($assoc_array);
793 
794  $path = strtr($path, '/', DIRECTORY_SEPARATOR);
795  $single_content = $assoc_content = '';
796  foreach ($assoc_array as $key => $item) {
797  if (is_array($item)) {
798  $assoc_content.= "\n[".$key."]\n";
799  foreach ($item as $key2 => $item2) {
800  if ($item2 != 'Array') { // Dreistufige Konfigurationen direkt aus der local.php nicht in die ini schreiben
801  $assoc_content.= $key2.'="'.$item2.'"'."\n";
802  }
803  }
804  } else {
805  $single_content.= $key.'="'.$item.'"'."\n";
806  }
807  }
808  $content = $single_content."\n".$assoc_content;
809  if (!$handle = @fopen($path, 'w')) {
810  return false;
811  }
812  if (!@fwrite($handle, $content)) {
813  return false;
814  }
815  @fclose($handle);
816  return true;
817  }
818 
833  public static function header($header, $replace = true)
834  {
835  if (is_numeric($header)) {
836  // Status Code Header
837  $codes = array(
838  100 => 'Continue',
839  101 => 'Switching Protocols',
840  200 => 'OK',
841  201 => 'Created',
842  202 => 'Accepted',
843  203 => 'Non-Authoritative Information',
844  204 => 'No Content',
845  205 => 'Reset Content',
846  206 => 'Partial Content',
847  207 => 'Multi-Status',
848  208 => 'Already Reported',
849  226 => 'IM Used',
850  300 => 'Multiple Choices',
851  301 => 'Moved Permanently',
852  302 => 'Found',
853  303 => 'See Other',
854  304 => 'Not Modified',
855  305 => 'Use Proxy',
856  306 => '',
857  307 => 'Temporary Redirect',
858  308 => 'Permanent Redirect',
859  400 => 'Bad Request',
860  401 => 'Unauthorized',
861  402 => 'Payment Required',
862  403 => 'Forbidden',
863  404 => 'Not Found',
864  405 => 'Method Not Allowed',
865  406 => 'Not Acceptable',
866  407 => 'Proxy Authentication Required',
867  408 => 'Request Timeout',
868  409 => 'Conflict',
869  410 => 'Gone',
870  411 => 'Length Required',
871  412 => 'Precondition Failed',
872  413 => 'Request Entity Too Large',
873  414 => 'Request-URI Too Long',
874  415 => 'Unsupported Media Type',
875  416 => 'Requested Range Not Satisfiable',
876  417 => 'Expectation Failed',
877  420 => 'Policy Not Fulfilled',
878  421 => 'Misdirected Request',
879  422 => 'Unprocessable Entity',
880  423 => 'Locked',
881  424 => 'Failed Dependency',
882  426 => 'Upgrade Required',
883  428 => 'Precondition Required',
884  429 => 'Too Many Requests',
885  431 => 'Request Header Fields Too Large',
886  451 => 'Unavailable For Legal Reasons',
887  500 => 'Internal Server Error',
888  501 => 'Not Implemented',
889  502 => 'Bad Gateway',
890  503 => 'Service Unavailable',
891  504 => 'Gateway Timeout',
892  505 => 'HTTP Version Not Supported',
893  506 => 'Variant Also Negotiates',
894  507 => 'Insufficient Storage',
895  508 => 'Loop Detected',
896  509 => 'Bandwidth Limit Exceeded',
897  510 => 'Not Extended',
898  511 => 'Network Authentication Required'
899  );
900  if (isset($codes[$header])) {
901  $GLOBALS['stats']['status'] = $header;
902  $GLOBALS['_SERVER']['REDIRECT_STATUS'] = $header;
903  $header = $_SERVER['SERVER_PROTOCOL'].' '.$header.' '.$codes[$header];
904  } else {
905  throw new Exception('Unsupported HTTP Status Code');
906  }
907  }
908  header($header, $replace);
909  $pos = strpos($header, ':');
910  $key = substr($header, 0, $pos);
911  $value = trim(substr($header, $pos+1));
912  if ($pos === false) {
913  $key = $header;
914  $value = '';
915  }
916  if (!$replace && isset($GLOBALS['egotec']['response_headers'][$key])) {
917  $GLOBALS['egotec']['response_headers'][$key] .= ", $value";
918  } else {
919  $GLOBALS['egotec']['response_headers'][$key] = $value;
920  }
921  }
922 
929  public static function noCache()
930  {
931  self::header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
932  self::header('Cache-Control: no-store, no-cache, must-revalidate');
933  self::header('Cache-Control: post-check=0, pre-check=0', false);
934  self::header('Pragma: no-cache');
935  }
936 
944  public static function redirect($location, $header = 302) {
945  if (!empty($header)) {
946  self::header($header);
947  }
948  if (is_a($location, 'Page')) {
949  $location = $location->getUrl();
950  }
951  self::header("Location: $location");
952  exit;
953  }
954 
963  public static function checkLicence($ini_path)
964  {
965  if (isset($_SESSION['egotec_licence'][$ini_path]))
966  {
967  return $_SESSION['egotec_licence'][$ini_path];
968  } else {
969  $ini_file = rtrim($ini_path,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'module.ini';
970  if (Ego_System::file_exists($ini_file))
971  {
972  $module = parse_ini_file($ini_file);
973  $licence_array = file($GLOBALS['egotec_conf']['var_dir']
974  .'co'.'nf'.'/'.'l'.'ic'.'en'.'ce'.'.'.'eg'.'ot'.'ec'.'.'.'x'.'ml');
975  $company = trim($licence_array[4]);
976  $num_named_users = trim($licence_array[7]);
977  foreach($licence_array as $key => $value)
978  {
979  if (trim($value) == '<module_'.$module['name'].'>')
980  {
981  if (trim($licence_array[$key+1]) == md5('2u4z#h76CN~JBSo'.$company.$num_named_users.$module['name']))
982  {
983  return $_SESSION['egotec_licence'][$ini_path] = true;
984  }
985  }
986  }
987  }
988  }
989  return $_SESSION['egotec_licence'][$ini_path] = false;
990  }
991 
1000  public static function setCronLock($expiry_date = 0, $lock_msg = "")
1001  {
1002  if ($GLOBALS['cron_fix_services']) {
1003  return;
1004  }
1005 
1006  $lock_file = $GLOBALS['egotec_conf']['log_dir'].'CRON.LOCK';
1007 
1008  // Wird keine lock_msg gesetzt, wird über debug_backtrace() der letzte Aufruf ermittelt.
1009  if(empty($lock_msg))
1010  {
1011  $tmp = debug_backtrace();
1012 
1013  $lock_msg = $lock_file;
1014  $lock_msg.= "<ul>";
1015  foreach($tmp[0] as $k => $v)
1016  {
1017  $lock_msg.= "<li><b>$k</b>: ";
1018 
1019  if(is_array($v))
1020  {
1021  $lock_msg.= join("," , $v);
1022  }
1023  else
1024  {
1025  $lock_msg.= $v;
1026  }
1027  }
1028  $lock_msg.= "</ul>";
1029  }
1030 
1031  // Lock verfällt per default nach einer Stunde
1032  if ($expiry_date == 0) {
1033  $expiry_date = time()+60*60;
1034  }
1035  else
1036  {
1037  $expiry_date += time();
1038  }
1039 
1040  /*
1041  * Wenn Lock nicht vorhanden, expiry_date schreiben. Wenn doch
1042  * prüfen ob Lock bereits abgelaufen ist.
1043  */
1044  if (!Ego_System::file_exists($lock_file))
1045  {
1046  self::file_put_contents($lock_file, $expiry_date .";". $lock_msg);
1047  }
1048  else
1049  {
1050  $lock_content = explode(";" , self::file_get_contents($lock_file));
1051  $lock_time = intval($lock_content[0]);
1052 
1053  if ($lock_time > time()) {
1054  $msg = "Neuer Lock konnte nicht gesetzt werden, da bereits ein Lock existiert.";
1055  $msg.= "<br/>Dieser verfällt am ".date("d. m. Y", $lock_time)." um ".date("H:i:s", $lock_time).".";
1056  $msg.= "<p>".$lock_msg."</p>";
1057 
1058  throw new Exception($msg);
1059  }
1060  else
1061  {
1062  self::file_put_contents($lock_file, $expiry_date .";". $lock_msg);
1063  }
1064  }
1065  }
1066 
1072  public static function removeCronLock()
1073  {
1074  $lock_file = $GLOBALS['egotec_conf']['log_dir'].'CRON.LOCK';
1075  if (self::file_exists($lock_file))
1076  {
1077  @unlink($lock_file);
1078  }
1079  }
1080 
1081 
1088  public static function file_exists($file)
1089  {
1090  if (!$GLOBALS['egotec_conf']['noclearstatcache']) {
1091  clearstatcache();
1092  }
1093  return file_exists($file);
1094  }
1095 
1113  public static function parseCsvLine($str, $delimiter=';', $qualifier='"', $qualifierEscape = '\\')
1114  {
1115  $fields = array();
1116  while (strlen($str) > 0)
1117  {
1118  if ($str{0} == $delimiter)
1119  $str = substr($str, 1);
1120  if ($str{0} == $qualifier)
1121  {
1122  $value = '';
1123  for ($i = 1; $i < strlen($str); $i++)
1124  {
1125  if (($str{$i} == $qualifier) && ($str{$i-1} != $qualifierEscape))
1126  {
1127  $str = substr($str, (strlen($value) + 2));
1128  $value = str_replace(($qualifierEscape.$qualifier), $qualifier, $value);
1129  break;
1130  }
1131  $value .= $str{$i};
1132  }
1133  } else
1134  {
1135  $end = strpos($str, $delimiter);
1136  $value = ($end !== false) ? substr($str, 0, $end) : $str;
1137  $str = substr($str, strlen($value));
1138  }
1139  $fields[] = $value;
1140  }
1141 
1142  return $fields;
1143  }
1144 
1150  public static function isWindows()
1151  {
1152  return $_SERVER['WINDIR'] || $_SERVER['windir'] || $_ENV['WINDIR'] || $_ENV['windir'] || getenv('windir');
1153  }
1154 
1161  public static function commandExists($cmd) {
1162  $format = self::isWindows() ? "where %s" : "command -v %s";
1163  $parts = explode(' ', sprintf($format, $cmd));
1164  $return = self::exec($parts[0], array($parts[1], $parts[2]));
1165  return !empty($return);
1166  }
1167 
1175  public static function encode_path($url, $id=0)
1176  {
1177  if ($_SESSION['export'])
1178  {
1179  mb_regex_encoding('UTF-8');
1180  $return = mb_eregi_replace("[^[a-zA-Z0-9]]","_", $url);
1181  } else
1182  {
1183  $return = strtr($url, "%\n\r\t,;#-+?:&/'\".\\", '_________________');
1184  }
1185  if ($id && $url!=$return)
1186  {
1187  $return.= '-p-'.$id;
1188  }
1189  return urlencode($return);
1190  }
1191 
1198  public static function decode_path( $url )
1199  {
1200  //$url = iconv('US-ASCII//TRANSLIT', 'UTF-8', $url);
1201  return $url;
1202  }
1203 
1209  public static function clearPageLocks()
1210  {
1211  $db = new_db_connection();
1212  $db->delete(array(
1213  'table' => 'egotec_page_lock',
1214  'where' => "1=1"
1215  ));
1216 
1217  }
1218 
1226  public static function parseIniFile($file) {
1227  $lines = file($file);
1228  $array = array();
1229  foreach ($lines as $entry) {
1230  if (strpos($entry, ';') !== 0) {
1231  $content = explode('=', $entry, 2);
1232  $array[rtrim($content[0])] = trim($content[1]);
1233  }
1234  }
1235  return $array;
1236  }
1237 
1245  public static function isEmptyContent($str)
1246  {
1247  if ($GLOBALS['frontend_admin']) {
1248  // In der Frontend Administration die automatisch generierten HTML Tags entfernen
1249  $str = preg_replace('/<([^ ]+) [^>]*data-edit-type="[^"]+"[^>]*>(.*?)<\/\\1>/msi', '$2', $str);
1250  }
1251  $str = strip_tags($str, '<img><div><input><textarea><form><hr><param><object><video><iframe><embed>');
1252  $str = html_entity_decode($str);
1253  $str = str_replace(
1254  array(
1255  '',
1256  ' ',
1257  "\n",
1258  "\r",
1259  chr(160) // nbsp
1260  ),
1261  '',$str
1262  );
1263  if (strlen($str) == 0)
1264  {
1265  return true;
1266  } else
1267  {
1268  return false;
1269  }
1270  }
1271 
1286  public static function urltopage($url, $params=array(), $only_site = false, $error_page = false, $commit_params = false)
1287  {
1288  require_once ('base/Site.php');
1289  $url = preg_replace('/#.*?$/ims', '', $url); // URL ohne Anker verwenden
1290 
1291  try
1292  {
1293  // keine Sprechende URL
1294  if (strpos($url, 'index.php?') !== false)
1295  {
1296  return self::_urltopage_index($url, $params);
1297  } else
1298  { // eine Sprechende URL
1299  // Mediapool Anteil entfernen
1300  $url = preg_replace('/\/_\/.*?$/ims', '.html', $url);
1301  return self::_urltopage_sprechend($url, $only_site, $error_page, $commit_params);
1302  }
1303  }
1304  catch (Exception $e)
1305  {
1306  return false;
1307  }
1308  }
1309 
1310  private static function _urltopage_sprechend($url, $only_site, $error_page, $commit_params)
1311  {
1312  if ($GLOBALS['egotec_conf']['rewrite_engine'] == 'url') {
1313  // Die URL in der Datenbank suchen
1314  $info = Ego_System::parseUrl($url);
1315  $domain = $info['host'] ?? $_SERVER['HTTP_HOST'];
1316  $file = ($pos = strpos($info['datei'], '.')) ? substr($info['datei'], 0, $pos) : $info['datei'];
1317  if (strpos($file, '%') !== false) {
1318  // Ggf. muss der Wert vorher noch dekodiert werden
1319  $file = urldecode(str_replace('+', '%2B', $file));
1320  }
1321  $dir = ltrim($info['pfad'] . '/' . $file, '/');
1322  $db = new_db_connection(array(
1323  'table' => 'egotec_url',
1324  'where' => "domain = :domain AND dir = :dir",
1325  'bind' => array(
1326  'domain' => $domain,
1327  'dir' => $dir
1328  )
1329  ));
1330  if ($db->nextRecord()) {
1332  'site' => $db->Record['site'],
1333  'lang' => $db->Record['lang'],
1334  'id' => $db->Record['id']
1335  ]));
1336  }
1337  return null;
1338  }
1339 
1340  if ($commit_params)
1341  {
1342  global $dir;
1343  }
1344 
1345  $req = array();
1346 
1347  // HTTP Host rausnehmen
1348  if (preg_match("#^http[s]?://([^/]+)#i", $url, $m))
1349  {
1350  $http_host = $m[1];
1351  $url = substr($url, strlen($m[0]));
1352  }
1353 
1354  $pos = strpos($url, $GLOBALS['egotec_conf']['url_dir']);
1355  if ($pos === 0)
1356  {
1357  $url = substr($url, strlen($GLOBALS['egotec_conf']['url_dir']));
1358  }
1359 
1360  // Die Dateiendung aus der URL entfernen
1361  $dot_pos = strrpos($url, '.');
1362  if ($dot_pos!==false)
1363  { // Dateiendung bestimmen.
1364  $request_suffix = substr($url, $dot_pos);
1365  $url = substr($url, 0, $dot_pos);
1366  } else
1367  {
1368  $request_suffix = '.html';
1369  }
1370 
1371  /*
1372  * 1. Schritt - Site Lang und Skin rauskriegen
1373  */
1374 
1375  $dir = dirname($url);
1376  if ($dir && $dir!='.')
1377  { // Den Pfad entschlüsseln. Site, Skin, Lang bestimmen
1378  $dir = explode('/', $dir);
1379  if ($dir && Ego_System::file_exists($GLOBALS['egotec_conf']['site_dir'].$dir[0]))
1380  { // Site aus Pfad gewinnen.
1381  $req['site'] = array_shift($dir);
1382  $url = substr($url, strlen($req['site'])+1);
1383  }
1384  if ($dir && strlen($dir[0])==2)
1385  { // Die Sprache aus dem Pfad gewinnen.
1386  $req['lang'] = array_shift($dir);
1387  $url = substr($url, 3);
1388  }
1389  if ($dir && Ego_System::file_exists($GLOBALS['egotec_conf']['skin_dir'].$dir[0]))
1390  { // Skin aus Pfad gewinnen.
1391  $req['skin'] = array_shift($dir);
1392  $url = substr($url, strlen($req['skin'])+1);
1393  }
1394 
1395  $meta_url = $url; // Die URL OHNE site, skin und lang
1396 
1397  // Den Pfad berücksichtigen
1398  $path_index = 0;
1399  $num_path = 0;
1400  while ($dir[$path_index])
1401  {
1402  $num_path+= strlen($dir[$path_index])+1;
1403  $path_index++;
1404  }
1405  $url = ltrim(substr($url, $num_path),'/');
1406  }
1407 
1408  $url = explode('-', $url); // %09
1409  do
1410  {
1411  $key = urldecode(next($url));
1412  $value = str_replace('%2d', '-', urldecode(next($url)));
1413  $req[$key] = urldecode($value);
1414  } while ($key);
1415 
1417  if ($http_host && Ego_System::file_exists($GLOBALS['egotec_conf']['bin_dir'].'admin/popup_virtual_hosts.php'))
1418  {
1419  $virtual_hosts = self::getVirtualHosts();
1420  if (!$req['site'])
1421  {
1422  $http_host = strtolower($http_host);
1423 
1424  if (!isset($virtual_hosts[$http_host]))
1425  {
1426  if ($http_host != $_SERVER['HTTP_HOST']) {
1427  /* Wenn es einen Host gibt, der nicht der aktuelle Host ist und es keinen virtuellen Host gibt,
1428  * handelt es sich wohlmöglich um eine externe URL, die nicht aufgelöst werden soll. */
1429  return false;
1430  }
1431  $req['site'] = $GLOBALS['egotec_conf']['default_site'];
1432  } else {
1433  $req['site'] = $virtual_hosts[$http_host]['site'];
1434  $GLOBALS['egotec_conf']['default_site'] = $req['site'];
1435  }
1436  if (!$req['lang'] && $virtual_hosts[$http_host]['lang'])
1437  {
1438  $req['lang'] = $virtual_hosts[$http_host]['lang'];
1439  }
1440  } else {
1441  if (isset($virtual_hosts[$http_host]))
1442  {
1443  $GLOBALS['egotec_conf']['default_site'] = $virtual_hosts[$http_host];
1444  }
1445  }
1446  }
1447 
1448  if (!$req['site'])
1449  {
1450  $req['site'] = $GLOBALS['egotec_conf']['default_site'];
1451  }
1452  try {
1453  $site = new Site($req['site'], $req['lang'], $req['skin']);
1454  } catch (Exception $e) {
1455  switch ($e->getCode()) {
1457  array_unshift($url, $req['lang']);
1458  unset($req['lang']);
1459  $site = new Site($req['site'], '', $req['skin']);
1460  break;
1461  default:
1462  if ($error_page)
1463  {
1464  $req['site'] = $GLOBALS['egotec_conf']['default_site'];
1465  $site = new Site($GLOBALS['egotec_conf']['default_site']);
1466  if ($commit_params)
1467  {
1468  self::header(404);
1469  }
1470  $req['p'] = $site->site['error_id']?$site->site['error_id']:$site->rootId;
1471  } else
1472  {
1473  return false; // Site+Lang gibts nicht
1474  }
1475  }
1476  }
1477 
1478  if ($req['lang'])
1479  {
1480  try {
1481  $site->setLanguage($req['lang']);
1482  } catch (Site_Exception $exception)
1483  { // Falls die Sprache nicht existiert
1484  if ($error_page)
1485  {
1486  unset($name);
1487  unset($req['lang']);
1488  switch ($exception->getCode())
1489  {
1491  $site = new Site(
1492  $req['site'],
1493  '',
1494  $req['skin'],
1495  !$req['nonactive']
1496  );
1497  break;
1499  $site = new Site();
1500  break;
1501  }
1502  $req['id'] = $site->site['error_id'];
1503  } else
1504  {
1505  return false;
1506  }
1507  }
1508  }
1509 
1510  if ($only_site)
1511  {
1512  if ($commit_params)
1513  {
1514  foreach ($req as $k => $v)
1515  {
1516  $_REQUEST[$k] = $v;
1517  }
1518  }
1519  return $site;
1520  }
1521 
1522  /*
1523  * 2. Schritt - Die Page aus der ID oder aus dem Namen erzeugen
1524  */
1525 
1526  $req['id'] = $req['p']; // id sollte aus Gründen der Suchmaschinenoptimierung nicht in der URL vorkommen
1527  if ($req['id'] && !is_numeric($req['id']))
1528  {
1529  if ($error_page)
1530  {
1531  $req['id'] = $site->site['error_id'];
1532  } else
1533  {
1534  return false;
1535  }
1536  }
1537 
1538  $name = urldecode($url[0]);
1539  $lang_name = ($req['lang']?$req['lang'].'/':'').$meta_url;
1540  if (!$meta_url && !$name && !$req['id'])
1541  { // Die Startseite wird gewünscht
1542  $req['id'] = $site->rootId;
1543  }
1544 
1545  $current_path = array();
1546  if (!$req['id'])
1547  { // Wenn die Seitenid nicht explizit gesetzt ist, dann muss sie aus dem Namen gewonnen werden.
1548  if (!$meta_url)
1549  { // Auf die URL prüfen.
1550  $meta_url = $name;
1551  }
1552  if (!$meta_url)
1553  {
1554  $req['id'] = $site->rootId;
1555  } else {
1556  $pages = $site->getPages(array('where' => 'url=\''.$meta_url.'\''), array('auth_or' => '1=1', 'inactive' => true));
1557  if ($pages && $pages->numRecords() == 1)
1558  {
1559  $page = $pages->nextPage();
1560  $current_path = $page->getPath(false, array(), false);
1561  } else { // Über das URL-Feld wurde kein passenden Eintrag gefunden
1562  $parent = false;
1563  if (is_array($dir))
1564  {
1565  foreach($dir as $path_name)
1566  {
1567  $path_name = urldecode($path_name);
1568  if (strpos($path_name, '-')!==false)
1569  {
1570  $path_name = explode('-', $path_name);
1571  $parent = $site->getPage((int)$path_name[2], array('auth_or' => '1=1', 'inactive' => true));
1572  } else {
1573  if (!is_object($parent))
1574  {
1575  $pages = $site->getRoot(array('auth_or' => '1=1'))->getChildren(
1576  array('where' => 'name=:name OR name LIKE :name', 'bind' => array('name' => $path_name)),
1577  array('auth_or' => '1=1', 'inactive' => true)
1578  );
1579  $parent = $pages->nextPage();
1580  } else {
1581  $pages = $parent->getChildren(
1582  array('where' => 'name=:name OR name LIKE :name', 'bind' => array('name' => $path_name)),
1583  array('auth_or' => '1=1', 'inactive' => true)
1584  );
1585  $parent = $pages->nextPage();
1586  }
1587  }
1588  if (is_object($parent)) // Bei fehlerhaften Pfaden, die z.B. von Robots oder Würmern erzeugt werden, kann es vorkommen,
1589  { // dass keine Seite für ein Verzeichnis existiert.
1590  $current_path[] = $parent->field['id'];
1591  }
1592  }
1593  }
1594 
1595  if (!is_object($parent))
1596  {
1597  $parent = $site->getRoot(array('auth_or' => '1=1', 'inactive' => true));
1598  }
1599  }}
1600 
1601  if ($name)
1602  {
1603  if (is_object($page))
1604  { // Es wurde bereits eine passende Seite gefunden
1605  $req['id'] = $page->field['id'];
1606  } else
1607  {//Bisher konnte nur der Pfad generiert werden
1608  if (is_object($parent))
1609  {
1610  $pages = $parent->getChildren(
1611  array('where' => 'url=\''.$name.'\' OR name=\''.$name.'\' OR name like \''.$name.'\''),
1612  array('auth_or' => '1=1')
1613  );
1614  if (!$pages->numRecords())
1615  {
1616  $pages = $site->getPages(
1617  array('where' => 'url LIKE \''.$name.'\' OR name=\''.$name.'\' OR name like \''.$name.'\''),
1618  array('auth_or' => '1=1')
1619  );
1620  }
1621  } else {
1622  $pages = $site->getPages(
1623  array('where' => 'url LIKE \''.$name.'\' OR name=\''.$name.'\' OR name like \''.$name.'\''),
1624  array('auth_or' => '1=1')
1625  );
1626  }
1627  $req['id'] = $pages->nextPage()->field['id'];
1628  }
1629  if (!$req['id'] && $commit_params)
1630  {
1631  $GLOBALS['no_cache'] = true;
1632  }
1633  } else if (!$req['id'])
1634  { // Hier muss nochmals abgefragt werden, da z.B. bei einem Fehler, z.B. eine nicht vorhandene Sprache, die id gesetzt wird.
1635  $req['id'] = $site->rootId;
1636  }
1637  }
1638  if ($commit_params)
1639  {
1640  $GLOBALS['current_path'] = $current_path;
1641  foreach ($req as $k => $v)
1642  {
1643  $_REQUEST[$k] = $v;
1644  }
1645  }
1646  $get_page_param = array();
1647  $get_page_param['auth_or'] = '1=1';
1648  $get_page_param['inactive'] = true;
1649  return $site->getPage($req['id'], $get_page_param);
1650  }
1651 
1652  private static function _urltopage_index($url, $params=array())
1653  {
1654  // ID ermitteln
1655  $pattern = '/id=(\d+)/';
1656  preg_match($pattern, $url, $match);
1657  $id = $match[1];
1658 
1659  // Site ermitteln
1660  if(!$params['site'])
1661  {
1662  $pattern = '/site=([^\?&]+)/';
1663  preg_match($pattern, $url, $match);
1664  $site_id = $match[1];
1665  }
1666  else
1667  {
1668  $site_id = $params['site'];
1669  }
1670 
1671  // Sprache ermitteln
1672  if(!$params['lang'])
1673  {
1674  $pattern = '/lang=([a-z]+)/';
1675  preg_match($pattern, $url, $match);
1676  $site_lang = $match[1];
1677  }
1678  else
1679  {
1680  $site_lang = $params['lang'];
1681  }
1682 
1683  $site = new Site($site_id, $site_lang);
1684  if (empty($GLOBALS['site'])) {
1685  // Wird eine Page ermittelt, muss global immer eine Site existieren (für PageExtension)
1686  $GLOBALS['site'] = $site;
1687  }
1688  $page = $site->getPage($id, $params['params']['param']);
1689 
1690  return $page;
1691  }
1692 
1706  public static function copy($src, $dest, $except = '', $useLinks=false)
1707  {
1708  set_time_limit(0);
1709  if (is_dir($src))
1710  {
1711  Ego_System::mkdir($dest);
1712  $dir = dir($src);
1713  while(($entry = $dir->read()) !== false)
1714  {
1715  if ($entry == '.svn' || $entry == '.' || $entry == '..') continue;
1716  if (
1717  !empty($except)
1718  && preg_match($except, $entry)
1719  ) {
1720  continue;
1721  }
1722 
1723  $path = $src.'/'.$entry;
1724  self::copy($path, $dest.'/'.$entry, $except, $useLinks);
1725  }
1726 
1727  $dir->close();
1728  } elseif (empty($except) || !preg_match($except, basename($src)))
1729  {
1730  if ($useLinks && @link($src, $dest)) { // falls gewünscht einen Hard Link setzen
1731  return true;
1732  }
1733  return @copy($src, $dest);
1734  }
1735 
1736  return true;
1737  }
1738 
1748  public static function getAllSites($username = '', $perm = '', $table = false, $type = '')
1749  {
1750  $unique_key = $username.$perm.(int)$table.(string)$type;
1751  if (!empty(self::$allSites[$unique_key])) {
1752  return self::$allSites[$unique_key];
1753  }
1754  if ($username)
1755  {
1756  $db = new_db_connection(array(
1757  'fields' => 'user_id',
1758  'table' => 'egotec_user',
1759  'where' => 'username=:username',
1760  'bind' => array('username' => $username)
1761  ));
1762  if (!$db->nextRecord())
1763  {
1764  return array(); // Bei einem nicht vorhandenen Benutzer werden keine Mandanten zurückgegeben.
1765  }
1766  $user_id = $db->Record['user_id'];
1767  } else {
1768  $user_id = false;
1769  }
1770  $dir = opendir($GLOBALS['egotec_conf']['site_dir']);
1771  $sites = $sort = array();
1772  while ($file = readdir($dir))
1773  {
1774  if (
1775  is_dir($GLOBALS['egotec_conf']['site_dir'].$file) && $file[0] != '.' &&
1776  Ego_System::file_exists($GLOBALS['egotec_conf']['site_dir'].$file.'/conf.ini')
1777  ) {
1778  $loop_site = new Site($file, '', '', !$GLOBALS['admin_area']);
1779 
1780  if ($type && $loop_site->site['type'] != $type) {
1781  continue;
1782  }
1783 
1784  // Prüfen ob dieser Mandant auch in der Datenbank existiert
1785  if ($table)
1786  {
1787  $db = new_db_connection();
1788  if (!$db->tableExists($loop_site->pageTable))
1789  {
1790  egotec_warning_log("Site table {$loop_site->pageTable} does not exist.");
1791  continue;
1792  }
1793  }
1794 
1795  if (
1796  !$user_id ||
1797  $loop_site->hasRight($perm, false, $user_id)
1798  ) {
1799  $sites[$file] = $loop_site;
1800  $sort[] = mb_strtolower($loop_site->site['title']);
1801  }
1802  }
1803  }
1804  closedir($dir);
1805 
1806  array_multisort($sort, SORT_ASC, SORT_NATURAL, $sites);
1807 
1808  self::$allSites[$unique_key] = $sites;
1809  return $sites;
1810  }
1811 
1817  public static function getAllSkins() {
1818  $skins = self::getSkins();
1819  foreach ($skins as $type => $list) {
1820  foreach ($list as $skin => $title) {
1821  if ($skin == '_empty') {
1822  unset($skins[$type][$skin]);
1823  continue;
1824  }
1825  $skins[$type][$skin] = array();
1826  }
1827  }
1828  foreach (Ego_System::getAllSites() as $site) {
1829  foreach (array_unique(array_merge(
1830  array($site->conf['site']['default_skin'], $site->conf['site']['mobile_skin']),
1831  explode(',', $site->conf['site']['skins'])
1832  )) as $skin) {
1833  if (
1834  !empty($skin)
1835  && isset($skins['skins'][$skin])
1836  && !in_array($site->name, $skins['skins'][$skin])
1837  ) {
1838  $skins['skins'][$skin][] = $site;
1839  }
1840  }
1841  if (
1842  $site->theme
1843  && (!$skins['themes'][$site->theme]
1844  || !in_array($site->name, $skins['themes'][$site->theme]))
1845  ) {
1846  $skins['themes'][$site->theme][] = $site;
1847  }
1848  }
1849  return $skins;
1850  }
1851 
1858  public static function getSkins($more_themes = array()) {
1859  $cache = self::getCache();
1860  $cache_key = 'getSkins' . md5(json_encode(func_get_args()));
1861  $result = $cache->get($cache_key);
1862 
1863  if ($result === null) {
1864  $result = array(
1865  'skins' => array(),
1866  'themes' => array()
1867  );
1868 
1869  // Alle Designs
1870  $skin_dir = $GLOBALS['egotec_conf']['skin_dir'];
1871  if (self::file_exists($skin_dir)) {
1872  $dir = dir($skin_dir);
1873  while ($file = $dir->read()) {
1874  if (
1875  is_dir($skin_dir.$file)
1876  && substr($file, 0, 1) != '.'
1877  && $file != 'base'
1878  && $file[0] != '_'
1879  ) {
1880  $result['skins'][$file] = $file;
1881  }
1882  }
1883  $dir->close();
1884  ksort($result['skins']);
1885  }
1886 
1887  // Alle Vorlagen
1888  $result['themes'] = array('_empty' => '--'); // keine Vorlage
1889  $theme_dir = $GLOBALS['egotec_conf']['egotec_dir'].'pub/theme/';
1890  if (self::file_exists($theme_dir)) {
1891  $dir = dir($theme_dir);
1892  while ($file = $dir->read()) {
1893  if(
1894  is_dir($theme_dir.$file)
1895  && substr($file, 0, 1) != '.'
1896  && $file != 'base'
1897  && $file[0] != '_'
1898  ) {
1899  $conf_file = $theme_dir.$file.'/conf.ini';
1900  if (Ego_System::file_exists($conf_file)) {
1901  $conf = parse_ini_file($conf_file);
1902  $title = $conf['title'];
1903  } else {
1904  $title = $file;
1905  }
1906  if (Ego_System::file_exists($theme_dir.$file.'/module.ini')) {
1907  $result['themes'][$file] = "[ $title ]";
1908  } else {
1909  $result['themes'][$file] = $title;
1910  }
1911  }
1912  }
1913  $dir->close();
1914  }
1915  foreach ($more_themes as $name => $theme) {
1916  if (!isset($result['themes'][$name])) {
1917  $result['themes'][$name] = $theme;
1918  }
1919  }
1920  ksort($result['themes']);
1921 
1922  $cache->set($cache_key, $result);
1923  }
1924 
1925  return $result;
1926  }
1927 
1937  public static function log($file, $message)
1938  {
1939  $file = $GLOBALS['egotec_conf']['log_dir'].$file;
1940  if (Ego_System::file_exists($file))
1941  {
1942  $size = filesize($file);
1943  if ($size > 100*1024*1024)
1944  { // größer als 100 MB
1945  $new_name = $file.'_'.date("Y-m-d_H-i-s");
1946  rename($file, $new_name);
1947  }
1948  }
1949  // Ist nicht mehr genug Speicherplatz vorhanden?
1950  $min = ($GLOBALS['egotec_conf']['log_min_disk_free']?
1951  $GLOBALS['egotec_conf']['log_min_disk_free']:10
1952  )*1024*1024; // MB -> Bytes, wenn nichts eingestellt min. 10 MB
1953  if (!is_dir($GLOBALS['egotec_conf']['log_dir'])) {
1954  self::mkdir($GLOBALS['egotec_conf']['log_dir']);
1955  }
1956  $bytes_free = disk_free_space($GLOBALS['egotec_conf']['log_dir']);
1957  if ($min > $bytes_free)
1958  { // zu wenig Speicherplatz
1959  // älteste Log löschen
1960  $times = array();
1961  $files = glob($file.'_*');
1962  foreach ($files as $f)
1963  {
1964  $m = array();
1965  if (
1966  strpos($f, $file)===0 &&
1967  preg_match('/_(\d{4}-\d{2}-\d{2})_(\d{2})-(\d{2})-(\d{2})$/', $f, $m)
1968  ) {
1969  $stamp = $m[1].' '.$m[2].':'.$m[3].':'.$m[4];
1970  $times[strtotime($stamp)] = $f;
1971  }
1972  }
1973  ksort($times);
1974  if (sizeof($times)>0)
1975  {
1976  unlink(current($times));
1977  } else
1978  {
1979  $last_mail_file = $GLOBALS['egotec_conf']['log_dir'].'disk_free_mail.date';
1980  $last_mail_date = '1970-01-01 00:00:00';
1981  if (Ego_System::file_exists($last_mail_file) && ($date = Ego_System::file_get_contents($last_mail_file))) {
1982  $last_mail_date = $date;
1983  }
1984  if (
1985  !$GLOBALS['egotec_conf']['no_disk_free_mail']
1986  && $last_mail_date + 3600 < date('Y-m-d H:i:s') // Nur einmal pro Stunde
1987  ) {
1988  Ego_System::file_put_contents($last_mail_file, date('Y-m-d H:i:s'));
1989  /*
1990  * problem - wenig Speicherplatz und keine alte Log Datei zum löschen
1991  * Benachrichtigung an den Admin
1992  */
1993  $frei = round($bytes_free / (1024*1024));
1994  $text = "Es ist nicht genügend Speicherplatz auf dem Server vorhanden.\n".
1995  "Aktuell sind auf dem Server $frei MB frei.\n\n".
1996  $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
1997  require_once('mail/Ego_Mail.php');
1998  $mail = new Ego_Mail();
1999  try {
2000  $mail->mail($GLOBALS['egotec_conf']['admin_mail'], 'Nicht genügend Speicherplatz auf dem Webserver', $text);
2001  } catch (Exception $e)
2002  {
2003  }
2004  }
2005 
2006  return; // keinen weiteren Log-Eintrag
2007  }
2008  }
2009 
2010  // endlich darf in die Log geschrieben werden
2011  error_log($message, 3, $file);
2012  }
2013 
2022  public static function checkRequirements()
2023  {
2024  $result = array(
2025  'passed' => true, // Prüfung bestanden oder nicht
2026  'installed' => array(), // Verfügbare Extensions
2027  'failed' => array(), // Fehlende Extensions
2028  'notice' => array() // Hinweise
2029  );
2030 
2031  /*
2032  * Voraussetzungen definieren
2033  *
2034  * Versionsangabe = diese Version muss mindestens installiert sein
2035  * true = Version ist egal, Extension wird aber benötigt
2036  * false = Version ist egal, Extension ist aber optional
2037  */
2038  $requirements = array(
2039  'php' => array(
2040  'min' => '7.1'
2041  ),
2042  'sys64' => array(
2043  'min' => 4
2044  ),
2045  'mysql' => array(
2046  'min' => '5.0'
2047  ),
2048  'oracle' => array(
2049  'min' => '10.2'
2050  ),
2051  'imagick' => array(
2052  'min' => true
2053  ),
2054  'fileinfo' => array(
2055  'min' => true
2056  ),
2057  'session' => array(
2058  'min' => true
2059  ),
2060  'sockets' => array(
2061  'min' => true
2062  ),
2063  'xml' => array(
2064  'min' => true
2065  ),
2066  'zlib' => array(
2067  'min' => true
2068  ),
2069  'soap' => array(
2070  'min' => true
2071  ),
2072  'pspell' => array(
2073  'min' => true
2074  ),
2075  'mbstring' => array(
2076  'min' => true
2077  ),
2078  'curl' => array(
2079  'min' => (bool) Ego_System::checkLicence($GLOBALS['egotec_conf']['lib_dir'].'lucene') || (bool) Ego_System::checkLicence($GLOBALS['egotec_conf']['lib_dir'].'elastic')
2080  )
2081  );
2082 
2083  // Alle geladenen Extensions
2084  $loaded_extensions = get_loaded_extensions();
2085 
2086  // Prüfung einleiten
2087  foreach($requirements as $requirement => $required)
2088  {
2089  $skip_version_compare = false;
2090  $installed = $failed = '';
2091 
2092  switch($requirement)
2093  {
2094  // PHP Version
2095  case 'php':
2096  $version = phpversion();
2097 
2098  $installed = "PHP {$required['min']} oder höher ist installiert ($version)";
2099  $failed = "PHP Version unzureichend ($version). Bitte aktualisieren Sie Ihre PHP Version auf {$required['min']} oder höher";
2100  break;
2101 
2102  // MySQL Version (nur falls vorhanden)
2103  case 'mysql':
2104  if(in_array(Ego_System::getDbDriver(), array('mysql', 'mysqli', 'innodb')))
2105  {
2106  $db = new_db_connection();
2107  $version = $db->getVersion();
2108 
2109  $installed = "MySQL {$required['min']} oder höher ist installiert ($version)";
2110  $failed = "MySQL Version unzureichend ($version). Bitte aktualisieren Sie Ihre MySQL Version auf {$required['min']} oder höher";
2111  } else
2112  {
2113  $installed = "MySQL wird nicht benötigt";
2114  }
2115  break;
2116 
2117  // Oracle Version (nur falls vorhanden)
2118  case 'oracle':
2119  if (Ego_System::getDbDriver() == 'oci')
2120  {
2121  if ($conn = @oci_connect($GLOBALS['egotec_conf']['db']['user'], $GLOBALS['egotec_conf']['db']['password'], $GLOBALS['egotec_conf']['db']['database'], 'AL32UTF8'))
2122  {
2123  $version = oci_server_version($conn);
2124  oci_close($conn);
2125 
2126  $installed = "Oracle {$required['min']} oder höher ist installiert ($version)";
2127  $failed = "Oracle Version unzureichend ($version). Bitte aktualisieren Sie Ihre Oracle Version auf {$required['min']} oder höher";
2128  }
2129  else
2130  {
2131  $version = false;
2132  $failed = "Oracle ist installiert, die Version konnte aber nicht ermittelt werden. Empfohlene Oracle Version ist {$required['min']} oder höher";
2133  }
2134  } else
2135  {
2136  $installed = "Oracle wird nicht benötigt";
2137  }
2138  break;
2139 
2140  // Mime Type erkennen
2141  case 'fileinfo':
2142  if (function_exists('finfo_file')) {
2143  $version = phpversion('fileinfo');
2144  $result['installed'][$requirement] = "Fileinfo ist installiert ($version)";
2145  } else {
2146  $result['failed'][$requirement] = "Fileinfo ist nicht installiert";
2147  }
2148  $skip_version_compare = true;
2149  break;
2150 
2151  // Test auf 64 Bit System
2152  case 'sys64':
2153  $installed = "64 Bit System";
2154  $failed = "32 Bit System";
2155  break;
2156 
2157  // Extensions bei denen die Versionierung egal ist
2158  default:
2159  $version = phpversion($requirement);
2160 
2161  /*
2162  * phpversion liefert false wenn die Extension nicht gefunden wurde,
2163  * aber auch wenn es nur keine Versionierung hierfür gibt. Deshalb nochmal prüfen
2164  */
2165  if (!$version)
2166  {
2167  $version = in_array($requirement, $loaded_extensions) ? '' : false;
2168  }
2169 
2170  if ($version === false)
2171  {
2172  $type = 'failed';
2173  if (!$required['min']) // falls Extension optional ist
2174  {
2175  $type = 'notice';
2176  }
2177 
2178  $result[$type][$requirement] = "$requirement ist nicht installiert";
2179  }
2180  else
2181  {
2182  $result['installed'][$requirement] = "$requirement ist installiert".($version != '' ? " ($version)" : '');
2183  }
2184 
2185  $skip_version_compare = true;
2186  break;
2187  }
2188 
2189  // Versionsüberprüfung überspringen
2190  if ($skip_version_compare)
2191  {
2192  continue;
2193  }
2194  if (
2195  $requirement == 'oracle'
2196  && preg_match('/\d+\.[^ ]*/', $version, $match)
2197  )
2198  {
2199  $version = $match[0];
2200  }
2201  // Versionen vergleichen
2202  if(!version_compare($version, $required['min'], '>=') && !$required['except'])
2203  {
2204  $result['failed'][$requirement] = $failed;
2205  }elseif(version_compare($version, $required['min'], '>=') && !$required['except'])
2206  {
2207  $result['installed'][$requirement] = $installed;
2208  }elseif(version_compare($version, $required['min'], '>=') && $required['except'])
2209  { //es gibt ausnahmen!!!
2210  $exceptions = explode(',', $required['except']);
2211 
2212  if (version_compare($version,$exceptions[0], '>=') && version_compare($version,$exceptions[1], '<'))
2213  {
2214  $result['failed'][$requirement] = $failed;
2215  }else
2216  {
2217  $result['installed'][$requirement] = $installed;
2218  }
2219  }else{
2220  $result['failed'][$requirement] = $failed;
2221  }
2222  }
2223 
2224  // MySQL oder Oracle müssen installiert sein
2225  if ($result['failed']['mysql'] && $result['failed']['oracle'])
2226  {
2227  $result['failed']['_db'] = "Weder MySQL noch Oracle sind installiert";
2228  }
2229 
2230  // GD oder ImageMagick müssen installiert sein
2231  if ($result['failed']['gd'] && $result['failed']['convert'])
2232  {
2233  $result['failed']['_image'] = "Weder GD noch ImageMagick sind installiert";
2234  }
2235 
2236  // Spezielle fehlgeschlagene Voraussetzungen als Hinweise markieren
2237  foreach($result['failed'] as $key => $value)
2238  {
2239  $set_notice = false;
2240 
2241  switch($key)
2242  {
2243  case 'mysql':
2244  if ($result['installed']['oracle'])
2245  {
2246  $set_notice = true;
2247  }
2248  break;
2249 
2250  case 'oracle':
2251  if ($result['installed']['mysql'])
2252  {
2253  $set_notice = true;
2254  }
2255  break;
2256 
2257  case 'gd':
2258  if ($result['installed']['convert'])
2259  {
2260  $set_notice = true;
2261  }
2262  break;
2263 
2264  case 'convert':
2265  if ($result['installed']['gd'])
2266  {
2267  $set_notice = true;
2268  }
2269  break;
2270  }
2271 
2272  if ($set_notice)
2273  {
2274  $result['notice'][$key] = $value;
2275  unset($result['failed'][$key]);
2276  }
2277  }
2278  // Systemvoraussetzungen werden nicht erfüllt
2279  if (sizeof($result['failed']) > 0)
2280  {
2281  $result['passed'] = false;
2282  }
2283 
2284  return $result;
2285  }
2286 
2293  public static function byte_format($byte)
2294  {
2295  if ($byte > 1024*1024*1024) {
2296  return number_format($byte / (1024*1024*1024), 1).' GB';
2297  } elseif ($byte > 1024*1024) {
2298  return number_format($byte / (1024*1024), 1).' MB';
2299  } elseif ($byte > 1024) {
2300  return number_format($byte / (1024), 1).' kB';
2301  } else {
2302  return $byte.' B';
2303  }
2304  }
2305 
2314  public static function eternalCache($active)
2315  {
2316  if ($active)
2317  {
2318  self::file_put_contents($GLOBALS['egotec_conf']['cache_dir'].'eternal', time()+900); // Der Html Cache bleibt für 15' aktiv.
2319  } else {
2320  @unlink($GLOBALS['egotec_conf']['cache_dir'].'eternal');
2321 
2322  // Den gesamten Cache löschen
2323  self::clearCacheAllSites();
2324  }
2325  }
2326 
2332  public static function checkSSL()
2333  {
2334  try {
2335  return (bool) (self::file_get_contents('https://'.$_SERVER['HTTP_HOST'].$GLOBALS['egotec_conf']['url_dir']));
2336  } catch (Exception $e) {
2337  return false;
2338  }
2339  }
2340 
2344  public static function getDbDriver()
2345  {
2346  return substr(strrchr(get_class(new_db_connection()), '_'), 1);
2347  }
2348 
2355  public static function getMimeTypes($ext = '')
2356  {
2357  require_once('MIME/Type/Extension.php');
2358  $mime = new MIME_Type_Extension();
2359 
2360  $types = $mime->extensionToType;
2361 
2362  return ($ext ? $types[$ext] : $types);
2363  }
2364 
2372  public static function getFilePath($dir, $file)
2373  {
2374  $sub_dir = array(
2375  'site' => $GLOBALS['site']->name,
2376  'skin' => $GLOBALS['site']->skin
2377  );
2378 
2379  if (file_exists($GLOBALS['egotec_conf'][$dir.'_dir'].$sub_dir[$dir].'/'.$file))
2380  {
2381  return $GLOBALS['egotec_conf']['url_dir'].$dir.'/'.$sub_dir[$dir].'/'.$file;
2382  } elseif ($GLOBALS['site']->globalAllowed() && file_exists($GLOBALS['egotec_conf'][$dir.'_dir'].'_global/'.$file))
2383  {
2384  return $GLOBALS['egotec_conf']['url_dir'].$dir.'/_global/'.$file;
2385  } elseif (file_exists($GLOBALS['egotec_conf']['lib_dir'].'type/'.$dir.'/'.$file))
2386  {
2387  return $GLOBALS['egotec_conf']['url_dir'].'lib/'.$dir.'/'.$file;
2388  } else
2389  {
2390  return '';
2391  }
2392  }
2399  public static function getDirectorySize($pfad, &$links = array())
2400  {
2401  $totalsize = 0;
2402  $totalcount = 0;
2403  $dircount = 0;
2404  if ($handle = opendir ($pfad))
2405  {
2406  while (false !== ($file = readdir($handle)))
2407  {
2408  $nextpath = $pfad . '/' . $file;
2409  if ($file != '.' && $file != '..' && !is_link ($nextpath))
2410  {
2411  if (is_dir ($nextpath))
2412  {
2413  $dircount++;
2414  $result = Ego_System::getDirectorySize($nextpath, $links);
2415  $totalsize += $result['size'];
2416  $totalcount += $result['count'];
2417  $dircount += $result['dircount'];
2418  }elseif (is_file ($nextpath))
2419  {
2420  $stat = stat ($nextpath);
2421  if (!isset($links[$stat['ino']])) {
2422  $totalsize += $stat['size'];
2423  }
2424  if ($stat['nlink'] > 1) {
2425  $links[$stat['ino']] = $stat['nlink'];
2426  }
2427  $totalcount++;
2428  }
2429  }
2430  }
2431  }
2432  closedir ($handle);
2433  $total['size'] = $totalsize;
2434  $total['count'] = $totalcount;
2435  $total['dircount'] = $dircount;
2436  return $total;
2437  }
2438 
2448  public static function file_get_contents($filename, $utf8 = true, $context = null) {
2449  $host = $GLOBALS['egotec_conf']['proxy']['proxy_host'];
2450  $port = $GLOBALS['egotec_conf']['proxy']['proxy_port'];
2451  $ssl = $GLOBALS['egotec_conf']['proxy']['proxy_ssl'];
2452  $login = $GLOBALS['egotec_conf']['proxy']['proxy_login'];
2453  $password = $GLOBALS['egotec_conf']['proxy']['proxy_password'];
2454 
2455  if ($host && $port) {
2456  $options = array(
2457  'http' => array(
2458  'proxy' => ($ssl ? 'ssl://' : 'tcp://').$host.':'.$port,
2459  'request_fulluri' => true
2460  )
2461  );
2462  if ($login) {
2463  $auth = base64_encode($login . ":" . $password);
2464  $options['http']['header'] = "Proxy-Authorization: Basic $auth\r\n";
2465  }
2466  if ($context) {
2467  $options = array_merge_recursive(stream_context_get_options($context), $options);
2468  if (is_array($options['http']['header'])) {
2469  $options['http']['header'] = implode("\r\n", array_map('trim', $options['http']['header']));
2470  }
2471  }
2472  $context = stream_context_create($options);
2473  }
2474  $content = @file_get_contents($filename, false, $context);
2475  if ($context && $content === false) {
2476  // Im Fehlerfall ohne Context versuchen
2477  $content = @file_get_contents($filename);
2478  }
2479 
2480  // in UTF-8 kodieren
2481  if ($utf8 && $content) {
2482  return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
2483  } else {
2484  return $content;
2485  }
2486  }
2487 
2498  public static function file_put_contents($filename, $data, $flags = 0, $context = null) {
2499  @Ego_System::mkdir(dirname($filename));
2500  return file_put_contents($filename, $data, $flags, $context);
2501  }
2502 
2509  public static function filesize($file) {
2510  clearstatcache();
2511  return filesize($file);
2512  }
2513 
2519  public static function getCluster($site = null) {
2520  if (!Ego_System::checkLicence($GLOBALS['egotec_conf']['lib_dir'].'cluster')) {
2521  return array();
2522  }
2523  if (!$site) {
2524  $site = $GLOBALS['site'];
2525  }
2526 
2527  $count = range(1, self::MAX_CLUSTER);
2528  $cluster = array();
2529  foreach ($count as $c) {
2530  if (
2531  $site->admin['cluster']['cluster_'.$c.'_aktiv'] == 1
2532  && $site->admin['cluster']['cluster_'.$c.'_url'] != ''
2533  ) {
2534  $cluster[] = array(
2535  'url' => rtrim($site->admin['cluster']['cluster_'.$c.'_url'], '/') . '/',
2536  'id' => $c,
2537  'oneway' => (bool) $site->admin['cluster']['cluster_'.$c.'_oneway']
2538  );
2539  }
2540  }
2541  return $cluster;
2542  }
2543 
2554  public static function truncate($string, $length, $etc = '...', $break_words = false, $middle = false)
2555  {
2556  require_once('smarty/plugins/modifier.html_truncate.php');
2557  return smarty_modifier_html_truncate($string, $length, $etc, $break_words, $middle);
2558  }
2559 
2566  public static function getDesktopSite($site) {
2567  switch ($site->site['type']) {
2568  case 'content':
2569  $_SESSION['_last_desktop'] = array(
2570  'name' => $site->name,
2571  'language' => $site->language
2572  );
2573  break;
2574 
2575  case 'media':
2576  if (is_array($_SESSION['_last_desktop'])) {
2577  $_site = new Site(
2578  $_SESSION['_last_desktop']['name'],
2579  $_SESSION['_last_desktop']['language']
2580  );
2581  if ($_site->site['media'] == $site->name)
2582  {
2583  return $_site;
2584  }
2585  }
2586  foreach (Ego_System::getAllSites() as $_site) {
2587  if (
2588  $_site->site['media'] == $site->name
2589  && $_site->name != $site->name
2590  ) {
2591  return $_site;
2592  }
2593  }
2594  break;
2595 
2596  case 'external':
2597  if (is_array($_SESSION['_last_desktop'])) {
2598  $_site = new Site(
2599  $_SESSION['_last_desktop']['name'],
2600  $_SESSION['_last_desktop']['language']
2601  );
2602  return $_site;
2603  }
2604  return new Site();
2605  }
2606  return $site;
2607  }
2608 
2614  public static function getLatestEgotecVersion() {
2615  require_once('base/Ego_SVN.php');
2616  require_once('base/SVN_Updater.php');
2617  require_once('base/Ego_Licence.php');
2618 
2619  $licence = new Ego_Licence();
2620  if ($licence->licence['soap']['login'] && $licence->licence['soap']) {
2621  $lokale_version = explode(' ', $GLOBALS['egotec_version']);
2622  $path = SVN_Updater::$svnPath;
2623  $svn = new Ego_SVN(SVN_Updater::$svnServer, SVN_Updater::$svnRepository, $path);
2624  $svn->setAuth($licence->licence['soap']['login'], $licence->licence['soap']['password']);
2625  $versionen = $svn->getFileList();
2626  $_versionen = array();
2627  foreach ($versionen as $v)
2628  {
2629  $v = trim($v['name'], '/');
2630  $_versionen[] = $v;
2631  }
2632  natsort($_versionen);
2633  $_versionen = array_reverse($_versionen);
2634  return $_versionen[0];
2635  } else {
2636  return null;
2637  }
2638  }
2639 
2647  public static function getDiff($diff1, $diff2) {
2648  require_once('diff/Ego_Diff.php');
2649  // Javascript Code ignorieren
2650  $jscripts = array();
2651  while (preg_match('/<script[^>]+type="text\/javascript"[^>]*>(.*?)<\/script>/ims', $diff1, $m))
2652  {
2653  $key = '__EGOTEC__JS__'.md5($m[0]).'__JS__EGOTEC__';
2654  $jscripts[$key] = $m[0];
2655  $diff1 = str_replace($m[0], $key, $diff1);
2656  $diff2 = str_replace($m[0], $key, $diff2);
2657  }
2658  $diff = new Ego_Diff();
2659  $result = $diff->compare($diff2, $diff1, false);
2660  // Javascript Code wieder rein schreiben
2661  foreach ($jscripts as $key => $js)
2662  {
2663  $result = str_replace($key, $js, $result);
2664  }
2665  return $result;
2666  }
2667 
2675  public static function getExceptionURL($params = array(), $placeholder = false) {
2676  $content = '#';
2677  if ($placeholder) {
2678  $media = $GLOBALS['egotec_conf']['url_dir'].'bin/media/error.php';
2679  } else {
2680  $media = $GLOBALS['egotec_conf']['url_dir'].'pub/missing_file.gif';
2681  }
2682  if ($params['site']) {
2683  try {
2684  $site = new Site($params['site']);
2685  } catch (Site_Exception $e) {
2686  $site = null;
2687  }
2688  if ($site) {
2689  if (
2690  $site->site['type'] == 'media'
2691  && ($params['width'] || $params['height'])
2692  ) {
2693  return $media.'?'.http_build_query(
2694  array(
2695  'width' => $params['width'],
2696  'height' => $params['height']
2697  )
2698  );
2699  } else {
2700  return $content;
2701  }
2702  }
2703  }
2704  return $content;
2705  }
2706 
2732  public static function getFallbackFile($type, $name, $path, $skip = array('module'), $url = false, $relative = false, $parent = '') {
2733  $cache = self::getCache();
2734  $cache_key = 'getFallbackFile' . md5(json_encode(func_get_args()));
2735  $result = $cache->get($cache_key);
2736 
2737  if ($result === null) {
2738  $result = '';
2739 
2740  $path = ltrim($path, '/');
2741  $files = array(
2742  'custom' => array(
2743  'path' => $GLOBALS['egotec_conf'][$type . '_dir'],
2744  'url' => $GLOBALS['egotec_conf']['url_dir'] . $type . '/',
2745  'file' => $name . '/' . $path
2746  ),
2747  'parent_custom' => array(
2748  'path' => $GLOBALS['egotec_conf'][$type . '_dir'],
2749  'url' => $GLOBALS['egotec_conf']['url_dir'] . $type . '/',
2750  'file' => $parent . '/' . $path
2751  ),
2752  'parent_theme' => array(
2753  'path' => $GLOBALS['egotec_conf']['pub_dir'],
2754  'url' => $GLOBALS['egotec_conf']['url_dir'] . 'pub/',
2755  'file' => 'theme/' . $parent . '/' . $type . '/' . $path
2756  ),
2757  'global' => array(
2758  'path' => $GLOBALS['egotec_conf'][$type . '_dir'],
2759  'url' => $GLOBALS['egotec_conf']['url_dir'] . $type . '/',
2760  'file' => '_global/' . $path
2761  ),
2762  'system' => array(
2763  'path' => $GLOBALS['egotec_conf']['lib_dir'],
2764  'url' => $GLOBALS['egotec_conf']['url_dir'] . 'lib/',
2765  'file' => 'type/' . $type . '/' . $path
2766  ),
2767  'module' => array(
2768  'path' => $GLOBALS['egotec_conf']['bin_dir'],
2769  'url' => $GLOBALS['egotec_conf']['url_dir'] . 'bin/',
2770  'file' => 'type/skin/' . $path
2771  )
2772  );
2773  if (empty($name)) {
2774  $skip[] = 'custom';
2775  }
2776  if (empty($parent)) {
2777  $skip[] = 'parent_custom';
2778  $skip[] = 'parent_theme';
2779  } elseif ($type != 'skin') {
2780  $skip[] = 'parent_custom';
2781  }
2782  foreach ($files as $key => $file) {
2783  $path_file = $file['path'] . $file['file'];
2784  $url_file = $file['url'] . $file['file'];
2785  if ($relative) {
2786  $pos = strpos($url_file, $GLOBALS['egotec_conf']['url_dir']);
2787  if ($pos === 0) {
2788  $url_file = substr_replace(
2789  $url_file,
2790  '',
2791  0,
2792  strlen($GLOBALS['egotec_conf']['url_dir'])
2793  );
2794  }
2795  }
2796  if (!in_array($key, $skip) && is_file($path_file)) {
2797  $result = $url ? $url_file : $path_file;
2798  break;
2799  }
2800  }
2801 
2802  $cache->set($cache_key, $result);
2803  }
2804 
2805  return $result;
2806  }
2807 
2823  public static function getFiles($type, $name, $path, $skip = array(), $parent = '', $return_path = false, $get_variants = true) {
2824  $cache = self::getCache();
2825  $cache_key = 'getFiles' . md5(json_encode(func_get_args()));
2826  $result = $cache->get($cache_key);
2827 
2828  if ($result === null) {
2829  $original_path = $path;
2830  $original_skip = $skip;
2831 
2835  $result = new stdClass();
2836  $result->{'_empty'} = $GLOBALS['auth']->translate('Standard');
2837 
2838  $files = array(
2839  'custom' => array(
2840  'path' => $GLOBALS['egotec_conf'][$type . '_dir'],
2841  'file' => $name . '/' . $path
2842  ),
2843  'parent_custom' => array(
2844  'path' => $GLOBALS['egotec_conf'][$type . '_dir'],
2845  'file' => $parent . '/' . $path
2846  ),
2847  'parent_theme' => array(
2848  'path' => $GLOBALS['egotec_conf']['egotec_dir'] . 'pub/',
2849  'file' => 'theme/' . $parent . '/' . $type . '/' . $path
2850  ),
2851  'global' => array(
2852  'path' => $GLOBALS['egotec_conf'][$type . '_dir'],
2853  'file' => '_global/' . $path
2854  ),
2855  'pub' => array(
2856  'path' => $GLOBALS['egotec_conf']['pub_dir'],
2857  'url' => $GLOBALS['egotec_conf']['url_dir'] . 'pub/',
2858  'file' => 'type/' . $type . '/' . $path
2859  ),
2860  'system' => array(
2861  'path' => $GLOBALS['egotec_conf']['lib_dir'],
2862  'file' => 'type/' . $type . '/' . $path
2863  ),
2864  'module' => array(
2865  'path' => $GLOBALS['egotec_conf']['bin_dir'],
2866  'file' => 'type/skin/' . $path
2867  )
2868  );
2869  if (empty($name)) {
2870  $skip[] = 'custom';
2871  }
2872  if (empty($parent)) {
2873  $skip[] = 'parent_custom';
2874  $skip[] = 'parent_theme';
2875  }
2876  foreach ($files as $key => $file) {
2877  if (!in_array($key, $skip)) {
2878  $list = glob($file['path'] . $file['file']);
2879  if (!empty($list)) {
2880  foreach ($list as $match) {
2881  if (@is_file($match)) {
2882  $parts = explode('.', basename($match));
2883  $i = $get_variants ? count($parts) - 2 : 0;
2884  if ($i >= 0 && $parts[$i]) {
2885  $variant = $parts[$i];
2886  if ($return_path) {
2887  $relative_path = substr($match, strlen($GLOBALS['egotec_conf']['egotec_dir']));
2888  $result->{$relative_path} = ucfirst($variant);
2889  } else {
2890  $result->{$variant} = ucfirst($variant);
2891  }
2892  }
2893  }
2894  }
2895  }
2896  }
2897  }
2898  $result = (array) $result;
2899  if (strpos($original_path, '.html') !== false) {
2900  // Bei .html Dateien auch nach .tpl Dateien suchen
2901  $result = array_merge($result, self::getFiles($type, $name, str_replace('.html', '.tpl', $original_path), $original_skip, $parent, $return_path, $get_variants));
2902  }
2903 
2904  $cache->set($cache_key, $result);
2905  }
2906 
2907  return $result;
2908  }
2909 
2923  public static function getVariantFiles($type, $name, $path, $skip = array(), $parent = '') {
2924  $path = substr_replace($path, '.*', strrpos($path, '.'), 0);
2925  return self::getFiles($type, $name, $path, $skip, $parent);
2926  }
2927 
2934  public static function getUrlParams($url = '') {
2935  $params = array();
2936  if (!$url && $_REQUEST['_url']) {
2937  $url = $_REQUEST['_url'];
2938  if ($url[0] == '/') {
2939  $url = substr($url, 1);
2940  }
2941  if ($query_pos = strpos($url, '?')) {
2942  $url = substr($url, 0, $query_pos);
2943  }
2944  $dot_pos = strrpos($url, '.');
2945  if ($dot_pos !== false) {
2946  $url = substr($url, 0, $dot_pos);
2947  }
2948  }
2949  if ($url) {
2950  // Query Parameter
2951  parse_str(parse_url($url, PHP_URL_QUERY), $params);
2952 
2953  if (strpos($url, 'index.php') === false) {
2954  // Rewrite1 Parameter (-key-value)
2955  $url = explode('-', parse_url($url, PHP_URL_PATH));
2956  $value = end($url);
2957  while ($value !== false)
2958  {
2959  $value = preg_replace('/\..*?$/', '', $value);
2960  $key = prev($url);
2961  if ($key === false || strpos($key, '/') !== false)
2962  {
2963  break;
2964  }
2965  $params[$key] = $value;
2966  $key = urldecode($key);
2967  $value = prev($url);
2968  }
2969  $params = array_reverse($params);
2970  }
2971  }
2972  return $params;
2973  }
2974 
2980  public static function getRequest($request = array()) {
2981  if (empty($request)) {
2982  $request = $_REQUEST;
2983  foreach ($_COOKIE as $key => $val) {
2984  unset($request[$key]);
2985  }
2986  }
2987  unset($request['_url']);
2988  unset($request['p']);
2989  unset($request['id']);
2990  unset($request['site']);
2991  unset($request['lang']);
2992  unset($request['skin']);
2993  unset($request['no301']);
2994  unset($request['return_absolute']);
2995  unset($request['return_relative']);
2996  unset($request['return_original']);
2997  unset($request['return_https']);
2998  return $request;
2999  }
3000 
3007  public static function cleanUrl($url) {
3008  if (preg_match('/^([^\/:]+:\/\/)?(.*?)$/', $url, $matches)) {
3009  $protocol = $matches[1];
3010  $uri = $matches[2];
3011  $uri = str_replace('//', '/', $uri);
3012  $url = $protocol.$uri;
3013  }
3014  return $url;
3015  }
3016 
3023  public static function isCurrentUrl($url) {
3024  if (isset($_SERVER['REQUEST_URI'])) {
3025  $data = array(
3026  array('url' => ltrim(preg_replace('#^https?://.*?/#i', '', rawurldecode($_SERVER['REQUEST_URI'])), '/')),
3027  array('url' => ltrim(preg_replace('#^https?://.*?/#i', '', rawurldecode($url)), '/'))
3028  );
3029  if ($data[0]['url'] != $data[1]['url']) {
3030  // Die URLs können trotzdem identisch sein
3031  $data[0]['info'] = self::getUrlInfo($data[0]['url']);
3032  $data[1]['info'] = self::getUrlInfo($data[1]['url']);
3033  unset($data[0]['info']['params']['p'], $data[1]['info']['params']['p']);
3034  if (
3035  $data[0]['info']['suffix'] == $data[1]['info']['suffix']
3036  && sizeof($data[0]['info']['params']) == sizeof($data[1]['info']['params'])
3037  && sizeof($data[0]['info']['parts']) == sizeof($data[1]['info']['parts'])
3038  ) {
3039  // Die Bestandteile stimmen überein, prüfen ob die Parameter identisch sind
3040  foreach ($data[0]['info']['params'] as $key => $value) {
3041  if ($value != $data[1]['info']['params'][$key]) {
3042  return false;
3043  }
3044  }
3045  // Die Parameter stimmen überein, prüfen ob die Namen identisch sind
3046  foreach ($data[0]['info']['parts'] as $key => $value) {
3047  $value = mb_strtoupper($value);
3048  $data[1]['info']['parts'][$key] = mb_strtoupper($data[1]['info']['parts'][$key]);
3049  if (
3050  $value != $data[1]['info']['parts'][$key]
3051  && $value != urldecode($data[1]['info']['parts'][$key])
3052  ) {
3053  return false;
3054  }
3055  }
3056  return true;
3057  }
3058  } else {
3059  return true;
3060  }
3061  }
3062  return false;
3063  }
3064 
3072  public static function getUrlInfo($url, $encode = false) {
3073  $url = str_replace('&amp;', '&', $url);
3074  $info = array(
3075  'suffix' => null,
3076  'params' => self::getUrlParams($url),
3077  'query' => (string) parse_url($url, PHP_URL_QUERY),
3078  'protocol' => ($scheme = parse_url($url, PHP_URL_SCHEME)) ? "$scheme://" : null,
3079  'anchor' => parse_url($url, PHP_URL_FRAGMENT)
3080  );
3081 
3082  // Suffix ermitteln
3083  if (($dot = strrpos($url, '.')) !== false) {
3084  $info['suffix'] = preg_split('/[\/?#]/', substr($url, $dot))[0];
3085  }
3086 
3087  // Mediapool ermitteln
3088  if (preg_match('/\/_\/([^?#]+)/', $url, $match)) {
3089  $info['params']['pool'] = urldecode($match[1]);
3090  }
3091 
3092  // Bestandteile ermitteln
3093  $info['parts'] = array_filter(explode('/', parse_url($url, PHP_URL_PATH)), function($value) {
3094  return $value !== '';
3095  });
3096  $info['parts'] = array_map(function($value) {
3097  if (preg_match('/^(.*?)\./', $value, $match)) {
3098  $value = $match[1];
3099  }
3100  if (substr_count($value, '-') % 2 == 0) {
3101  $value = preg_replace('/^([^-]*).*?$/', '$1', $value);
3102  } else {
3103  $value = preg_replace('/^([^-]*-[^-]*).*?$/', '$1', $value);
3104  }
3105  return $value;
3106  }, $info['parts']);
3107 
3108  // URL wurde unkodiert übergeben
3109  if ($encode) {
3110  $info['parts'] = array_map('self::encode_path', $info['parts']);
3111  }
3112 
3113  return $info;
3114  }
3115 
3122  public static function getFileInfo($file) {
3123  if (self::file_exists($file)) {
3124  $cache = self::getCache();
3125  $cache_key = 'getFileInfo' . md5($file);
3126  $info = $cache->get($cache_key);
3127 
3128  if ($info === null || filemtime($file) > $cache->getLastChanged()) {
3129  $info = array();
3130 
3131  $finfo = new finfo();
3132  $mime_type = $finfo->file($file, FILEINFO_MIME_TYPE);
3133 
3134  $info['size'] = @filesize($file);
3135  $info['mime'] = $mime_type;
3136 
3137  if (stripos($mime_type, 'video/') === 0) {
3138  // Bei Videos die Informationen über ffprobe (ffmpeg) ermitteln
3139  // Dimensionen
3140  self::exec('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=height,width', '-of', 'csv=s=x:p=0', $file], $output);
3141  $s = explode('x', $output[0]);
3142  $info['width'] = (int)$s[0];
3143  $info['height'] = (int)$s[1];
3144 
3145  // Dauer
3146  self::exec('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', $file], $output);
3147  $s = ceil((float) $output[0]);
3148  $info['duration'] = $s
3149  ? sprintf('%02d:%02d:%02d', $s / 3600, $s / 60 % 60, $s % 60)
3150  : '--:--:--';
3151  } elseif ($size = @getimagesize($file)) {
3152  // Bei Bildern die Breite und Höhe ermitteln
3153  $info['width'] = $size[0];
3154  $info['height'] = $size[1];
3155  }
3156 
3157  $cache->set($cache_key, $info);
3158  }
3159  return $info;
3160  }
3161  return array();
3162  }
3163 
3169  public static function getVirtualHosts() {
3170  $virtual_hosts = $h = array();
3171 
3172  $file_name = $GLOBALS['egotec_conf']['var_dir'].'conf/virtual_hosts.ini';
3173  if (self::file_exists($file_name)) {
3174  $virtual_hosts = parse_ini_file($file_name,1);
3175  }
3176  foreach($virtual_hosts as $k => $v) {
3177  $h[mb_strtolower($k)] = $v;
3178  }
3179  return $h;
3180  }
3181 
3188  public static function getFormats($type) {
3189  switch ($type) {
3190  case 'image':
3191  return array('jpg', 'jpeg', 'gif', 'png', 'bmp', 'svg', 'ico');
3192  case 'web':
3193  return array('image/gif', 'image/png', 'image/jpeg', 'image/jpg');
3194  case 'archive':
3195  return array('zip', 'rar', 'tar', 'gz', 'bz2', '7z');
3196  case 'video':
3197  return array('mp4', 'ogg', 'webm');
3198  default:
3199  throw new Exception('Format type does not exist.');
3200  }
3201  }
3202 
3213  public static function sortPages($pages, $sorttype = 'field', $sortby = 'id', $sortdirection = "asc")
3214  {
3215  // Es kann nur mit Arrays sortiert werden
3216  if (gettype($pages) == 'object')
3217  {
3218  $pagesnew = array();
3219  foreach ($pages as $p)
3220  {
3221  $pagesnew[] = $p;
3222  }
3223  $pages = $pagesnew;
3224  }
3225 
3226  if (is_array($pages))
3227  {
3228  usort($pages, function($a, $b) use ($sorttype, $sortby, $sortdirection) {
3229  $r = function($s) {
3230  return str_replace(
3231  array('ä', 'ö', 'ü', 'ß'),
3232  array('ae', 'oe', 'ue', 'ss'),
3233  $s
3234  );
3235  };
3236  $v1 = $r(mb_strtolower(Ego_System::getAssocValue(is_object($a) ? $a->{$sorttype} : $a[$sorttype], $sortby)));
3237  $v2 = $r(mb_strtolower(Ego_System::getAssocValue(is_object($b) ? $b->{$sorttype} : $b[$sorttype], $sortby)));
3238  return $sortdirection == 'asc' ? strnatcmp($v1, $v2) : strnatcmp($v2, $v1);
3239  });
3240  }
3241  else
3242  {
3243  return array();
3244  }
3245  return $pages;
3246  }
3247 
3254  public static function getProtocol($https = false) {
3255  return 'http' . ($https || $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
3256  ? 's' : '') . '://';
3257  }
3258 
3264  public static function getBaseUrl() {
3265  return ($_SERVER['HTTP_HOST']
3266  ? self::getProtocol().$_SERVER['HTTP_HOST']
3267  : rtrim($GLOBALS['egotec_conf']['local_server_access'], '/'))
3268  .$GLOBALS['egotec_conf']['url_dir'];
3269  }
3270 
3277  public static function getDiskUsage($recalc = false) {
3278  $cache_file = $GLOBALS['egotec_conf']['tmp_dir'].'disk_usage';
3279  if (!$recalc && self::file_exists($cache_file)) {
3280  $usage = unserialize(self::file_get_contents($cache_file));
3281  } else {
3282  @set_time_limit(0);
3283  @clearstatcache();
3284  $usage = array(
3285  'elements' => array(
3286  'system' => array(
3287  'all' => array(
3288  'label' => $GLOBALS['auth']->translate('System'),
3289  'color' => '#f8482b',
3290  'dirs' => array(
3291  $GLOBALS['egotec_conf']['lib_dir'],
3292  $GLOBALS['egotec_conf']['bin_dir'],
3293  $GLOBALS['egotec_conf']['egotec_dir'].'pub'.DIRECTORY_SEPARATOR
3294  )
3295  )
3296  ),
3297  'data' => array(
3298  'backup' => array(
3299  'label' => $GLOBALS['auth']->translate('Backups'),
3300  'color' => '#0e88f0',
3301  'dirs' => array(
3302  $GLOBALS['egotec_conf']['backup_dir']
3303  )
3304  ),
3305  'cache' => array(
3306  'label' => $GLOBALS['auth']->translate('Cache'),
3307  'color' => '#2fedac',
3308  'dirs' => array(
3309  $GLOBALS['egotec_conf']['cache_dir'],
3310  $GLOBALS['egotec_conf']['cachemedia_dir']
3311  )
3312  ),
3313  'log' => array(
3314  'label' => $GLOBALS['auth']->translate('Logs'),
3315  'color' => '#edc72f',
3316  'dirs' => array(
3317  $GLOBALS['egotec_conf']['log_dir']
3318  )
3319  ),
3320  'tmp' => array(
3321  'label' => $GLOBALS['auth']->translate('Temporär'),
3322  'color' => '#efd2de',
3323  'dirs' => array(
3324  $GLOBALS['egotec_conf']['tmp_dir']
3325  )
3326  ),
3327  'media' => array(
3328  'label' => $GLOBALS['auth']->translate('Medien'),
3329  'color' => '#4fac0b',
3330  'dirs' => array(
3331  $GLOBALS['egotec_conf']['var_dir'].'media'.DIRECTORY_SEPARATOR
3332  )
3333  )
3334  ),
3335  'customer' => array(
3336  'site' => array(
3337  'label' => $GLOBALS['auth']->translate('Skripte'),
3338  'color' => '#deefd2',
3339  'dirs' => array(
3340  $GLOBALS['egotec_conf']['site_dir']
3341  )
3342  ),
3343  'skin' => array(
3344  'label' => $GLOBALS['auth']->translate('Designs'),
3345  'color' => '#8813f5',
3346  'dirs' => array(
3347  $GLOBALS['egotec_conf']['skin_dir']
3348  )
3349  )
3350  )
3351  ),
3352  'total' => array(),
3353  'used' => array(),
3354  'free' => array(),
3355  'unknown' => array(),
3356  'dirs' => array(),
3357  'date' => time(),
3358  'time' => microtime(true),
3359  'config' => array(
3360  'bytes' => true
3361  )
3362  );
3363  $total = (float) @disk_total_space($GLOBALS['egotec_conf']['egotec_dir']);
3364  $origin = md5($total);
3365  $usage['total'][$origin] = $total;
3366  $usage['used'][$origin] = 0;
3367  $usage['free'][$origin] = 0;
3368  $usage['unknown'][$origin] = 0;
3369  $usage['dirs'][$origin] = $GLOBALS['egotec_conf']['egotec_dir'];
3370  $total_values = array($usage['total'][$origin]);
3371  foreach ($usage['elements'] as $element => $types) {
3372  foreach ($types as $type => $data) {
3373  foreach ($data['dirs'] as $dir) {
3374  if (!self::file_exists($dir)) {
3375  egotec_warning_log("Path '$dir' doesn't exist.");
3376  continue;
3377  }
3378  $cms_dir = self::getDirectorySize($dir);
3379  $used = (float) $cms_dir['size'];
3380  $usage['elements'][$element][$type]['value'] += $used;
3381  if (strpos($dir, $GLOBALS['egotec_conf']['egotec_dir']) !== 0) {
3382  $base_dir = substr($dir, 0,
3383  strrpos(rtrim($dir, DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR) + 1
3384  );
3385  $total = (float) @disk_total_space($base_dir);
3386  if ($total > 0) {
3387  $skip = false;
3388  foreach ($total_values as $size) {
3389  if ($total == $size) {
3390  $skip = true;
3391  break;
3392  }
3393  }
3394  if (!$skip) {
3395  $origin = md5($total);
3396  $usage['total'][$origin] += $total;
3397  $usage['dirs'][$origin] = $base_dir;
3398  $total_values[] = $total;
3399  }
3400  }
3401  } else {
3402  $origin = md5($total_values[0]);
3403  }
3404  $usage['used'][$origin] += $used;
3405  $usage['elements'][$element][$type]['origin'] = $origin;
3406  }
3407  }
3408  }
3409  foreach ($usage['total'] as $origin => $value) {
3410  $usage['free'][$origin] = $value - $usage['used'][$origin];
3411 
3412  // Unbekannten, genutzten Speicherplatz ermitteln
3413  $free = (float) @disk_free_space($usage['dirs'][$origin]);
3414  if ($free > 0 && $free < $usage['free'][$origin]) {
3415  $usage['unknown'][$origin] = $usage['free'][$origin] - $free;
3416  $usage['used'][$origin] += $usage['unknown'][$origin];
3417  $usage['free'][$origin] = $free;
3418  } else {
3419  $usage['unknown'][$origin] = 0;
3420  }
3421  }
3422  $usage['time'] = microtime(true) - $usage['time'];
3423  @file_put_contents($cache_file, serialize($usage));
3424  }
3425  return $usage;
3426  }
3427 
3433  public static function getIp() {
3434  return isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
3435  }
3436 
3443  public static function gzdecode($string) {
3444  if (function_exists('gzdecode')) {
3445  return gzdecode($string);
3446  } else {
3447  $tmp = tempnam($GLOBALS['egotec_conf']['tmp_dir'], 'gzDecode');
3448  @file_put_contents($tmp, $string);
3449  ob_start();
3450  readgzfile($tmp);
3451  $output = ob_get_clean();
3452  @unlink($tmp);
3453  return $output;
3454  }
3455  }
3456 
3468  public static function replaceLinks($content, $search, $replace) {
3469  if (preg_match_all('/index\.php\?[^>"\' ]+/msi', $content, $matches)) {
3470  foreach ($matches[0] as $url) {
3471  $info = self::getUrlInfo($url);
3472  if (!empty($info['params'])) {
3473  $continue = false;
3474  foreach ($search as $param => $value) {
3475  if (
3476  !isset($info['params'][$param])
3477  || $info['params'][$param] != $value
3478  ) {
3479  $continue = true;
3480  } elseif (isset($replace[$param])) {
3481  $info['params'][$param] = $replace[$param];
3482  }
3483  }
3484  if ($continue) {
3485  continue;
3486  } else {
3487  $query = http_build_query($info['params']);
3488  $content = str_replace($url, 'index.php?'.$query, $content);
3489  }
3490  }
3491  }
3492  }
3493  return $content;
3494  }
3495 
3503  public static function base64Encode($s) {
3504  return strtr(base64_encode($s), '+/=', '-_,');
3505  }
3506 
3514  public static function base64Decode($s) {
3515  return base64_decode(strtr($s, '-_,', '+/='));
3516  }
3517 
3524  public static function arrayValuesRecursive($array) {
3525  $result = array();
3526  foreach ($array as $value) {
3527  if (is_array($value)) {
3528  $result = array_merge($result, self::arrayValuesRecursive($value));
3529  } else {
3530  $result[] = $value;
3531  }
3532  }
3533  return array_unique($result);
3534  }
3535 
3544  public static function arrayFlatRecursive($array, $callback = null) {
3545  $result = array();
3546  array_walk_recursive($array, function($a, $k) use (&$result, $callback) {
3547  if (!is_array($result[$k])) {
3548  $result[$k] = array();
3549  }
3550  if (!empty($callback)) {
3551  $a = call_user_func_array($callback, array($a));
3552  }
3553  array_push($result[$k], $a);
3554  $result[$k] = array_values(array_unique($result[$k]));
3555  });
3556  return $result;
3557  }
3558 
3564  public static function isDevMode() {
3565  return $GLOBALS['egotec_conf']['devserver'] || self::file_exists($GLOBALS['egotec_conf']['egotec_dir'].'.svn');
3566  }
3567 
3574  public static function isStatistic($token_auth) {
3575  // Ist das Statistikmodul vorhanden?
3576  return self::checkLicence($GLOBALS['egotec_conf']['lib_dir'].'stats') && $GLOBALS['egotec_conf']['piwik']['auth_url'] && $token_auth;
3577  }
3578 
3586  public static function getAssocValue($a, $k) {
3587  if (($p = strstr($k, '.', true)) !== false) {
3588  if (is_array($a)) {
3589  return self::getAssocValue($a[$p], ltrim(strstr($k, '.'), '.'));
3590  }
3591  return null;
3592  }
3593  return $a[$k];
3594  }
3595 
3604  public static function setAssocValue(&$a, $k, $v) {
3605  if (($p = strstr($k, '.', true)) !== false) {
3606  return self::setAssocValue($a[$p], ltrim(strstr($k, '.'), '.'), $v);
3607  }
3608  $a[$k] = $v;
3609  return $a[$k];
3610  }
3611 
3621  public static function getJSON($path, $values = array(), $combine = false, $ignore = []) {
3622  $file = self::file_get_contents($path);
3623  if (!empty($file) && is_array($values2 = json_decode(trim($file), true))) {
3624  $new_values = array_replace_recursive($values, $values2);
3625  if ($combine) {
3626  $recursive = function($value, $keys = []) use (&$recursive, $values, $ignore) {
3627  if (!empty($keys) && in_array(implode('.', $keys), $ignore)) {
3628  return $value;
3629  } elseif (is_array($value)) {
3630  foreach ($value as $k => $v) {
3631  $value[$k] = $recursive($v, array_merge($keys, [$k]));
3632  }
3633  } elseif (
3634  is_string($value)
3635  && in_array($value[0], ['+', '-'])
3636  ) {
3637  $old_value = Ego_System::getAssocValue($values, implode('.', $keys));
3638  if ($old_value === null) {
3639  $old_value = '';
3640  }
3641  $array_value = explode(',', substr($value, 1));
3642  switch ($value[0]) {
3643  case '+':
3644  $value = implode(',', array_unique(array_merge(explode(',', $old_value), $array_value)));
3645  break;
3646  case '-':
3647  $value = implode(',', array_unique(array_diff(explode(',', $old_value), $array_value)));
3648  }
3649  return trim($value, ',');
3650  }
3651  return $value;
3652  };
3653  return $recursive($new_values);
3654  }
3655  return $new_values;
3656  }
3657  return $values;
3658  }
3659 
3667  public static function setJSON($path, $values = array()) {
3668  return self::file_put_contents($path, str_replace(" ", "\t", json_encode($values, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)));
3669  }
3670 
3677  public static function getChecksum($value) {
3678  return md5(is_array($value) ? json_encode($value, JSON_FORCE_OBJECT) : $value);
3679  }
3680 
3687  public static function getCache($path = '_system')
3688  {
3689  $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
3690  switch ($GLOBALS['egotec_conf']['site_cache_type']) {
3691  case 'apc':
3692  require_once('base/Ego_Cache_apc.php');
3693  $cache = new Ego_Cache_apc($path);
3694  break;
3695  case 'apcu':
3696  require_once('base/Ego_Cache_apcu.php');
3697  $cache = new Ego_Cache_apcu($path);
3698  break;
3699  case 'shm':
3700  require_once('base/Ego_Cache_shm.php');
3701  $cache = new Ego_Cache_shm($path);
3702  break;
3703  default:
3704  require_once('base/Ego_Cache_file.php');
3705  $cache = new Ego_Cache_file($path);
3706  }
3707  return $cache;
3708  }
3709 
3717  public static function isEqual($a, $b) {
3718  return md5(serialize($a)) == md5(serialize($b));
3719  }
3720 
3737  public static function createCSV($path, $data, $delimiter = ',', $enclosure = '"', $escape_char = '\'') {
3738  $fp = fopen($path, 'a');
3739  foreach ($data as $line) {
3740  fputcsv($fp, $line, $delimiter, $enclosure, $escape_char);
3741  }
3742  fclose($fp);
3743  }
3744 
3765  public static function createXML($path, $data, $root = 'root', $version = '1.0', $encoding = 'UTF-8') {
3766  $xml = '<?xml version="' . $version . '" encoding="' . $encoding . '"?>';
3767  $recursive = function($data) use (&$recursive) {
3768  $result = '';
3769  foreach ($data as $key => $value) {
3770  if (is_array($value)) {
3771  $result .= "<{$key}>" . $recursive($value) . "</{$key}>";
3772  } else {
3773  if (is_string($value)) {
3774  $value = "<![CDATA[{$value}]]>";
3775  }
3776  $result .= "<{$key}>{$value}</{$key}>";
3777  }
3778  }
3779  return $result;
3780  };
3781  self::file_put_contents($path, "{$xml}<{$root}>" . $recursive($data) . "</{$root}>");
3782  }
3783 
3789  public static function getContrastColor($color)
3790  {
3791  $hex = str_replace("#","",$color);
3792 
3793  if (strlen($hex) != 3 && strlen($hex) != 6) {
3794  return '#000000';
3795  } elseif (strlen($hex) == 3) {
3796  $hex = str_split($hex);
3797  $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
3798  }
3799 
3800  $r = hexdec(substr($hex,0,2));
3801  $g = hexdec(substr($hex,2,2));
3802  $b = hexdec(substr($hex,4,2));
3803  $yiq = (($r*299)+($g*587)+($b*114))/1000;
3804  return ($yiq >= 128) ? '#000000' : '#ffffff';
3805  }
3806 
3814  public static function includeHtml($src, $once = true) {
3815  $html = '';
3816 
3817  if (!$once || !in_array($src, self::$includedHtml)) {
3818  $type = mb_strtolower(ltrim(strrchr($src, '.'), '.'));
3819  switch ($type) {
3820  case 'css':
3821  $html = '<link rel="stylesheet" property="stylesheet" href="' . $src . '" type="text/css" />';
3822  break;
3823  case 'js':
3824  $html = '<script type="text/javascript" src="' . $src . '"></script>';
3825  }
3826  self::$includedHtml[] = $src;
3827  }
3828 
3829  return $html;
3830  }
3831 
3837  public static function isNobody() {
3838  return $_SESSION['auth_id'] === null;
3839  }
3840 
3846  public static function getAdminMail()
3847  {
3848  return $GLOBALS['egotec_conf']['admin_mail'] ? $GLOBALS['egotec_conf']['admin_mail'] : 'support@egotec.com';
3849  }
3850 
3860  public static function checkRequirePath($path) {
3861  if (
3862  !preg_match('#\.php$#', $path) // nur PHP Dateien
3863  ) {
3864  Ego_System::header(400);
3865  exit;
3866  }
3867  return $path;
3868  }
3869 
3873  private static function shell(String $php_command, String $command, Array $params = array(), Array &$output = null, &$return_var = null) {
3874  if (!(
3875  strpos($command, " ") === false // kein Leerzeichen im Kommando
3876  || ($command[0] == '"' && $command[-1] == '"' && strpos(substr($command, 1, -1), '"') === false) // oder korrekt escape
3877  )) throw new RuntimeException('Please use parameter binding for security reasons!');
3878 
3879  $output = [];
3880 
3881  foreach ($params as $value) {
3882  if ($value[0]=='-') {
3883  $pos = strpos($value, ' ');
3884  $pos2 = strpos($value, '=');
3885  if ($pos2 && $pos2>$pos) {
3886  $pos = $pos2;
3887  }
3888  if ($pos) {
3889  $command.= " ".substr($value, 0, $pos)." ".escapeshellarg(substr($value, $pos+1));
3890  } else {
3891  $command.= " ".$value;
3892  }
3893  } else {
3894  $command.= " ".(in_array($value, array('<', '<<', '>', '>>', '&&', '2>&1')) ? $value : escapeshellarg($value));
3895  }
3896  }
3897 
3898  egotec_warning_log($php_command.' executing '.$command);
3899 
3900  switch ($php_command) {
3901  case 'exec':
3902  return exec($command, $output, $return_var);
3903  case 'system':
3904  return system($command, $return_var);
3905  }
3906  }
3907 
3921  public static function exec(String $command, Array $params = array(), Array &$output = null, &$return_var = null) {
3922  return Ego_System::shell('exec', $command, $params, $output, $return_var);
3923  }
3924 
3937  public static function system(String $command, Array $params = array(), &$return_var = null) {
3938  $output = [];
3939  return Ego_System::shell('system', $command, $params, $output, $return_var);
3940  }
3941 
3947  public static function isLocalRequest() {
3948  return in_array(
3949  self::getIp(),
3950  $GLOBALS['egotec_conf']['local_server_ips']
3951  ? explode(',', $GLOBALS['egotec_conf']['local_server_ips'])
3952  : self::getDefaultLocalServerIps()
3953  );
3954  }
3955 
3961  public static function getDefaultLocalServerIps() {
3962  return array("127.0.0.1", "localhost", "::1", "0:0:0:0:0:0:0:1", $_SERVER['SERVER_ADDR']);
3963  }
3964 }
static includeHtml($src, $once=true)
static endless($string='', $flush=true)
Definition: Ego_System.php:748
static getFormats($type)
static getFilePath($dir, $file)
const LANG_DOESNT_EXIST
Definition: Site.php:13
static redirect($location, $header=302)
Definition: Ego_System.php:944
static pathinfo($string)
Definition: Ego_System.php:275
static getBaseUrl()
static getChecksum($value)
static isDevMode()
const SITE_DOESNT_EXIST
Definition: Site.php:12
static getVariantFiles($type, $name, $path, $skip=array(), $parent='')
static $fileList
Definition: Ego_System.php:34
static checkLicence($ini_path)
Definition: Ego_System.php:963
static file_put_contents($filename, $data, $flags=0, $context=null)
static stringEncode($string, $from='UTF-8', $to='UTF-8')
Definition: Ego_System.php:448
static getAdminMail()
static filterData($data)
Definition: Ego_System.php:391
static eternalCache($active)
static deldir($location, $del=true, $without='', $rename=true)
Definition: Ego_System.php:593
static clearNginxCache()
Definition: Ego_System.php:205
static checkRequirePath($path)
static basename($path)
Definition: Ego_System.php:306
static clearMediaCache()
Definition: Ego_System.php:210
const ADMIN_SKIN
Definition: Ego_System.php:28
static $allSites
Definition: Ego_System.php:135
static getLatestEgotecVersion()
const REGEX_EMAIL
Definition: Ego_System.php:21
static urltopage($url, $params=array(), $only_site=false, $error_page=false, $commit_params=false)
static base64Decode($s)
static encode_path($url, $id=0)
static noCache()
Definition: Ego_System.php:929
static clearPageLocks()
static getDefaultLocalServerIps()
static arrayFlatRecursive($array, $callback=null)
static getJSON($path, $values=array(), $combine=false, $ignore=[])
static getAllSites($username='', $perm='', $table=false, $type='')
const REGEX_EMAIL_OPTIONAL
Definition: Ego_System.php:23
static getUrlParams($url='')
static isEmail($email)
Definition: Ego_System.php:57
static sortPages($pages, $sorttype='field', $sortby='id', $sortdirection="asc")
static flush($string='')
Definition: Ego_System.php:724
static flushHeaders($headers)
Definition: Ego_System.php:709
static file_exists($file)
static system(String $command, Array $params=array(), &$return_var=null)
static getSkins($more_themes=array())
static clearCache()
Definition: Ego_System.php:166
static parseCsvLine($str, $delimiter=';', $qualifier='"', $qualifierEscape = '\)
static isEmptyContent($str)
static parseIniFile($file)
static decode_path( $url)
static filesize($file)
static replaceLinks($content, $search, $replace)
static isCurrentUrl($url)
static byte_format($byte)
static checkRequirements()
static getCache($path='_system')
static escape($string, $esc_type='html', $char_set='UTF-8')
Definition: Ego_System.php:69
static isNobody()
static getAllSkins()
static setCronLock($expiry_date=0, $lock_msg="")
static getMimeTypes($ext='')
static clearCacheAllSites()
Definition: Ego_System.php:243
static createCSV($path, $data, $delimiter=',', $enclosure='"', $escape_char = '\)
static mkdir($dir, $mode=0755, $recursive=true)
Definition: Ego_System.php:497
static getCluster($site=null)
static isWindows()
static clearTypeCache($site_name='')
Definition: Ego_System.php:143
static write_ini_file($path, $assoc_array=array())
Definition: Ego_System.php:767
static getContrastColor($color)
static createIdentity($params)
Definition: Page.php:9173
static setAssocValue(&$a, $k, $v)
static getDiff($diff1, $diff2)
static getRequest($request=array())
static getExceptionURL($params=array(), $placeholder=false)
static getAssocValue($a, $k)
static getUrlInfo($url, $encode=false)
static log($file, $message)
static checkSSL()
static createXML($path, $data, $root='root', $version='1.0', $encoding='UTF-8')
static gzdecode($string)
static parseUrl($url)
Definition: Ego_System.php:546
static file_get_contents($filename, $utf8=true, $context=null)
static copy($src, $dest, $except='', $useLinks=false)
static setJSON($path, $values=array())
static byIdentity($identity, $param=array())
Definition: Page.php:9185
static removeCronLock()
static getDesktopSite($site)
const REGEX_EMAIL_ESCAPED
Definition: Ego_System.php:25
static checkEncoding($from='CP1252', $to='UTF-8', $original, $converted)
Definition: Ego_System.php:420
const MAX_CLUSTER
Definition: Ego_System.php:31
static base64Encode($s)
static getIp()
static cleanUrl($url)
static getProtocol($https=false)
static getFallbackFile($type, $name, $path, $skip=array('module'), $url=false, $relative=false, $parent='')
static getDbDriver()
static isEqual($a, $b)
static getFileInfo($file)
static isLocalRequest()
static dateEncode($string)
Definition: Ego_System.php:484
static commandExists($cmd)
static getDirectorySize($pfad, &$links=array())
static arrayValuesRecursive($array)
static filterNonUtf8($s, $substitute="", $strict=false)
Definition: Ego_System.php:320
static header($header, $replace=true)
Definition: Ego_System.php:833
static getVirtualHosts()
static exec(String $command, Array $params=array(), Array &$output=null, &$return_var=null)
static isStatistic($token_auth)
static getDiskUsage($recalc=false)
static getFiles($type, $name, $path, $skip=array(), $parent='', $return_path=false, $get_variants=true)
static truncate($string, $length, $etc='...', $break_words=false, $middle=false)
Definition: Site.php:29