<?php

namespace FOP;

class Files {
  
  

    // --- Statische Eigenschaften ---
  
  static private $dummyCounter = 0;

    // --- Statische Methoden ---
  
  public static function getNextDummyCounter($value) { 
    
    
    // --- BLOCK: main ---
    if ($value) return $value; self::$dummyCounter = -rand(1, 40000000); return self::$dummyCounter;
    
  }

  public static function getLastDummyCounter($value) { 
    
    
    // --- BLOCK: main ---
    if ($value) return $value; return self::$dummyCounter;
    
  }

  public static function downloadAction($id, $w = 0 , $h = 0 , $q = 70 , $disregardPermissions = false ) { 
    
    
    // --- BLOCK: access ---
    
    // --- BLOCK: main ---
    
$result = \FOP\Database::query('SELECT filename, '.qi('type').', size, data, width, height, ' . ($disregardPermissions === true /* ===, damit es niemand per GET-Parameter setzen kann */ ? '1' : 'EXISTS (
			SELECT '.qi('ID').' FROM '.qi('doc_revision').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_mail_host_box_draft_attachment').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_mail_host_box_dir_email_attachment').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('aufgabeAnhang').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_import_tbl').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND (' . (\FOP\User::getIsGuest() ? 'false' : 'true') . ')
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_import_tbl').' WHERE '.qi('summary').' = fop_files.'.qi('ID').' AND '.(((true)) ? 'true' : 'false').'
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_fints_file').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND (('.\FOP\Database::quote(\FOP\User::getBuchhaltung()).'))
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('userconfig').' WHERE '.qi('Configuration_Stammdaten_logo').' = fop_files.'.qi('ID').' AND (('.\FOP\Database::quote(\FOP\User::getAdmin()).'))
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('campaign').' WHERE '.qi('post_template').' = fop_files.'.qi('ID').' AND (('.\FOP\Database::quote(\FOP\User::getCampaign()).'))
	UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('campaignAttachment').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ((COALESCE((SELECT ('.\FOP\Database::quote(\FOP\User::getCampaign()).') FROM '.qi('campaign').' '.qi('oP3oPgne').' WHERE '.qi('oP3oPgne').'.'.qi('ID').' = '.qi('campaignAttachment').'.'.qi('campaign').' LIMIT 1), FALSE)) AND ('.\FOP\Database::quote(\FOP\User::getCampaign()).')))') . ' AS can_view FROM fop_files WHERE '.qi('ID').' = '.intval($id));

if ($result = $result->fetch(\PDO::FETCH_ASSOC)) {
	if ($result['can_view'] != 1 && !\FOP\Session::getPayload('upload_' . $id)) {
		throw new \FOP\AccessDeniedException();
	}
	
	$range = null;
	if (ob_get_level() <= 1) {
		header_remove('Pragma');
		header_remove('Cache-Control');
		header_remove('Expires');

		header('Content-Type: ' . $result['type']);
		header('Content-Disposition: ' . (isset($_GET['inline']) ? 'inline' : 'attachment; filename="' . $result['filename'] . '"'));
		header('Cache-Control: immutable,max-age=315360000');
		header('Expires: Sun, 19 Jul 2120 18:06:32 GMT');
		header('Accept-Ranges: bytes');

		// Range header lesen - nur bei Direktanfrage
		$range = getallheaders()['Range'] ?? null;
		if (preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches)) {
			// Range
			$range = $matches;
			if (!$range[1]) $range[1] = 0;
			if (!$range[2]) $range[2] = $result['size'] - 1;
		} else $range = null;
	}

	$data = '';

	// Datei inline rezitieren
	if (is_resource($result['data'])) {
		// postgres loads bytea values as stream
		$result['data'] = stream_get_contents($result['data']);
	}
	if (strlen($result['data']) == $result['size']) {
		if ($range) {
			http_response_code(206);
			header('Content-Length: ' . ($range[2] - $range[1] + 1));
			header('Content-Range: bytes '.$range[1].'-'.$range[2].'/'.$result['size']);
			echo substr($result['data'], $range[1], $range[2] - $range[1] + 1);
		} else {
			if (ob_get_level() <= 1) {
				header('Content-Length: ' . $result['size']);
			}
			echo ($result['data']);
		}
		return;
	}

	

