Subversion Repositories oidplus

Rev

Rev 316 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
171 daniel-mar 1
<?php
2
 
3
/*
4
 * This file includes:
5
 *
6
 * 1. "PHP SVN CLIENT" class
7
 *    Copyright (C) 2007-2008 by Sixdegrees <cesar@sixdegrees.com.br>
8
 *    Cesar D. Rodas
9
 *    https://code.google.com/archive/p/phpsvnclient/
10
 *    License: BSD License
11
 *    CHANGES by Daniel Marschall, ViaThinkSoft in 2019:
12
 *    - The class has been customized and contains specific changes for the software "OIDplus"
13
 *    - Functions which are not used in the "SVN checkout" were removed.
172 daniel-mar 14
 *      The only important functions are getVersion() and updateWorkingCopy()
171 daniel-mar 15
 *    - The dependency class xml2array was converted from a class into a function and
16
 *      included into this class
172 daniel-mar 17
 *    - Added "revision log/comment" functionality
171 daniel-mar 18
 *
19
 * 2. "xml2array" class
20
 *    Taken from http://www.php.net/manual/en/function.xml-parse.php#52567
21
 *    Modified by Martin Guppy <http://www.deadpan110.com/>
22
 *    CHANGES by Daniel Marschall, ViaThinkSoft in 2019:
23
 *    - Converted class into a single function and added that function into the phpsvnclient class
24
 */
25
 
26
/**
27
 *  PHP SVN CLIENT
28
 *
29
 *  This class is a SVN client. It can perform read operations
30
 *  to a SVN server (over Web-DAV).
31
 *  It can get directory files, file contents, logs. All the operaration
32
 *  could be done for a specific version or for the last version.
33
 *
34
 *  @author Cesar D. Rodas <cesar@sixdegrees.com.br>
35
 *  @license BSD License
36
 */
