Core  3.2
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
cleanContext.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @package FDL
5 */
6 /**
7  * Generated Header (not documented yet)
8  *
9  * @subpackage
10  */
11 /**
12  */
13 // remove all tempory doc and orphelines values
14 include_once ("FDL/Class.Doc.php");
15 include_once ("WHAT/Class.SessionUtils.php");
16 global $action;
17 
18 $usage = new ApiUsage();
19 
20 $usage->setDefinitionText("Clean base");
21 $real = ($usage->addHiddenParameter("real", "real (yes or no)") == "yes");
22 $full = ($usage->addEmptyParameter("full", "clean also obsolete permission, log, folder contains"));
23 
24 if ($full !== true) {
25  $full = ($full == "yes");
26 }
27 
28 $usage->verify();
29 
30 $dbaccess = $action->dbaccess;
31 if ($dbaccess == "") {
32  print "Database not found : action->dbaccess";
33  exit;
34 }
35 
36 $duration = intval($action->GetParam("CORE_LOGDURATION", 60)); // default 60 days
37 $logdelete = sprintf("DELETE FROM doclog where date < '%s'", Doc::getDate(-($duration)));
38 
40 
41 global $_SERVER;
42 
43 cleanTmpDoc();
44 
45 if ($real || $full) {
46  print "Full clean.\n";
48 } else {
49  print "Basic clean.\n";
51 }
52 // Cleanup session files
53 $core_db = $action->dbaccess;
55 $sessionUtils->deleteExpiredSessionFiles();
56 // Clean token open access
58 
60 \Dcp\VaultManager::destroyTmpFiles($action->GetParam('CORE_TMPDIR_MAXAGE', '2'));
61 
62 function mkTmpScript($script, $prefix)
63 {
64  $tmpDir = getTmpDir();
65  $tmpScript = tempnam($tmpDir, $prefix);
66  if ($tmpScript === false) {
67  throw new Exception(sprintf("Error creating temporary file in '%s'.", $tmpDir));
68  }
69  if (file_put_contents($tmpScript, $script) === false) {
70  throw new Exception(sprintf("Error writing to temporary file '%s'.", $tmpScript));
71  }
72  return $tmpScript;
73 }
74 
76 {
77  $sqlDir = implode(DIRECTORY_SEPARATOR, array(
79  'CORE',
80  'cleanContext'
81  ));
82  if (($fh = opendir($sqlDir)) === false) {
83  throw new Exception(sprintf("Error opening directory '%s'", $sqlDir));
84  }
85  $files = array();
86  while (($file = readdir($fh)) !== false) {
87  if ($file === '.' || $file === '..') {
88  continue;
89  }
90  if (preg_match(sprintf('/^%s_.*\.sql$/', preg_quote($prefix)) , $file) !== 1) {
91  continue;
92  }
93  $files[] = implode(DIRECTORY_SEPARATOR, array(
94  $sqlDir,
95  $file
96  ));
97  }
98  uasort($files, function ($a, $b)
99  {
100  return strcmp($a, $b);
101  });
102  return $files;
103 }
104 
105 function execSqlFile(Action & $action, $sqlFile)
106 {
107  $pgService = getServiceName($action->dbaccess);
108  $script = <<<'EOF'
109 #!/bin/bash
110 PGSERVICE=%s psql --set ON_ERROR_STOP=1 -c '\timing' -a -f %s 2>&1 | logger -s -t %s
111 exit ${PIPESTATUS[0]}
112 EOF;
113  $script = sprintf($script, escapeshellarg($pgService) , escapeshellarg($sqlFile) , escapeshellarg("cleanContext(" . $action->GetParam("CORE_CLIENT") . ")"));
114  $tmpScript = mkTmpScript($script, 'basicDbClean');
115  $out = array();
116  $ret = 0;
117  exec(sprintf("bash %s 2>&1", escapeshellarg($tmpScript)) , $out, $ret);
118  if ($ret !== 0) {
119  unlink($tmpScript);
120  throw new Exception(sprintf("Error executing SQL file '%s': %s", $sqlFile, join("\n", $out)));
121  }
122  unlink($tmpScript);
123 }
124 
126 {
127  $sqlFiles = getSqlFiles($prefix);
128  $errors = [];
129  foreach ($sqlFiles as $sqlFile) {
130  try {
131  printf("Executing '%s': ", $sqlFile);
132  execSqlFile($action, $sqlFile);
133  printf("[OK]\n");
134  }
135  catch(\Exception $e) {
136  printf("[ERROR]\n%s\n", $e->getMessage());
137  $errors[] = $e->getMessage();
138  }
139  }
140  if (count($errors) > 0) {
141  throw new Exception(sprintf("Errors:\n%s\n", join("\n", $errors)));
142  }
143 }
144 
146 {
147  execSqlFiles($action, 'cleanFullContext');
148 }
149 
151 {
152  execSqlFiles($action, 'cleanContext');
153 }
154 
155 function cleanTmpFiles()
156 {
157  global $action;
158  global $pubdir;
159 
160  if ($pubdir == '') {
161  echo sprintf("Error: Yikes! we got an empty pubdir?");
162  return;
163  }
164 
165  $maxAge = $action->GetParam('CORE_TMPDIR_MAXAGE', '');
166  if ($maxAge == '') {
167  echo sprintf("Error: empty CORE_TMPDIR_MAXAGE parameter.");
168  return;
169  }
170 
171  if (!is_numeric($maxAge)) {
172  echo sprintf("Error: found non-numeric value '%s' for CORE_TMPDIR_MAXAGE.", $maxAge);
173  return;
174  }
175 
176  $tmpDir = getTmpDir('');
177  if ($tmpDir == '') {
178  echo sprintf("Error: empty directory returned by getTmpDir().");
179  return;
180  }
181  //clean tmp files
182  $r = cleanOldFiles($tmpDir, $maxAge);
183  if ($r) {
184  echo $r;
185  }
186  //clean mustache cache files
187  $r = cleanOldFiles($pubdir . '/var/cache/mustache', $maxAge);
188  if ($r) {
189  echo $r;
190  }
191 
192  return;
193 }
194 /*
195  * Delete files oldre than N days in given directory
196 */
197 function cleanOldFiles($dir, $maxAge)
198 {
199  if (!is_dir($dir)) {
200  return "";
201  }
202  /* Values < 0 disable tmp file cleaning */
203  if ($maxAge < 0) {
204  return "";
205  }
206  /* We use find & xargs shell commands to do the cleaning. */
207  /* First pass: remove expired files */
208  $cmd = sprintf('find %s -type f -mtime +%s -print0 | xargs -0 --no-run-if-empty rm', escapeshellarg($dir) , $maxAge);
209  exec($cmd, $output, $ret);
210  if ($ret != 0) {
211  return sprintf("Error: removal of old files from '%s' returned with error: %s", $dir, join("\n", $output));
212  }
213  /* Second pass: remove expired empty directories */
214  $cmd = sprintf('find %s -type d -empty -mtime +%s -print0 | xargs -0 --no-run-if-empty rmdir', escapeshellarg($dir) , $maxAge);
215  exec($cmd, $output, $ret);
216  if ($ret != 0) {
217  return sprintf("Error: removal of empty temporary directories from '%s' returned with error: %s", $dir, join("\n", $output));
218  }
219 
220  return "";
221 }
222 /**
223  * Delete temporary documents that have reached their end-of-life (CORE_TMPDOC_MAXAGE).
224  */
225 function cleanTmpDoc()
226 {
227  $days = \ApplicationParameterManager::getParameterValue('CORE', 'CORE_TMPDOC_MAXAGE');
228  if (!is_int($days) && !ctype_digit($days)) {
229  $days = 1;
230  }
231 
232  $sql = <<<'EOF'
233 BEGIN;
234 
235 -- Delete expired temporary documents
236 DELETE FROM doc WHERE doctype = 'T' AND cdate < (now() - INTERVAL '%d day');
237 
238 -- Delete lingering dochisto entries of temporary documents
239 DELETE FROM dochisto WHERE id >= 1000000000 AND NOT EXISTS (SELECT 1 FROM doc WHERE doc.id = dochisto.id);
240 
241 -- Reset temporary id sequence to MAX(id) of temporary documents
242 SELECT SETVAL('seq_id_tdoc', (SELECT COALESCE(MAX(id), 1000000000) FROM doc WHERE doctype = 'T'));
243 
244 COMMIT;
245 EOF;
246  try {
247  $sql = sprintf($sql, $days);
248  simpleQuery('', $sql, $res, true, true, true);
249  }
250  catch(\Exception $e) {
251  printf("Error: removal of expired temporary documents returned with error: %s\n", $e->getMessage());
252  }
253 }
cleanTmpDoc()
cleanTmpFiles()
static deleteExpired()
static getDate($daydelta=0, $dayhour="", $daymin="", $getlocale=false)
Definition: Class.Doc.php:8783
global $pubdir
Definition: vault_init.php:18
print< H1 > Check Database< i > $dbaccess</i ></H1 > $a
Definition: checklist.php:45
if($dbaccess=="") $duration
$full
$ret
static destroyTmpFiles($dayInterval=2)
static getParameterValue($application, $parameterName)
$file
print t
Definition: cleanFamily.php:92
getSqlFiles($prefix)
$logdelete
$real
execSqlFile(Action &$action, $sqlFile)
const DEFAULT_PUBDIR
Definition: Lib.Prefix.php:28
foreach($argv as $arg) $cmd
$core_db
$usage
print
Definition: checklist.php:49
getTmpDir($def= '/tmp')
Definition: Lib.Common.php:150
global $_SERVER
getServiceName($dbaccess)
Definition: Lib.Common.php:466
switch($command) exit
Definition: checkVault.php:46
$sessionUtils
$dir
Definition: resizeimg.php:144
basicDbClean(Action &$action)
global $action
fullDbClean(Action &$action)
simpleQuery($dbaccess, $query, &$result=array(), $singlecolumn=false, $singleresult=false, $useStrict=null)
Definition: Lib.Common.php:484
$dbaccess
mkTmpScript($script, $prefix)
cleanOldFiles($dir, $maxAge)
Verify arguments for wsh programs.
execSqlFiles(Action &$action, $prefix)
← centre documentaire © anakeen