/var/www/html_it/wp-content/plugins/loco-translate/src/fs/Revisions.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
<?php
/**
 * Manages revisions (backups) of a file.
 * Revision file names have form "<filename>-backup-<date>.<ext>~"
 */
class Loco_fs_Revisions implements Countable/*, IteratorAggregate*/ {
    
    
/**
     * @var Loco_fs_File
     */
    
private $master;
    
    
/**
     * Sortable list of backed up file paths (not including master)
     * @var array
     */
    
private $paths;
    
    
/**
     * Cached regular expression for matching backup file paths
     * @var string
     */
    
private $regex;

    
/**
     * Cached count of backups + 1
     * @var int
     */
    
private $length;

    
/**
     * Paths to delete when object removed from memory
     * @var array
     */
    
private $trash = [];
    

    
/**
     * Construct from master file (current version)
     * @param Loco_fs_File $file
     */
    
public function __constructLoco_fs_File $file ){
        
$this->master $file;
    }


    
/**
     * @internal
     * Executes deferred deletions with silent errors
     */
    
public function __destruct(){
        if( 
$trash $this->trash ){
            
$writer = clone $this->master->getWriteContext();
            foreach( 
$trash as $file ){
                if( 
$file->exists() ){
                    try {
                        
$writer->setFile($file);
                        
$writer->delete(false);
                    }
                    catch( 
Loco_error_WriteException $e ){
                        
// avoiding fatal error because pruning is non-critical operation
                        
Loco_error_AdminNotices::debug$e->getMessage() );
                    }
                }
            }
        }
    }



    
/**
     * Check that file permissions allow a new backup to be created
     * @return bool
     */
    
public function writable(){
        return 
$this->master->exists() && $this->master->getParent()->writable();
    }



    
/**
     * Create a new backup of current version
     * @return Loco_fs_File
     */
    
public function create(){
        
$vers 0;
        
$date date('YmdHis');
        
$ext $this->master->extension();
        
$base $this->master->dirname().'/'.$this->master->filename();
        do {
            
$path sprintf'%s-backup-%s%u.%s~'$base$date$vers++, $ext);
        }
        while ( 
            
file_exists($path)
        );

        
$copy $this->master->copy$path );
        
        
// invalidate cache so next access reads disk
        
$this->paths null;
        
$this->length null;
        
        return 
$copy;
    }


    
/**
     * Delete the oldest backups until we have maximum of $num_backups remaining
     * @param int $num_backups
     * @return Loco_fs_Revisions
     */
    
public function prune$num_backups ){
        
$paths $this->getPaths();
        if( isset(
$paths[$num_backups]) ){
            foreach( 
array_slice$paths$num_backups ) as $path ){
                
$this->unlinkLater($path);
            }
            
$this->paths array_slice$paths0$num_backups );
            
$this->length null;
        }
        return 
$this;
    }


    
/**
     * build regex for matching backed up revisions of master
     * @return string
     */
    
private function getRegExp(){
        
$regex $this->regex;
        if( 
is_null($regex) ){
            
$regex preg_quote$this->master->filename(), '/' ).'-backup-(\\d{14,})';
            if( 
$ext $this->master->extension() ){
                
$regex .= preg_quote('.'.$ext,'/');
            }
            
$regex '/^'.$regex.'~/';
            
$this->regex $regex;
        }
        return 
$regex;
    }


    
/**
     * @return array
     */
    
public function getPaths(){
        if( 
is_null($this->paths) ){
            
$this->paths = [];
            
$regex $this->getRegExp();
            
$finder = new Loco_fs_FileFinder$this->master->dirname() );
            
$finder->setRecursive(false);
            
/* @var $file Loco_fs_File */
            
foreach( $finder as $file ){
                if( 
preg_match$regex$file->basename() ) ){
                    
$this->paths[] = $file->getPath();
                }
            }
            
// time sort order descending
            
rsort$this->paths );
        }
        return 
$this->paths;
    }


    
/**
     * Parse a file path into a timestamp
     * @param string $path
     * @return int
     */
    
public function getTimestamp$path ){
        
$name basename($path);
        if( 
preg_match$this->getRegExp(), $name$r ) ){
            
$ymdhis substr$r[1], 014 );
            return 
strtotime$ymdhis );
        }
        throw new 
Loco_error_Exception('Invalid revision file: '.$name);
    }


    
/**
     * Get number of backups plus master
     * @return int
     */
    
#[ReturnTypeWillChange]
    public function 
count(){
        if( ! 
$this->length ){
            
$this->length count$this->getPaths() );
        }
        return 
$this->length;
    }


    
/**
     * Delete file when object removed from memory.
     * Previously unlinked on shutdown, but doesn't work with WordPress file system abstraction
     * @param string $path
     * @return void
     */
    
public function unlinkLater($path){
        
$this->trash[] = new Loco_fs_File($path);
    }


    
/**
     * Execute backup of current file if enabled in settings.
     * @param Loco_api_WordPressFileSystem $api Authorized file system
     * @return Loco_fs_File|null backup file if saved
     */
    
public function rotateLoco_api_WordPressFileSystem $api ){
        
$backup null;
        
$pofile $this->master;
        
$num_backups Loco_data_Settings::get()->num_backups;
        if( 
$num_backups ){
            
// Attempt backup, but return null on failure
            
try {
                
$api->authorizeCopy($pofile);
                
$backup $this->create();
            }
            catch( 
Exception $e ){
                
Loco_error_AdminNotices::debug$e->getMessage() );
                
// translators: %s refers to a directory where a backup file could not be created due to file permissions
                
$message __('Failed to create backup file in "%s". Check file permissions or disable backups','loco-translate');
                
Loco_error_AdminNotices::warnsprintf$message$pofile->getParent()->basename() ) );
            }
            
// prune operation in separate catch block as error would be misleading
            
try {
                
$this->prune($num_backups);
            }
            catch( 
Exception $e ){
                
Loco_error_AdminNotices::debug('Failed to prune backup files: '.$e->getMessage() );
            }
        }
        return 
$backup;
    }

}