251 daniel-mar 37
class phpsvnclient {
38
 
269 daniel-mar 39
        /*protected*/ const PHPSVN_NORMAL_REQUEST = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><getlastmodified xmlns="DAV:"/> <checked-in xmlns="DAV:"/><version-name xmlns="DAV:"/><version-controlled-configuration xmlns="DAV:"/><resourcetype xmlns="DAV:"/><baseline-relative-path xmlns="http://subversion.tigris.org/xmlns/dav/"/><repository-uuid xmlns="http://subversion.tigris.org/xmlns/dav/"/></prop></propfind>';
293 daniel-mar 40
 
269 daniel-mar 41
        /*protected*/ const PHPSVN_VERSION_REQUEST = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><checked-in xmlns="DAV:"/></prop></propfind>';
293 daniel-mar 42
 
269 daniel-mar 43
        /*protected*/ const PHPSVN_LOGS_REQUEST = '<?xml version="1.0" encoding="utf-8"?> <S:log-report xmlns:S="svn:"> <S:start-revision>%d</S:start-revision><S:end-revision>%d</S:end-revision><S:path></S:path><S:discover-changed-paths/></S:log-report>';
293 daniel-mar 44
 
269 daniel-mar 45
        /*protected*/ const NO_ERROR = 1;
46
        /*protected*/ const NOT_FOUND = 2;
47
        /*protected*/ const AUTH_REQUIRED = 3;
48
        /*protected*/ const UNKNOWN_ERROR = 4;
251 daniel-mar 49
 
171 daniel-mar 50
        /**
51
         *  SVN Repository URL
52
         *
53
         *  @var string
54
         *  @access private
55
         */
56
        private $_url;
57
 
58
        /**
59
         *  HTTP Client object
60
         *
61
         *  @var object
62
         *  @access private
63
         */
64
        private $_http;
65
 
66
        /**
67
         *  Respository Version.
68
         *
69
         *  @access private
70
         *  @var interger
71
         */
72
        private $_repVersion;
73
 
74
        /**
75
         *  Last error number
76
         *
77
         *  Possible values are NOT_ERROR, NOT_FOUND, AUTH_REQUIRED, UNKOWN_ERROR
78
         *
79
         *  @access public
80
         *  @var integer
81
         */
82
        public $errNro;
83
 
84
        /**
85
         * Number of actual revision local repository.
86
         * @var Integer, Long
87
         */
88
        private $actVersion;
89
        private $storeDirectoryFiles = array();
90
        private $lastDirectoryFiles;
91
        private $file_size;
92
        private $file_size_founded = false;
93
 
94
        public function __construct($url)
95
        {
96
                $http =& $this->_http;
97
                $http             = new http_class;
98
                $http->user_agent = "phpsvnclient (https://code.google.com/archive/p/phpsvnclient/)";
99
 
100
                $this->_url = $url;
101
 
102
                $this->actVersion = $this->getVersion();
103
        }
104
 
105
        /**
106
         * Function for creating directories.
107
         * @param type $path The path to the directory that will be created.
108
         */
109
        private function createDirs($path)
110
        {
111
                $dirs = explode("/", $path);
112
 
113
                foreach ($dirs as $dir) {
114
                        if ($dir != "") {
115
                                $createDir = substr($path, 0, strpos($path, $dir) + strlen($dir));
116
                                @mkdir($createDir);
117
                        }
118
                }
119
        }
120
 
121
        /**
122
         * Function for the recursive removal of directories.
123
         * @param type $path The path to the directory to be deleted.
124
         * @return type Returns the status of a function or function rmdir unlink.
125
         */
126
        private function removeDirs($path)
127
        {
128
                if (is_dir($path)) {
129
                        $entries = scandir($path);
130
                        if ($entries === false) {
131
                                $entries = array();
132
                        }
133
                        foreach ($entries as $entry) {
134
                                if ($entry != '.' && $entry != '..') {
135
                                        $this->removeDirs($path . '/' . $entry);
136
                                }
137
                        }
138
                        return @rmdir($path);
139
                } else {
140
                        return @unlink($path);
141
                }
142
        }
143
 
144
        /**
145
         *  Public Functions
146
         */
147
 
148
        /**
172 daniel-mar 149
        * Updates a working copy
150
        * @param $from_revision Either a revision number or a text file with the
151
        *                       contents "Revision ..." (if it is a file,
152
        *                       the file revision will be updated if everything
153
        *                       was successful)
154
        * @param $folder        SVN remote folder
155
        * @param $outpath       Local path of the working copy
156
        * @param $preview       Only simulate, do not write to files
157
        **/
158
        public function updateWorkingCopy($from_revision='version.txt', $folder = '/trunk/', $outPath = '.', $preview = false)
171 daniel-mar 159
        {
160
                if (!is_dir($outPath)) {
161
                        echo "ERROR: Local path $outPath not existing\n";
162
                        flush();
163
                        return false;
164
                }
165
 
303 daniel-mar 166
                $webbrowser_update = !is_numeric($from_revision);
167
 
172 daniel-mar 168
                if (!is_numeric($from_revision)) {
169
                        $version_file = $from_revision;
170
                        $from_revision = -1;
171
 
172
                        if (!file_exists($version_file)) {
173
                                echo "ERROR: $version_file missing\n";
171 daniel-mar 174
                                flush();
175
                                return false;
172 daniel-mar 176
                        } else {
177
                                //Obtain the number of current version number of the local copy.
178
                                $cont = file_get_contents($version_file);
179
                                if (!preg_match('@Revision (\d+)@', $cont, $m)) {
180
                                        echo "ERROR: $version_file unknown format\n";
181
                                        flush();
182
                                        return false;
183
                                }
184
                                $from_revision = $m[1];
185
 
186
                                echo "Found $version_file with revision information $from_revision\n";
187
                                flush();
171 daniel-mar 188
                        }
172 daniel-mar 189
                } else {
190
                        $version_file = '';
191
                }
171 daniel-mar 192
 
172 daniel-mar 193
                $errors_happened = false;
194
 
303 daniel-mar 195
                if ($webbrowser_update) {
196
                        // First, do some read/write test (even if we are in preview mode, because we want to detect errors before it is too late)
197
                        $file = $outPath . '/dummy_'.uniqid().'.tmp';
198
                        $file = str_replace("///", "/", $file);
199
                        if (@file_put_contents($file, 'Write Test') === false) {
200
                                echo (!$preview ? "ERROR" : "WARNING").": Cannot write test file $file ! An update through the web browser will NOT be possible.\n";
201
                                flush();
202
                                if (!$preview) return false;
203
                        }
204
                        @unlink($file);
205
                        if (file_exists($file)) {
206
                                echo (!$preview ? "ERROR" : "WARNING").": Cannot delete test file $file ! An update through the web browser will NOT be possible.\n";
207
                                flush();
208
                                if (!$preview) return false;
209
                        }
172 daniel-mar 210
                }
171 daniel-mar 211
 
172 daniel-mar 212
                //Get a list of objects to be updated.
213
                $objects_list = $this->getLogsForUpdate($folder, $from_revision + 1);
214
                if (!is_null($objects_list)) {
215
                        // Output version information
216
                        foreach ($objects_list['revisions'] as $revision) {
216 daniel-mar 217
                                $comment = empty($revision['comment']) ? 'No comment' : $revision['comment'];
186 daniel-mar 218
                                $tex = "New revision ".$revision['versionName']." by ".$revision['creator']." (".date('Y-m-d H:i:s', strtotime($revision['date'])).") ";
216 daniel-mar 219
                                echo trim($tex . str_replace("\n", "\n".str_repeat(' ', strlen($tex)), $comment));
186 daniel-mar 220
                                echo "\n";
171 daniel-mar 221
                        }
222
 
172 daniel-mar 223
                        // Add dirs
200 daniel-mar 224
                        sort($objects_list['dirs']); // <-- added by Daniel Marschall: Sort folder list, so that directories will be created in the correct hierarchical order
172 daniel-mar 225
                        foreach ($objects_list['dirs'] as $file) {
226
                                if ($file != '') {
227
                                        $localPath = str_replace($folder, "", $file);
228
                                        $localPath = rtrim($outPath,DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($localPath,DIRECTORY_SEPARATOR);
171 daniel-mar 229
 
172 daniel-mar 230
                                        echo "Added or modified directory: $file\n";
231
                                        flush();
232
                                        if (!$preview) {
233
                                                $this->createDirs($localPath);
234
                                                if (!is_dir($localPath)) {
235
                                                        $errors_happened = true;
236
                                                        echo "=> FAILED\n";
237
                                                        flush();
171 daniel-mar 238
                                                }
239
                                        }
240
                                }
172 daniel-mar 241
                        }
171 daniel-mar 242
 
172 daniel-mar 243
                        // Add files
200 daniel-mar 244
                        sort($objects_list['files']); // <-- added by Daniel Marschall: Sort list, just for cosmetic improvement
172 daniel-mar 245
                        foreach ($objects_list['files'] as $file) {
246
                                if ($file != '') {
247
                                        $localFile = str_replace($folder, "", $file);
248
                                        $localFile = rtrim($outPath,DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($localFile,DIRECTORY_SEPARATOR);
171 daniel-mar 249
 
172 daniel-mar 250
                                        echo "Added or modified file: $file\n";
251
                                        flush();
252
                                        if (!$preview) {
253
                                                $contents = $this->getFile($file);
254
                                                if (@file_put_contents($localFile, $contents) === false) {
255
                                                        $errors_happened = true;
256
                                                        echo "=> FAILED\n";
257
                                                        flush();
171 daniel-mar 258
                                                }
259
                                        }
260
                                }
172 daniel-mar 261
                        }
216 daniel-mar 262
 
263
                        // Remove files
200 daniel-mar 264
                        sort($objects_list['filesDelete']); // <-- added by Daniel Marschall: Sort list, just for cosmetic improvement
172 daniel-mar 265
                        foreach ($objects_list['filesDelete'] as $file) {
266
                                if ($file != '') {
267
                                        $localFile = str_replace($folder, "", $file);
268
                                        $localFile = rtrim($outPath,DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($localFile,DIRECTORY_SEPARATOR);
171 daniel-mar 269
 
172 daniel-mar 270
                                        echo "Removed file: $file\n";
271
                                        flush();
171 daniel-mar 272
 
172 daniel-mar 273
                                        if (!$preview) {
274
                                                @unlink($localFile);
275
                                                if (file_exists($localFile)) {
276
                                                        $errors_happened = true;
277
                                                        echo "=> FAILED\n";
278
                                                        flush();
171 daniel-mar 279
                                                }
280
                                        }
281
                                }
172 daniel-mar 282
                        }
171 daniel-mar 283
 
172 daniel-mar 284
                        // Remove dirs
285
                        // Changed by Daniel Marschall: moved this to the end, because "add/update" requests for this directory might happen before the directory gets removed
200 daniel-mar 286
                        rsort($objects_list['dirsDelete']); // <-- added by Daniel Marschall: Sort list in reverse order, so that directories get deleted in the correct hierarchical order
172 daniel-mar 287
                        foreach ($objects_list['dirsDelete'] as $file) {
288
                                if ($file != '') {
289
                                        $localPath = str_replace($folder, "", $file);
290
                                        $localPath = rtrim($outPath,DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($localPath,DIRECTORY_SEPARATOR);
171 daniel-mar 291
 
172 daniel-mar 292
                                        echo "Removed directory: $file\n";
293
                                        flush();
171 daniel-mar 294
 
172 daniel-mar 295
                                        if (!$preview) {
296
                                                $this->removeDirs($localPath);
297
                                                if (is_dir($localPath)) {
298
                                                        $errors_happened = true;
299
                                                        echo "=> FAILED\n";
300
                                                        flush();
171 daniel-mar 301
                                                }
302
                                        }
303
                                }
172 daniel-mar 304
                        }
171 daniel-mar 305
 
216 daniel-mar 306
                        // Update version file
172 daniel-mar 307
                        // Changed by Daniel Marschall: Added $errors_happened
308
                        if (!$preview && !empty($version_file)) {
309
                                if (!$errors_happened) {
310
                                        if (@file_put_contents($version_file, "Revision " . $this->actVersion . "\n") === false) {
311
                                                echo "ERROR: Could not set the revision\n";
312
                                                flush();
313
                                                return false;
171 daniel-mar 314
                                        } else {
172 daniel-mar 315
                                                echo "Set revision to " . $this->actVersion . "\n";
171 daniel-mar 316
                                                flush();
172 daniel-mar 317
                                                return true;
171 daniel-mar 318
                                        }
172 daniel-mar 319
                                } else {
320
                                        echo "Revision NOT set to " . $this->actVersion . " because some files/dirs could not be updated. Please try again.\n";
321
                                        flush();
322
                                        return false;
171 daniel-mar 323
                                }
172 daniel-mar 324
                        } else {
325
                                return true;
171 daniel-mar 326
                        }
327
                }
328
        }
329
 
330
        /**
331
         *  rawDirectoryDump
332
         *
333
         * Dumps SVN data for $folder in the version $version of the repository.
334
         *
335
         *  @param string  $folder Folder to get data
336
         *  @param integer $version Repository version, -1 means actual
337
         *  @return array SVN data dump.
338
         */
339
        private function rawDirectoryDump($folder = '/trunk/', $version = -1)
340
        {
341
                if ($version == -1 || $version > $this->actVersion) {
342
                        $version = $this->actVersion;
343
                }
344
                $url = $this->cleanURL($this->_url . "/!svn/bc/" . $version . "/" . $folder . "/");
345
                $this->initQuery($args, "PROPFIND", $url);
251 daniel-mar 346
                $args['Body']                      = self::PHPSVN_NORMAL_REQUEST;
347
                $args['Headers']['Content-Length'] = strlen(self::PHPSVN_NORMAL_REQUEST);
171 daniel-mar 348
 
349
                if (!$this->Request($args, $headers, $body))
250 daniel-mar 350
                        throw new OIDplusException("Cannot get rawDirectoryDump (Request failed)");
171 daniel-mar 351
 
216 daniel-mar 352
                return self::xmlParse($body);
171 daniel-mar 353
        }
354
 
355
        /**
356
         *  getDirectoryFiles
357
         *
358
         *  Returns all the files in $folder in the version $version of
359
         *  the repository.
360
         *
361
         *  @param string  $folder Folder to get files
362
         *  @param integer $version Repository version, -1 means actual
363
         *  @return array List of files.
364
         */
365
        private function getDirectoryFiles($folder = '/trunk/', $version = -1)
366
        {
367
                if ($arrOutput = $this->rawDirectoryDump($folder, $version)) {
368
                        $files = array();
369
                        foreach ($arrOutput['children'] as $key => $value) {
172 daniel-mar 370
                                array_walk_recursive($value,
371
                                        function ($item, $key) {
372
                                                if ($key == 'name') {
373
                                                        if (($item == 'D:HREF') || ($item == 'LP1:GETLASTMODIFIED') || ($item == 'LP1:VERSION-NAME') || ($item == 'LP2:BASELINE-RELATIVE-PATH') || ($item == 'LP3:BASELINE-RELATIVE-PATH') || ($item == 'D:STATUS')) {
374
                                                                $this->lastDirectoryFiles = $item;
375
                                                        }
376
                                                } elseif (($key == 'tagData') && ($this->lastDirectoryFiles != '')) {
377
 
378
                                                        // Unsure if the 1st of two D:HREF's always returns the result we want, but for now...
379
                                                        if (($this->lastDirectoryFiles == 'D:HREF') && (isset($this->storeDirectoryFiles['type'])))
380
                                                                return;
381
 
382
                                                        // Dump into the array
383
                                                        switch ($this->lastDirectoryFiles) {
384
                                                                case 'D:HREF':
385
                                                                        $var = 'type';
386
                                                                        break;
387
                                                                case 'LP1:VERSION-NAME':
388
                                                                        $var = 'version';
389
                                                                        break;
390
                                                                case 'LP1:GETLASTMODIFIED':
391
                                                                        $var = 'last-mod';
392
                                                                        break;
393
                                                                case 'LP2:BASELINE-RELATIVE-PATH':
394
                                                                case 'LP3:BASELINE-RELATIVE-PATH':
395
                                                                        $var = 'path';
396
                                                                        break;
397
                                                                case 'D:STATUS':
398
                                                                        $var = 'status';
399
                                                                        break;
400
                                                        }
401
                                                        $this->storeDirectoryFiles[$var] = $item;
402
                                                        $this->lastDirectoryFiles        = '';
403
 
404
                                                        // Detect 'type' as either a 'directory' or 'file'
405
                                                        if ((isset($this->storeDirectoryFiles['type'])) && (isset($this->storeDirectoryFiles['last-mod'])) && (isset($this->storeDirectoryFiles['path'])) && (isset($this->storeDirectoryFiles['status']))) {
406
                                                                $this->storeDirectoryFiles['path'] = str_replace(' ', '%20', $this->storeDirectoryFiles['path']); //Hack to make filenames with spaces work.
407
                                                                $len                               = strlen($this->storeDirectoryFiles['path']);
408
                                                                if (substr($this->storeDirectoryFiles['type'], strlen($this->storeDirectoryFiles['type']) - $len) == $this->storeDirectoryFiles['path']) {
409
                                                                        $this->storeDirectoryFiles['type'] = 'file';
410
                                                                } else {
411
                                                                        $this->storeDirectoryFiles['type'] = 'directory';
412
                                                                }
413
                                                        }
414
                                                } else {
415
                                                        $this->lastDirectoryFiles = '';
416
                                                }
417
                                        }
418
                                );
171 daniel-mar 419
                                array_push($files, $this->storeDirectoryFiles);
420
                                unset($this->storeDirectoryFiles);
421
                        }
422
                        return $files;
423
                }
424
                return false;
425
        }
426
 
306 daniel-mar 427
        private static function dirToArray($dir, &$result) {
428
                $cdir = scandir($dir);
429
                foreach ($cdir as $key => $value) {
430
                        if (!in_array($value,array('.','..'))) {
431
                                if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
432
                                        $result[] = $dir.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR;
433
                                        self::dirToArray($dir.DIRECTORY_SEPARATOR.$value, $result);
434
                                } else {
435
                                        $result[] = $dir.DIRECTORY_SEPARATOR.$value;
436
                                }
437
                        }
438
                }
439
        }
440
 
441
        public function compareToDirectory($local_folder, $svn_folder='/trunk/', $version=-1) {
442
                $local_cont = array();
443
                self::dirToArray($local_folder, $local_cont);
444
                foreach ($local_cont as $key => &$c) {
350 daniel-mar 445
                        $c = str_replace('\\', '/', $c);
306 daniel-mar 446
                        $c = substr($c, strlen($local_folder));
447
                        if (substr($c,0,1) === '/') $c = substr($c, 1);
448
                        if ($c === '') unset($local_cont[$key]);
449
                        if (strpos($c,'.svn/') === 0) unset($local_cont[$key]);
450
                        if ((strpos($c,'userdata/') === 0) && ($c !== 'userdata/info.txt') && ($c !== 'userdata/.htaccess') && ($c !== 'userdata/index.html') && (substr($c,-1) !== '/')) unset($local_cont[$key]);
451
                }
452
                unset($key);
453
                unset($c);
454
                natsort($local_cont);
455
 
456
                $svn_cont = array();
457
                $contents = $this->getDirectoryTree($svn_folder, $version, true);
458
                foreach ($contents as $cont) {
459
                        if ($cont['type'] == 'directory') {
316 daniel-mar 460
                                $svn_cont[] = '/'.urldecode($cont['path']).'/';
306 daniel-mar 461
                        } else if ($cont['type'] == 'file') {
316 daniel-mar 462
                                $svn_cont[] = '/'.urldecode($cont['path']);
306 daniel-mar 463
                        }
464
                }
465
                foreach ($svn_cont as $key => &$c) {
350 daniel-mar 466
                        $c = str_replace('\\', '/', $c);
306 daniel-mar 467
                        $c = substr($c, strlen($svn_folder));
468
                        if (substr($c,0,1) === '/') $c = substr($c, 1);
469
                        if ($c === '') unset($svn_cont[$key]);
470
                        if ((strpos($c,'userdata/') === 0) && ($c !== 'userdata/info.txt') && ($c !== 'userdata/.htaccess') && ($c !== 'userdata/index.html') && (substr($c,-1) !== '/')) unset($svn_cont[$key]);
471
                }
472
                unset($key);
473
                unset($c);
474
                unset($contents);
475
                unset($cont);
476
                natsort($svn_cont);
477
 
478
                $only_svn = array_diff($svn_cont, $local_cont);
479
                $only_local = array_diff($local_cont, $svn_cont);
480
                return array($svn_cont, $local_cont);
481
        }
482
 
171 daniel-mar 483
        /**
484
         *  getDirectoryTree
485
         *
486
         *  Returns the complete tree of files and directories in $folder from the
487
         *  version $version of the repository. Can also be used to get the info
488
         *  for a single file or directory.
489
         *
490
         *  @param string  $folder Folder to get tree
491
         *  @param integer $version Repository version, -1 means current
492
         *  @param boolean $recursive Whether to get the tree recursively, or just
493
         *  the specified directory/file.
494
         *
495
         *  @return array List of files and directories.
496
         */
497
        private function getDirectoryTree($folder = '/trunk/', $version = -1, $recursive = true)
498
        {
499
                $directoryTree = array();
500
 
501
                if (!($arrOutput = $this->getDirectoryFiles($folder, $version)))
502
                        return false;
503
 
504
                if (!$recursive)
505
                        return $arrOutput[0];
506
 
507
                while (count($arrOutput) && is_array($arrOutput)) {
508
                        $array = array_shift($arrOutput);
509
 
510
                        array_push($directoryTree, $array);
511
 
512
                        if (trim($array['path'], '/') == trim($folder, '/'))
513
                                continue;
514
 
515
                        if ($array['type'] == 'directory') {
516
                                $walk = $this->getDirectoryFiles($array['path'], $version);
517
                                array_shift($walk);
518
 
519
                                foreach ($walk as $step) {
520
                                        array_unshift($arrOutput, $step);
521
                                }
522
                        }
523
                }
524
                return $directoryTree;
525
        }
526
 
527
        /**
528
         *  Returns file contents
529
         *
530
         *  @param      string  $file File pathname
531
         *  @param      integer $version File Version
532
         *  @return     string  File content and information, false on error, or if a
533
         *              directory is requested
534
         */
535
        private function getFile($file, $version = -1)
536
        {
537
                if ($version == -1 || $version > $this->actVersion) {
538
                        $version = $this->actVersion;
539
                }
540
 
541
                // check if this is a directory... if so, return false, otherwise we
542
                // get the HTML output of the directory listing from the SVN server.
543
                // This is maybe a bit heavy since it makes another connection to the
544
                // SVN server. Maybe add this as an option/parameter? ES 23/06/08
545
                $fileInfo = $this->getDirectoryTree($file, $version, false);
546
                if ($fileInfo["type"] == "directory")
547
                        return false;
548
 
549
                $url = $this->cleanURL($this->_url . "/!svn/bc/" . $version . "/" . $file . "/");
550
                $this->initQuery($args, "GET", $url);
551
                if (!$this->Request($args, $headers, $body))
250 daniel-mar 552
                        throw new OIDplusException("Cannot call getFile (Request failed)");
171 daniel-mar 553
 
554
                return $body;
555
        }
556
 
172 daniel-mar 557
        private function getLogsForUpdate($file, $vini = 0, $vend = -1)
171 daniel-mar 558
        {
559
                $fileLogs = array();
560
 
172 daniel-mar 561
                if ($vend == -1) {
171 daniel-mar 562
                        $vend = $this->actVersion;
563
                }
564
 
565
                if ($vini < 0)
566
                        $vini = 0;
567
 
568
                if ($vini > $vend) {
569
                        $vini = $vend;
570
                        echo "Nothing updated\n";
571
                        flush();
572
                        return null;
573
                }
574
 
575
                $url = $this->cleanURL($this->_url . "/!svn/bc/" . $this->actVersion . "/" . $file . "/");
576
                $this->initQuery($args, "REPORT", $url);
251 daniel-mar 577
                $args['Body']                      = sprintf(self::PHPSVN_LOGS_REQUEST, $vini, $vend);
171 daniel-mar 578
                $args['Headers']['Content-Length'] = strlen($args['Body']);
579
                $args['Headers']['Depth']          = 1;
580
 
581
                if (!$this->Request($args, $headers, $body))
250 daniel-mar 582
                        throw new OIDplusException("Cannot call getLogsForUpdate (Request failed)");
171 daniel-mar 583
 
216 daniel-mar 584
                $arrOutput = self::xmlParse($body);
171 daniel-mar 585
 
172 daniel-mar 586
                $revlogs = array();
587
 
171 daniel-mar 588
                $array = array();
227 daniel-mar 589
                if (!isset($arrOutput['children'])) $arrOutput['children'] = array();
171 daniel-mar 590
                foreach ($arrOutput['children'] as $value) {
172 daniel-mar 591
                        /*
592
                        <S:log-item>
593
                        <D:version-name>164</D:version-name>
594
                        <S:date>2019-08-13T13:12:13.915920Z</S:date>
595
                        <D:comment>Update assistant bugfix</D:comment>
596
                        <D:creator-displayname>daniel-marschall</D:creator-displayname>
597
                        <S:modified-path node-kind="file" text-mods="true" prop-mods="false">/trunk/update/index.php</S:modified-path>
598
                        <S:modified-path node-kind="file" text-mods="true" prop-mods="false">/trunk/update/phpsvnclient.inc.php</S:modified-path>
599
                        </S:log-item>
600
                        */
601
 
602
                        $versionName = '';
603
                        $date = '';
604
                        $comment = '';
171 daniel-mar 605
                        foreach ($value['children'] as $entry) {
606
                                if (($entry['name'] == 'S:ADDED-PATH') || ($entry['name'] == 'S:MODIFIED-PATH') || ($entry['name'] == 'S:DELETED-PATH')) {
607
                                        if ($entry['attrs']['NODE-KIND'] == "file") {
608
                                                $array['objects'][] = array(
609
                                                        'object_name' => $entry['tagData'],
610
                                                        'action' => $entry['name'],
611
                                                        'type' => 'file'
612
                                                );
613
                                        } else if ($entry['attrs']['NODE-KIND'] == "dir") {
614
                                                $array['objects'][] = array(
615
                                                        'object_name' => $entry['tagData'],
616
                                                        'action' => $entry['name'],
617
                                                        'type' => 'dir'
618
                                                );
619
                                        }
172 daniel-mar 620
                                } else if ($entry['name'] == 'D:VERSION-NAME') {
621
                                        $versionName = isset($entry['tagData']) ? $entry['tagData'] : '';
622
                                } else if ($entry['name'] == 'S:DATE') {
623
                                        $date = isset($entry['tagData']) ? $entry['tagData'] : '';
624
                                } else if ($entry['name'] == 'D:COMMENT') {
625
                                        $comment = isset($entry['tagData']) ? $entry['tagData'] : '';
626
                                } else if ($entry['name'] == 'D:CREATOR-DISPLAYNAME') {
627
                                        $creator = isset($entry['tagData']) ? $entry['tagData'] : '';
171 daniel-mar 628
                                }
629
                        }
172 daniel-mar 630
                        $revlogs[] = array('versionName' => $versionName,
631
                                           'date' => $date,
632
                                           'comment' => $comment,
633
                                           'creator' => $creator);
171 daniel-mar 634
                }
216 daniel-mar 635
                $files       = array();
636
                $filesDelete = array();
637
                $dirs        = array();
315 daniel-mar 638
                $dirsNew     = array();
639
                $dirsMod     = array();
216 daniel-mar 640
                $dirsDelete  = array();
171 daniel-mar 641
 
227 daniel-mar 642
                if (!isset($array['objects'])) $array['objects'] = array();
171 daniel-mar 643
                foreach ($array['objects'] as $objects) {
216 daniel-mar 644
                        // This section was completely changed by Daniel Marschall
171 daniel-mar 645
                        if ($objects['type'] == "file") {
646
                                if ($objects['action'] == "S:ADDED-PATH" || $objects['action'] == "S:MODIFIED-PATH") {
216 daniel-mar 647
                                        self::xarray_add($objects['object_name'], $files);
648
                                        self::xarray_remove($objects['object_name'], $filesDelete);
171 daniel-mar 649
                                }
650
                                if ($objects['action'] == "S:DELETED-PATH") {
216 daniel-mar 651
                                        self::xarray_add($objects['object_name'], $filesDelete);
652
                                        self::xarray_remove($objects['object_name'], $files);
171 daniel-mar 653
                                }
654
                        }
655
                        if ($objects['type'] == "dir") {
315 daniel-mar 656
                                if ($objects['action'] == "S:ADDED-PATH") {
216 daniel-mar 657
                                        self::xarray_add($objects['object_name'], $dirs);
315 daniel-mar 658
                                        self::xarray_add($objects['object_name'], $dirsNew);
216 daniel-mar 659
                                        self::xarray_remove($objects['object_name'], $dirsDelete);
171 daniel-mar 660
                                }
315 daniel-mar 661
                                if ($objects['action'] == "S:MODIFIED-PATH") {
662
                                        self::xarray_add($objects['object_name'], $dirs);
663
                                        self::xarray_add($objects['object_name'], $dirsMod);
664
                                        self::xarray_remove($objects['object_name'], $dirsDelete);
665
                                }
171 daniel-mar 666
                                if ($objects['action'] == "S:DELETED-PATH") {
667
                                        // Delete files from filelist
216 daniel-mar 668
                                        $files_copy = $files;
669
                                        foreach ($files_copy as $file) {
670
                                                if (strpos($file, $objects['object_name'].'/') === 0) self::xarray_remove($file, $files);
171 daniel-mar 671
                                        }
672
                                        // END OF Delete files from filelist
673
                                        // Delete dirs from dirslist
216 daniel-mar 674
                                        self::xarray_add($objects['object_name'], $dirsDelete);
675
                                        self::xarray_remove($objects['object_name'], $dirs);
315 daniel-mar 676
                                        self::xarray_remove($objects['object_name'], $dirsMod);
677
                                        self::xarray_remove($objects['object_name'], $dirsNew);
171 daniel-mar 678
                                        // END OF Delete dirs from dirslist
679
                                }
680
                        }
681
                }
315 daniel-mar 682
                foreach ($dirsNew as $dir) {
683
                        // For new directories, also download all its contents
316 daniel-mar 684
                        try {
685
                                $contents = $this->getDirectoryTree($dir, $vend, true);
686
                        } catch (Exception $e) {
687
                                // This can happen when you update from a very old version and a directory was new which is not existing in the newest ($vend) version
688
                                // In this case, we don't need it and can ignore the error
689
                                $contents = array();
690
                        }
302 daniel-mar 691
                        foreach ($contents as $cont) {
692
                                if ($cont['type'] == 'directory') {
316 daniel-mar 693
                                        $dirname = '/'.urldecode($cont['path']);
302 daniel-mar 694
                                        self::xarray_add($dirname, $dirs);
695
                                        self::xarray_remove($dirname, $dirsDelete);
696
                                } else if ($cont['type'] == 'file') {
316 daniel-mar 697
                                        $filename = '/'.urldecode($cont['path']);
302 daniel-mar 698
                                        self::xarray_add($filename, $files);
699
                                        self::xarray_remove($filename, $filesDelete);
700
                                }
701
                        }
702
                }
171 daniel-mar 703
                $out                = array();
704
                $out['files']       = $files;
705
                $out['filesDelete'] = $filesDelete;
706
                $out['dirs']        = $dirs;
707
                $out['dirsDelete']  = $dirsDelete;
172 daniel-mar 708
                $out['revisions']   = $revlogs;
171 daniel-mar 709
                return $out;
710
        }
711
 
712
        /**
713
         *  Returns the repository version
714
         *
715
         *  @return integer Repository version
716
         *  @access public
717
         */
718
        public function getVersion()
719
        {
720
                if ($this->_repVersion > 0)
721
                        return $this->_repVersion;
722
 
723
                $this->_repVersion = -1;
724
                $this->initQuery($args, "PROPFIND", $this->cleanURL($this->_url . "/!svn/vcc/default"));
251 daniel-mar 725
                $args['Body']                      = self::PHPSVN_VERSION_REQUEST;
726
                $args['Headers']['Content-Length'] = strlen(self::PHPSVN_NORMAL_REQUEST);
171 daniel-mar 727
                $args['Headers']['Depth']          = 0;
728
 
729
                if (!$this->Request($args, $tmp, $body))
250 daniel-mar 730
                        throw new OIDplusException("Cannot get repository revision (Request failed)");
171 daniel-mar 731
 
732
                $this->_repVersion = null;
733
                if (preg_match('@/(\d+)\s*</D:href>@ismU', $body, $m)) {
734
                        $this->_repVersion = $m[1];
735
                } else {
250 daniel-mar 736
                        throw new OIDplusException("Cannot get repository revision (RegEx failed)");
171 daniel-mar 737
                }
738
 
739
                return $this->_repVersion;
740
        }
741
 
742
        /**
743
         *  Private Functions
744
         */
745
 
746
        /**
747
         *  Prepare HTTP CLIENT object
748
         *
749
         *  @param array &$arguments Byreferences variable.
750
         *  @param string $method Method for the request (GET,POST,PROPFIND, REPORT,ETC).
751
         *  @param string $url URL for the action.
752
         *  @access private
753
         */
754
        private function initQuery(&$arguments, $method, $url)
755
        {
756
                $http =& $this->_http;
757
                $http->GetRequestArguments($url, $arguments);
758
                $arguments["RequestMethod"]           = $method;
759
                $arguments["Headers"]["Content-Type"] = "text/xml";
760
                $arguments["Headers"]["Depth"]        = 1;
761
        }
762
 
763
        /**
764
         *  Open a connection, send request, read header
765
         *  and body.
766
         *
767
         *  @param Array $args Connetion's argument
768
         *  @param Array &$headers Array with the header response.
769
         *  @param string &$body Body response.
770
         *  @return boolean True is query success
771
         *  @access private
772
         */
773
        private function Request($args, &$headers, &$body)
774
        {
775
                $args['RequestURI'] = str_replace(' ', '%20', $args['RequestURI']); //Hack to make filenames with spaces work.
776
                $http =& $this->_http;
777
                $http->Open($args);
778
                $http->SendRequest($args);
779
                $http->ReadReplyHeaders($headers);
780
                if ($http->response_status[0] != 2) {
781
                        switch ($http->response_status) {
782
                                case 404:
251 daniel-mar 783
                                        $this->errNro = self::NOT_FOUND;
171 daniel-mar 784
                                        break;
785
                                case 401:
251 daniel-mar 786
                                        $this->errNro = self::AUTH_REQUIRED;
171 daniel-mar 787
                                        break;
788
                                default:
251 daniel-mar 789
                                        $this->errNro = self::UNKNOWN_ERROR;
171 daniel-mar 790
                                        break;
791
                        }
792
                        //            trigger_error("request to $args[RequestURI] failed: $http->response_status
793
                        //Error: $http->error");
794
                        $http->close();
795
                        return false;
796
                }
251 daniel-mar 797
                $this->errNro = self::NO_ERROR;
171 daniel-mar 798
                $body         = '';
799
                $tbody        = '';
800
                for (;;) {
801
                        $error = $http->ReadReplyBody($tbody, 1000);
802
                        if ($error != "" || strlen($tbody) == 0) {
803
                                break;
804
                        }
805
                        $body .= ($tbody);
806
                }
807
                $http->close();
808
                return true;
809
        }
810
 
811
        /**
812
         *  Returns $url stripped of '//'
813
         *
814
         *  Delete "//" on URL requests.
815
         *
816
         *  @param string $url URL
817
         *  @return string New cleaned URL.
818
         *  @access private
819
         */
820
        private function cleanURL($url)
821
        {
822
                return preg_replace("/((^:)\/\/)/", "//", $url);
823
        }
824
 
825
        /*
826
          Taken from http://www.php.net/manual/en/function.xml-parse.php#52567
827
          Modified by Martin Guppy <http://www.deadpan110.com/>
828
          Usage
829
          Grab some XML data, either from a file, URL, etc. however you want.
830
          Assume storage in $strYourXML;
831
          Converted "class" into a single function by Daniel Marschall, ViaThinkSoft
832
         */
833
        private static function xmlParse($strInputXML) {
834
                $arrOutput = array();
835
 
836
                $resParser = xml_parser_create();
837
                xml_set_element_handler($resParser,
838
                        function /*tagOpen*/($parser, $name, $attrs) use (&$arrOutput) {
839
                                $tag = array("name" => $name, "attrs" => $attrs);
840
                                array_push($arrOutput, $tag);
841
                        },
842
                        function /*tagClosed*/($parser, $name) use (&$arrOutput) {
843
                                $arrOutput[count($arrOutput) - 2]['children'][] = $arrOutput[count($arrOutput) - 1];
844
                                array_pop($arrOutput);
845
                        }
846
                );
847
                xml_set_character_data_handler($resParser,
848
                        function /*tagData*/($parser, $tagData) use (&$arrOutput) {
849
                                if (trim($tagData)) {
850
                                        if (isset($arrOutput[count($arrOutput) - 1]['tagData'])) {
851
                                                $arrOutput[count($arrOutput) - 1]['tagData'] .= $tagData;
852
                                        } else {
853
                                                $arrOutput[count($arrOutput) - 1]['tagData'] = $tagData;
854
                                        }
855
                                }
856
                        }
857
                );
858
 
859
                if (!xml_parse($resParser, $strInputXML)) {
860
                        die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($resParser)), xml_get_current_line_number($resParser)));
861
                }
862
 
863
                xml_parser_free($resParser);
864
 
865
                return $arrOutput[0];
866
        }
216 daniel-mar 867
 
868
        /*
869
          Small helper functions
870
        */
871
 
872
        private static function xarray_add($needle, &$array) {
873
                $key = array_search($needle, $array);
874
                if ($key === false) {
875
                        $array[] = $needle;
876
                }
877
        }
878
 
879
        private static function xarray_remove($needle, &$array) {
880
                while (true) {
881
                        $key = array_search($needle, $array);
882
                        if ($key === false) break;
883
                        unset($array[$key]);
884
                }
885
        }
171 daniel-mar 886
}