	// Standardausgabe
	$filename = self::getPath($id);
	if (file_exists($filename)) {
		if ($range) {
			http_response_code(206);
			$bytestoread = $range[2] - $range[1] + 1;
			header('Content-Length: ' . $bytestoread);
			header('Content-Range: bytes '.$range[1].'-'.$range[2].'/'.$result['size']);
			$f = fopen($filename, 'r');
			fseek($f, $range[1]);
			$chunksize = 8192;
			while ($bytestoread > $chunksize) {
				// 1mb chunks for very large range queries
				echo fread($f, $chunksize);
				$bytestoread -= $chunksize;
			}
			// output the rest
			echo fread($f, $bytestoread);
			fclose($f);
		} else {
			if (ob_get_level() <= 1) header('Content-Length: ' . $result['size']);
			readfile($filename);
		}
		return;
	} else {
		http_response_code(404);
		return ('Error file not found: ' . $filename);
	}
} else {
	http_response_code(404);
	return ('Error file not found');
}


    
  }

  public static function getDefaultStorage() { 
    
    
    // --- BLOCK: main ---
    return \FOP\Configuration::getFOPFilesDefaultStorage();
    
  }

  public static function getPath($id) { 
    
    
    // --- BLOCK: main ---
    return 'fop-files/' . ($id % 13) . '/' . ($id % 101) . '/' . $id;
    
  }

  public static function validate($x) { 
    
    
    // --- BLOCK: main ---
    
	if ($x <= 0) return true;

	// Sondererlaubnis: wenn ich der Uploader bin (wird in der SESSION gespeichert)
	if (\FOP\Session::getPayload('upload_' . $x)) {
		return true;
	}

	// Prüfung auf Zugriffsrechte
	$q = 'SELECT 1 FROM fop_files WHERE EXISTS (
			SELECT '.qi('ID').' FROM '.qi('doc_revision').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_mail_host_box_draft_attachment').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_mail_host_box_dir_email_attachment').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('aufgabeAnhang').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ('.(\FOP\User::getIsGuest() ? 'false' : 'true').')
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_import_tbl').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND (' . (\FOP\User::getIsGuest() ? 'false' : 'true') . ')
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_import_tbl').' WHERE '.qi('summary').' = fop_files.'.qi('ID').' AND '.(((true)) ? 'true' : 'false').'
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('fop_fints_file').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND (('.\FOP\Database::quote(\FOP\User::getBuchhaltung()).'))
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('userconfig').' WHERE '.qi('Configuration_Stammdaten_logo').' = fop_files.'.qi('ID').' AND (('.\FOP\Database::quote(\FOP\User::getAdmin()).'))
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('campaign').' WHERE '.qi('post_template').' = fop_files.'.qi('ID').' AND (('.\FOP\Database::quote(\FOP\User::getCampaign()).'))
		UNION ALL 
			SELECT '.qi('ID').' FROM '.qi('campaignAttachment').' WHERE '.qi('file').' = fop_files.'.qi('ID').' AND ((COALESCE((SELECT ('.\FOP\Database::quote(\FOP\User::getCampaign()).') FROM '.qi('campaign').' '.qi('oP3oPgne').' WHERE '.qi('oP3oPgne').'.'.qi('ID').' = '.qi('campaignAttachment').'.'.qi('campaign').' LIMIT 1), FALSE)) AND ('.\FOP\Database::quote(\FOP\User::getCampaign()).'))) AND '.qi('ID').' = '.intval($x);
	if (\FOP\Database::query($q)->fetchColumn() != 1) throw new \FOP\AccessDeniedException('filedenied');

    
  }

  public static function getURL($id) { 
    
    
    // --- BLOCK: main ---
    
	$file = \FOP\Database::query('SELECT '.qi('ID').', filename, type, data FROM fop_files WHERE '.qi('ID').' = ' . \FOP\Database::quote($id))->fetch(\PDO::FETCH_ASSOC);
	$filename = self::getPath($file['ID']);
	if (is_resource($file['data'])) {
		// postgres loads bytea values as stream
		$file['data'] = stream_get_contents($file['data']);
	}
	if ($file['data']) {
		return 'data:' . $file['type'] . ';base64,' . base64_encode($file['data']);
	} else if (file_exists($filename)) {
		return 'data:' . $file['type'] . ';base64,' . base64_encode(file_get_contents($filename));
	}

    
  }

  public static function getContents($id) { 
    
    
    // --- BLOCK: main ---
    
	$file = \FOP\Database::query('SELECT '.qi('ID').', filename, type, data FROM fop_files WHERE '.qi('ID').' = ' . \FOP\Database::quote($id))->fetch(\PDO::FETCH_ASSOC);
	$filename = self::getPath($file['ID']);
	if (is_resource($file['data'])) {
		// postgres loads bytea values as stream
		$file['data'] = stream_get_contents($file['data']);
	}
	if (file_exists($filename)) {
		return file_get_contents($filename);
	} else if ($file['data']) {
		return $file['data'];
	}

    
  }

  public static function uploadAction($x) { 
    
    
    // --- BLOCK: access ---
    if(!((!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    global $_FILES;
	if (!isset($_FILES['file_'.$x]) || $_FILES['file_'.$x]['error'] || !$_FILES['file_'.$x]['tmp_name']) return $x > 0 ? $x : null;
	return self::handleUpload($x);

    
  }

  public static function sanitizeUpload($x) { 
    
    
    // --- BLOCK: main ---
    
	if (isset($_FILES['file_'.$x])) {
		// Image-Upload oder 'Legacy' mit direktem Upload des Files
		return \FOP\Files::handleUpload($x);
	} else if ($x <= 0) {
		return null; // leer gelassene Upload-Datei
	} else {
		$files = \FOP\Database::query('SELECT '.qi('ID').' FROM fop_files WHERE '.qi('ID').' = ' . intval($x))->fetchAll();
		if (count($files) != 1) throw new \Exception('Expected to find 1 uploaded file, not ' . count($files));
		return $x;
	}

    
  }

  public static function handleUpload($x) { 
    
    
    // --- BLOCK: main ---
    global $_FILES;
	 // zuerst: Hash auswerten
    $filename = $_FILES['file_'.$x]['name'];
	 $hash = hash_file('sha256', $_FILES['file_'.$x]['tmp_name'], false);
	 $id = \FOP\Database::query('SELECT '.qi('ID').' FROM fop_files WHERE filename = ' . \FOP\Database::quote($filename) . ' AND hash = ' . \FOP\Database::quote($hash))->fetchColumn();
	 if ($id) {
		 // found already existing file with same content and same filename => return that file ID
		 \FOP\Session::setPayload('upload_' . $id, $id); // in der Session vormerken, dass ich sie selbst hochgeladen habe

		 return $id;
	 }

    // alten Wert übergeben, wenn Error
    if (!isset($_FILES['file_'.$x]) || $_FILES['file_'.$x]['error'] || !$_FILES['file_'.$x]['tmp_name']) return $x > 0 ? $x : null;
    $stmt = \FOP\Database::prepare('INSERT INTO '.qi('fop_files').' (filename, type, size, data, hash, width, height, uploaded_at, '.qi('lastUsed').') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $type = $_FILES['file_'.$x]['type'];
    $size = $_FILES['file_'.$x]['size'];
    $null = NULL;
	 $time = time();
    $stmt->bindParam(1, $filename);
	$stmt->bindParam(2, $type);
	$stmt->bindParam(3, $size);
	$stmt->bindParam(5, $hash);
	$stmt->bindParam(8, $time);
	$stmt->bindParam(9, $time);
	 	 
	 if (self::getDefaultStorage() == 'files' && is_writable('fop-files') && $size > 1024) {
		// Kann im Dateisystem abgelegt werden
		
			$stmt->bindParam(6, $null); $stmt->bindParam(7, $null);
		
	 	$stmt->bindParam(4, $null);
		$stmt->execute();
		$id = \FOP\Database::getLastInsertId();

	 	

		if (!file_exists("fop-files/" . ($id % 13) . "/" . ($id % 101) . "/")) {
			mkdir("fop-files/" . ($id % 13) . "/" . ($id % 101) . "/", 0777, true);
		}

		if (isset($_FILES['file_'.$x]['copy'])) {
			copy($_FILES['file_'.$x]['tmp_name'], self::getPath($id));
		} else {
			move_uploaded_file($_FILES['file_'.$x]['tmp_name'], self::getPath($id));
		}
	 } else {
		 $file = file_get_contents($_FILES['file_'.$x]['tmp_name']);
		
			$stmt->bindParam(6, $null); $stmt->bindParam(7, $null);
		
		
		// direct upload into database
	 	$stmt->bindParam(4, $file, \PDO::PARAM_LOB);
		$stmt->execute();
		$id = \FOP\Database::getLastInsertId();

	 	
	 }
    $stmt->closeCursor();

	 \FOP\Session::setPayload('upload_' . $id, $id); // in der Session vormerken, dass ich sie selbst hochgeladen habe

    return $id;

    
  }

  public static function previewAction($id) { 
    
    
    // --- BLOCK: access ---
    if(!((!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    
$result = \FOP\Database::query('SELECT filename, type, size, data FROM fop_files WHERE '.qi('ID').' = '.intval($id));
if ($result = $result->fetch(\PDO::FETCH_ASSOC)) {
	
	if ($result['type'] == 'application/pdf') {
		$tmpfile = tempnam(sys_get_temp_dir(), 'img');
		header('Content-Type: image/jpeg');
	} else if (substr($result['type'], 0, 6) == 'image/') {
		header('Content-Type: ' . $result['type']);
		header('Content-Length: ' . $result['size']);
		header('Content-Disposition: inline; filename="' . $result['filename'] . '"');
	} else {
		header('Content-Type: image/svg+xml');
	}
	header('Cache-Control: max-age=315360000');
	header('Expires: Sun, 19 Jul 2120 18:06:32 GMT');

	if ($result['type'] == 'application/pdf') {
		exec("gs -dNOPAUSE -sDEVICE=jpeg -r30 -sOutputFile=$tmpfile " . escapeshellarg(self::getTempFile($id)));
		readfile($tmpfile);
		unlink($tmpfile);
		die();
	} else if (substr($result['type'], 0, 6) == 'image/') {
		\FOP\Files::downloadAction($id, 140);
		die();
	}

	// else: not previewable file type: render a document icon
	?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <defs id="defs3051">
    <style type="text/css" id="current-color-scheme">
      .ColorScheme-Text {
        color:#232629;
      }
      </style>
  </defs>
  <g transform="translate(1,1)">
  <path style="fill:currentColor;fill-opacity:1;stroke:none" 
     d="M 4,3 V 19 H 5 17 V 18 H 5 V 4 h 8 v 3 1 h 4 v 11 h 1 V 8.4 7 7 L 14,3 14,3 V 3 H 13 5 Z "
     class="ColorScheme-Text"
     /></g>
</svg><?php
} else {
	http_response_code(404);
	die('Error file not found');
}


    
  }

  public static function attachFileToMail($files, $mail) { 
    
    
    // --- BLOCK: main ---
    
	$idlist = new \FOP\IDList();
	if (is_array($files)) {
		foreach ($files AS $file) $idlist->push($file);
	} else {
		$idlist->push($files);
	}
	$files = \FOP\Database::query('SELECT '.qi('ID').', filename, type, data FROM fop_files WHERE ' . $idlist->toSQL(qi('ID')))->fetchAll(\PDO::FETCH_ASSOC);
	foreach ($files AS $file) {
		$id = $file['ID'];
		$filename = self::getPath($id);
		if (is_resource($file['data'])) {
			// postgres loads bytea values as stream
			$file['data'] = stream_get_contents($file['data']);
		}
		if (file_exists($filename)) {
			$mail->addAttachment($filename, $file['filename'], 'base64', $file['type']);
		} else if ($file['data']) {
			$mail->addStringAttachment($file['data'], $file['filename'], 'base64', $file['type']);
		}
	}

    
  }

  public static function getTempFile($file, $desiredExtension = null ) { 
    
    
    // --- BLOCK: main ---
    
	$file = \FOP\Database::query('SELECT '.qi('ID').', filename, type, data FROM fop_files WHERE '.qi('ID').' = ' . \FOP\Database::quote($file))->fetch(\PDO::FETCH_ASSOC);
	$filename = self::getPath($file['ID']);
	if (is_resource($file['data'])) {
		// postgres loads bytea values as stream
		$file['data'] = stream_get_contents($file['data']);
	}
	if (file_exists($filename)) {
		if ($desiredExtension) {
			$result = tempnam(sys_get_temp_dir(), 'file') . '.' . $desiredExtension;
			copy($filename, $result);
			register_shutdown_function(function () use ($result) {
				@unlink($result);
			});
			return $result;
		}
		return $filename;
	} else if ($file['data']) {
		$filename = tempnam(sys_get_temp_dir(), 'file');
		register_shutdown_function(function () use ($filename) {
			@unlink($filename);
		});
		if ($desiredExtension) {
			$filename .= '.' . $desiredExtension;
			register_shutdown_function(function () use ($filename) {
				@unlink($filename);
			});
		}
		file_put_contents($filename, $file['data']);
		return $filename;
	}
	return null;

    
  }

  public static function uploadFromString($content, $filename) { 
    
    
    // --- BLOCK: main ---
    
	$tmp = tempnam(sys_get_temp_dir(), 'fopfile');
	file_put_contents($tmp, $content);
	return self::uploadFromFile($tmp, $filename);

    
  }

  public static function uploadFromFile($filename, $friendlyname = null ) { 
    
    
    // --- BLOCK: main ---
    global $_FILES;
	if (!file_exists($filename)) throw new \FOP\AccessDeniedException('file does not exist: ' . $filename);
	// rufe einfach handleUpload auf
	$_FILES['file_dummy'] = [
		'name' => $friendlyname ?: basename($filename),
		'type' => mime_content_type($filename),
		'size' => filesize($filename),
		'tmp_name' => $filename,
		'error' => null,
		'copy' => true
	];
	return self::handleUpload('dummy');

    
  }

  public static function getPDFURL($id, $bgcolor = null ) { 
    
    
    // --- BLOCK: main ---
    
	$file = \FOP\Database::query('SELECT '.qi('ID').', filename, type, data FROM fop_files WHERE '.qi('ID').' = ' . \FOP\Database::quote($id))->fetch(\PDO::FETCH_ASSOC);
	$filename = self::getPath($file['ID']);
	if (is_resource($file['data'])) {
		// postgres loads bytea values as stream
		$file['data'] = stream_get_contents($file['data']);
	}
	
	if (file_exists($filename)) {
		return $filename;
	} else if ($file['data']) {
		return 'data:' . $file['type'] . ';base64,' . base64_encode($file['data']);
	}

    
  }

  public static function attachToPDF($file, $mpdf) { 
    
    
    // --- BLOCK: main ---
    
	$tmp = \FOP\Files::getTempFile($file);
	// Footer retten und leere Seite starten
	$mpdf->AddPage();
	$footer = $mpdf->HTMLFooter['html'];
	$mpdf->SetHTMLFooter(''); // Footer leer setzen, da wir das PDF einfügen; TODO: später wieder auf Alt-Wert zurücksetzen
	if ($tmp) {
		$pagecount = $mpdf->SetSourceFile($tmp);
		for ($i = 1; $i <= $pagecount; $i++) {
			$tplId = $mpdf->importPage($i);
			$mpdf->UseTemplate($tplId);
			if ($i != $pagecount) $mpdf->AddPage();
		}
	}
	$mpdf->SetHTMLFooter($footer);

    
  }

  public static function attachFileToZip($files, $zip, $filenameprefix = '' , $appendOriginalFilename = true ) { 
    
    
    // --- BLOCK: main ---
    
	$idlist = new \FOP\IDList();
	if (is_array($files)) {
		foreach ($files AS $file) $idlist->push($file);
	} else {
		$idlist->push($files);
	}
	$files = \FOP\Database::query('SELECT '.qi('ID').', filename, type, data FROM fop_files WHERE ' . $idlist->toSQL(qi('ID')))->fetchAll(\PDO::FETCH_ASSOC);
	foreach ($files AS $file) {
		$id = $file['ID'];
		$filename = self::getPath($id);
		if (is_resource($file['data'])) {
			// postgres loads bytea values as stream
			$file['data'] = stream_get_contents($file['data']);
		}
		if (file_exists($filename)) {
			$zip->addFile($filename, $filenameprefix . ($appendOriginalFilename ? $file['filename'] : ''));
		} else if ($file['data']) {
			$zip->addFromString($filenameprefix . ($appendOriginalFilename ? $file['filename'] : ''), $file['data']);
		}
	}

    
  }

  public static function removeOld() { 
    
    
    // --- BLOCK: 1-prepare ---
    error_log('prepare gc'); /* no prepare necessary with lastUsed */
    // --- BLOCK: 2-normal ---
    
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('fop_fints_file').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('fop_fints_file').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('fop_fints_file').' WHERE '.qi('fop_fints_file').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('doc_revision').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('doc_revision').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('doc_revision').' WHERE '.qi('doc_revision').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('fop_mail_host_box_draft_attachment').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('fop_mail_host_box_draft_attachment').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('fop_mail_host_box_draft_attachment').' WHERE '.qi('fop_mail_host_box_draft_attachment').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('fop_mail_host_box_dir_email_attachment').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('fop_mail_host_box_dir_email_attachment').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('fop_mail_host_box_dir_email_attachment').' WHERE '.qi('fop_mail_host_box_dir_email_attachment').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('aufgabeAnhang').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('aufgabeAnhang').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('aufgabeAnhang').' WHERE '.qi('aufgabeAnhang').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('userconfig').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('userconfig').'.'.qi('Configuration_Stammdaten_logo').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('userconfig').' WHERE '.qi('userconfig').'.'.qi('Configuration_Stammdaten_logo').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('campaignAttachment').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('campaignAttachment').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('campaignAttachment').' WHERE '.qi('campaignAttachment').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('campaign').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('campaign').'.'.qi('post_template').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('campaign').' WHERE '.qi('campaign').'.'.qi('post_template').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('fop_import_tbl').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('fop_import_tbl').'.'.qi('file').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('fop_import_tbl').' WHERE '.qi('fop_import_tbl').'.'.qi('file').' = fop_files.'.qi('ID'));
			}
		
			if (\FOP\Database::getDriver() == 'mysql') {
				\FOP\Database::query('UPDATE fop_files, '.qi('fop_import_tbl').' SET fop_files.'.qi('lastUsed').' = '.time().' WHERE '.qi('fop_import_tbl').'.'.qi('summary').' = fop_files.'.qi('ID'));
			} else {
				\FOP\Database::query('UPDATE fop_files SET '.qi('lastUsed').' = '.time().' FROM '.qi('fop_import_tbl').' WHERE '.qi('fop_import_tbl').'.'.qi('summary').' = fop_files.'.qi('ID'));
			}
		
	
    // --- BLOCK: 3-collect-remove ---
    error_log("perform gc"); 
		// 1 days
		$toDelete = \FOP\Database::query('SELECT '.qi('ID').' FROM fop_files WHERE '.qi('lastUsed').' IS NULL OR '.qi('lastUsed').' < '.time().' - 7 * 24 * 60 * 60');
		while ($id = $toDelete->fetch(\PDO::FETCH_COLUMN)) {
			if (file_exists('fop-files/' . ($id % 13) . '/' . ($id % 101) . '/' . $id)) {
				unlink('fop-files/' . ($id % 13) . '/' . ($id % 101) . '/' . $id);
			}
		}
		\FOP\Database::query('DELETE FROM fop_files WHERE '.qi('lastUsed').' IS NULL OR '.qi('lastUsed').' < '.time().' - 7 * 24 * 60 * 60');
	
    
  }


  
  

  
  
}



