dolibarr 25.0.0-alpha
repair.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 * or see https://www.gnu.org/
17 */
18
31function checkElementExist($id, $table)
32{
33 global $db;
34
35 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
36 $sql .= " WHERE rowid = ".((int) $id);
37 $resql = $db->query($sql);
38 if ($resql) {
39 $num = $db->num_rows($resql);
40 if ($num > 0) {
41 return true;
42 } else {
43 return false;
44 }
45 } else {
46 return true; // for security
47 }
48}
49
57function checkLinkedElements($sourcetype, $targettype)
58{
59 global $db, $langs;
60
61 $elements = array();
62 $deleted = 0;
63
64 $sourcetable = $sourcetype;
65 $targettable = $targettype;
66
67 if ($sourcetype == 'shipping') {
68 $sourcetable = 'expedition';
69 } elseif ($targettype == 'shipping') {
70 $targettable = 'expedition';
71 }
72 if ($sourcetype == 'delivery') {
73 $sourcetable = 'livraison';
74 } elseif ($targettype == 'delivery') {
75 $targettable = 'livraison';
76 }
77 if ($sourcetype == 'order_supplier') {
78 $sourcetable = 'commande_fournisseur';
79 } elseif ($targettype == 'order_supplier') {
80 $targettable = 'commande_fournisseur';
81 }
82 if ($sourcetype == 'invoice_supplier') {
83 $sourcetable = 'facture_fourn';
84 } elseif ($targettype == 'invoice_supplier') {
85 $targettable = 'facture_fourn';
86 }
87
88 $out = $langs->trans('SourceType').': '.$sourcetype.' => '.$langs->trans('TargetType').': '.$targettype.' ';
89
90 $sql = "SELECT rowid, fk_source, fk_target FROM ".MAIN_DB_PREFIX."element_element";
91 $sql .= " WHERE sourcetype = '".$db->escape($sourcetype)."' AND targettype = '".$db->escape($targettype)."'";
92 $resql = $db->query($sql);
93 if ($resql) {
94 $num = $db->num_rows($resql);
95 if ($num) {
96 $i = 0;
97 while ($i < $num) {
98 $obj = $db->fetch_object($resql);
99 $elements[$obj->rowid] = array($sourcetype => $obj->fk_source, $targettype => $obj->fk_target);
100 $i++;
101 }
102 }
103 }
104
105 if (!empty($elements)) {
106 foreach ($elements as $key => $element) {
107 if (!checkElementExist($element[$sourcetype], $sourcetable) || !checkElementExist($element[$targettype], $targettable)) {
108 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'element_element';
109 $sql .= " WHERE rowid = ".((int) $key);
110 $resql = $db->query($sql);
111 $deleted++;
112 }
113 }
114 }
115
116 if ($deleted) {
117 $out .= '('.$langs->trans('LinkedElementsInvalidDeleted', $deleted).')<br>';
118 } else {
119 $out .= '('.$langs->trans('NothingToDelete').')<br>';
120 }
121
122 return $out;
123}
124
131{
132 global $db, $langs;
133
134 // Clean data from ecm_directories
135 $sql = "SELECT rowid, label FROM ".MAIN_DB_PREFIX."ecm_directories";
136 $resql = $db->query($sql);
137 if ($resql) {
138 while ($obj = $db->fetch_object($resql)) {
139 $id = $obj->rowid;
140 $label = $obj->label;
141 $newlabel = dol_sanitizeFileName($label);
142 if ($label != $newlabel) {
143 $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."ecm_directories set label = '".$db->escape($newlabel)."' WHERE rowid = ".((int) $id);
144 print '<tr><td>'.$sqlupdate."</td></tr>\n";
145 $resqlupdate = $db->query($sqlupdate);
146 if (!$resqlupdate) {
147 dol_print_error($db, 'Failed to update');
148 return -1;
149 }
150 }
151 }
152 } else {
153 dol_print_error($db, 'Failed to run request');
154 return -1;
155 }
156
157 return 1;
158}
159
171function repairEcmFiles($db, $entity, $documentroot, $confirmed = false, $maxdelete = 100)
172{
173 $report = array('processed' => 0, 'missing' => 0, 'deleted' => 0, 'skipped' => 0, 'limitreached' => false, 'entries' => array(), 'error' => '');
174 if ($entity <= 0 || $maxdelete <= 0) {
175 $report['error'] = 'ErrorWrongParameters';
176 return $report;
177 }
178 $realroot = realpath(dol_osencode($documentroot));
179 if ($realroot === false || !dol_is_dir($documentroot) || !is_readable(dol_osencode($documentroot))) {
180 $report['error'] = 'RepairEcmDirectoryUnavailable';
181 return $report;
182 }
183 $rootprefix = rtrim(str_replace('\\', '/', $realroot), '/').'/';
184 $sql = "SELECT rowid, filename, filepath FROM ".$db->prefix()."ecm_files";
185 $sql .= " WHERE entity = ".((int) $entity)." ORDER BY rowid ASC";
186 $resql = $db->query($sql);
187 if (!$resql) {
188 $report['error'] = 'RepairEcmDatabaseError';
189 return $report;
190 }
191 $candidates = array();
192 while (is_object($obj = $db->fetch_object($resql))) {
193 $report['processed']++;
194 $relativepath = str_replace('\\', '/', (string) $obj->filepath);
195 $filename = (string) $obj->filename;
196 // Never interpret an unsafe or inaccessible indexed path as a missing file.
197 if ($relativepath === '' || preg_match('~^/|(^|/)\.\.?(/|$)|[\x00-\x1f:]~', $relativepath)
198 || $filename === '' || $filename === '.' || $filename === '..' || preg_match('~[\\\\/\x00-\x1f:]~', $filename)) {
199 $report['skipped']++;
200 continue;
201 }
202 $directory = $documentroot.'/'.$relativepath;
203 $realdirectory = realpath(dol_osencode($directory));
204 if ($realdirectory === false || !is_readable(dol_osencode($directory))
205 || strpos(rtrim(str_replace('\\', '/', $realdirectory), '/').'/', $rootprefix) !== 0) {
206 $report['skipped']++;
207 continue;
208 }
209 $filetocheck = $directory.'/'.$filename;
210 if (dol_is_file($filetocheck) || dol_is_file($filetocheck.'.noexe')) {
211 continue;
212 }
213 if (dol_is_dir($filetocheck) || dol_is_link($filetocheck) || dol_is_link($filetocheck.'.noexe')) {
214 $report['skipped']++;
215 continue;
216 }
217 $report['missing']++;
218 if (count($candidates) >= $maxdelete) {
219 $report['limitreached'] = true;
220 break;
221 }
222 $candidates[] = $obj;
223 $report['entries'][] = array('id' => (int) $obj->rowid, 'path' => $relativepath.'/'.$filename);
224 }
225 $db->free($resql);
226 if (!$confirmed || !$candidates) {
227 return $report;
228 }
229 if (!$db->begin()) {
230 $report['error'] = 'RepairEcmDatabaseError';
231 return $report;
232 }
233 foreach ($candidates as $candidate) {
234 // Keep an entry if another process has restored its file or changed its indexed path.
235 $filetocheck = $documentroot.'/'.$candidate->filepath.'/'.$candidate->filename;
236 $directory = dirname($filetocheck);
237 $realdirectory = realpath(dol_osencode($directory));
238 if ($realdirectory === false || !is_readable(dol_osencode($directory))
239 || strpos(rtrim(str_replace('\\', '/', $realdirectory), '/').'/', $rootprefix) !== 0
240 || dol_is_link($filetocheck) || dol_is_link($filetocheck.'.noexe') || dol_is_dir($filetocheck)) {
241 $report['skipped']++;
242 continue;
243 }
244 if (dol_is_file($filetocheck) || dol_is_file($filetocheck.'.noexe')) {
245 continue;
246 }
247 $sql = "DELETE FROM ".$db->prefix()."ecm_files WHERE rowid = ".((int) $candidate->rowid);
248 $sql .= " AND entity = ".((int) $entity);
249 $sql .= " AND filepath = '".$db->escape($candidate->filepath)."' AND filename = '".$db->escape($candidate->filename)."'";
250 $result = $db->query($sql);
251 if (!$result) {
252 $db->rollback();
253 $report['deleted'] = 0;
254 $report['error'] = 'RepairEcmDatabaseError';
255 return $report;
256 }
257 $report['deleted'] += $db->affected_rows($result);
258 }
259 if (!$db->commit()) {
260 $db->rollback();
261 $report['deleted'] = 0;
262 $report['error'] = 'RepairEcmDatabaseError';
263 }
264 return $report;
265}
266
275function repairImagePathIsSafe($path, $directory, $documentroot)
276{
277 $path = rtrim(str_replace('\\', '/', $path), '/');
278 $directory = rtrim(str_replace('\\', '/', $directory), '/');
279 $documentroot = rtrim(str_replace('\\', '/', $documentroot), '/');
280 $windows = stripos(PHP_OS, 'WIN') === 0;
281 $documentrootlength = dol_strlen($documentroot, 'UTF-8', 1);
282 $directorylength = dol_strlen($directory, 'UTF-8', 1);
283 if ($path === '' || $directory === '' || $documentroot === '' || preg_match('~(?:^|/)\.\.?(?:/|$)~', $path)) {
284 return false;
285 }
286 if (($windows ? strncasecmp($directory.'/', $documentroot.'/', $documentrootlength + 1) : strncmp($directory.'/', $documentroot.'/', $documentrootlength + 1)) !== 0
287 || ($windows ? strncasecmp($path.'/', $directory.'/', $directorylength + 1) : strncmp($path.'/', $directory.'/', $directorylength + 1)) !== 0) {
288 return false;
289 }
290 $realroot = realpath(dol_osencode($documentroot));
291 $realdirectory = realpath(dol_osencode($directory));
292 if ($realroot === false || $realdirectory === false || !dol_is_dir($directory)) {
293 return false;
294 }
295 $realroot = rtrim(str_replace('\\', '/', $realroot), '/');
296 $expected = $realroot.dol_substr($directory, $documentrootlength, null, 'UTF-8', 1);
297 $realdirectory = str_replace('\\', '/', $realdirectory);
298 if (($windows ? strcasecmp($realdirectory, $expected) : strcmp($realdirectory, $expected)) !== 0) {
299 return false;
300 }
301 $parent = $path;
302 // lstat also detects broken links and Windows junctions that is_link() may miss.
303 while (@lstat(dol_osencode($parent)) === false) {
304 $nextparent = dirname($parent);
305 if ($nextparent === $parent) {
306 return false;
307 }
308 $parent = $nextparent;
309 }
310 $realparent = realpath(dol_osencode($parent));
311 if ($realparent === false) {
312 return false;
313 }
314 $expected = $realroot.dol_substr($parent, $documentrootlength, null, 'UTF-8', 1);
315 $realparent = str_replace('\\', '/', $realparent);
316 return ($windows ? strcasecmp($realparent, $expected) : strcmp($realparent, $expected)) === 0;
317}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
dol_is_link($pathoffile)
Return if path is a symbolic link.
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
clean_data_ecm_directories()
Clean data into ecm_directories table.
checkLinkedElements($sourcetype, $targettype)
Check linked elements and delete if invalid.
repairEcmFiles($db, $entity, $documentroot, $confirmed=false, $maxdelete=100)
Check an entity's ECM index against the filesystem, optionally removing missing-file entries.
checkElementExist($id, $table)
Check if an element exist.
repairImagePathIsSafe($path, $directory, $documentroot)
Check an image repair path, including a missing destination, against its owner's directory.