Subversion Repositories oidplus

Rev

Rev 315 | 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) {
445
                        $c = substr($c, strlen($local_folder));
446
                        if (substr($c,0,1) === '/') $c = substr($c, 1);
447
                        if ($c === '') unset($local_cont[$key]);
448
                        if (strpos($c,'.svn/') === 0) unset($local_cont[$key]);
449
                        if ((strpos($c,'userdata/') === 0) && ($c !== 'userdata/info.txt') && ($c !== 'userdata/.htaccess') && ($c !== 'userdata/index.html') && (substr($c,-1) !== '/')) unset($local_cont[$key]);
450
                }
451
                unset($key);
452
                unset($c);
453
                natsort($local_cont);
454
 
455
                $svn_cont = array();
456
                $contents = $this->getDirectoryTree($svn_folder, $version, true);
457
                foreach ($contents as $cont) {
458
                        if ($cont['type'] == 'directory') {
316 daniel-mar 459
                                $svn_cont[] = '/'.urldecode($cont['path']).'/';
306 daniel-mar 460
                        } else if ($cont['type'] == 'file') {
316 daniel-mar 461
                                $svn_cont[] = '/'.urldecode($cont['path']);
306 daniel-mar 462
                        }
463
                }
464
                foreach ($svn_cont as $key => &$c) {
465
                        $c = substr($c, strlen($svn_folder));
466
                        if (substr($c,0,1) === '/') $c = substr($c, 1);
467
                        if ($c === '') unset($svn_cont[$key]);
468
                        if ((strpos($c,'userdata/') === 0) && ($c !== 'userdata/info.txt') && ($c !== 'userdata/.htaccess') && ($c !== 'userdata/index.html') && (substr($c,-1) !== '/')) unset($svn_cont[$key]);
469
                }
470
                unset($key);
471
                unset($c);
472
                unset($contents);
473
                unset($cont);
474
                natsort($svn_cont);
475
 
476
                $only_svn = array_diff($svn_cont, $local_cont);
477
                $only_local = array_diff($local_cont, $svn_cont);
478
                return array($svn_cont, $local_cont);
479
        }
480
 
171 daniel-mar 481
        /**
482
         *  getDirectoryTree
483
         *
484
         *  Returns the complete tree of files and directories in $folder from the
485
         *  version $version of the repository. Can also be used to get the info
486
         *  for a single file or directory.
487
         *
488
         *  @param string  $folder Folder to get tree
489
         *  @param integer $version Repository version, -1 means current
490
         *  @param boolean $recursive Whether to get the tree recursively, or just
491
         *  the specified directory/file.
492
         *
493
         *  @return array List of files and directories.
494
         */
495
        private function getDirectoryTree($folder = '/trunk/', $version = -1, $recursive = true)
496
        {
497
                $directoryTree = array();
498
 
499
                if (!($arrOutput = $this->getDirectoryFiles($folder, $version)))
500
                        return false;
501
 
502
                if (!$recursive)
503
                        return $arrOutput[0];
504
 
505
                while (count($arrOutput) && is_array($arrOutput)) {
506
                        $array = array_shift($arrOutput);
507
 
508
                        array_push($directoryTree, $array);
509
 
510
                        if (trim($array['path'], '/') == trim($folder, '/'))
511
                                continue;
512
 
513
                        if ($array['type'] == 'directory') {
514
                                $walk = $this->getDirectoryFiles($array['path'], $version);
515
                                array_shift($walk);
516
 
517
                                foreach ($walk as $step) {
518
                                        array_unshift($arrOutput, $step);
519
                                }
520
                        }
521
                }
522
                return $directoryTree;
523
        }
524
 
525
        /**
526
         *  Returns file contents
527
         *
528
         *  @param      string  $file File pathname
529
         *  @param      integer $version File Version
530
         *  @return     string  File content and information, false on error, or if a
531
         *              directory is requested
532
         */
533
        private function getFile($file, $version = -1)
534
        {
535
                if ($version == -1 || $version > $this->actVersion) {
536
                        $version = $this->actVersion;
537
                }
538
 
539
                // check if this is a directory... if so, return false, otherwise we
540
                // get the HTML output of the directory listing from the SVN server.
541
                // This is maybe a bit heavy since it makes another connection to the
542
                // SVN server. Maybe add this as an option/parameter? ES 23/06/08
543
                $fileInfo = $this->getDirectoryTree($file, $version, false);
544
                if ($fileInfo["type"] == "directory")
545
                        return false;
546
 
547
                $url = $this->cleanURL($this->_url . "/!svn/bc/" . $version . "/" . $file . "/");
548
                $this->initQuery($args, "GET", $url);
549
                if (!$this->Request($args, $headers, $body))
250 daniel-mar 550
                        throw new OIDplusException("Cannot call getFile (Request failed)");
171 daniel-mar 551
 
552
                return $body;
553
        }
554
 
172 daniel-mar 555
        private function getLogsForUpdate($file, $vini = 0, $vend = -1)
171 daniel-mar 556
        {
557
                $fileLogs = array();
558
 
172 daniel-mar 559
                if ($vend == -1) {
171 daniel-mar 560
                        $vend = $this->actVersion;
561
                }
562
 
563
                if ($vini < 0)
564
                        $vini = 0;
565
 
566
                if ($vini > $vend) {
567
                        $vini = $vend;
568
                        echo "Nothing updated\n";
569
                        flush();
570
                        return null;
571
                }
572
 
573
                $url = $this->cleanURL($this->_url . "/!svn/bc/" . $this->actVersion . "/" . $file . "/");
574
                $this->initQuery($args, "REPORT", $url);
251 daniel-mar 575
                $args['Body']                      = sprintf(self::PHPSVN_LOGS_REQUEST, $vini, $vend);
171 daniel-mar 576
                $args['Headers']['Content-Length'] = strlen($args['Body']);
577
                $args['Headers']['Depth']          = 1;
578
 
579
                if (!$this->Request($args, $headers, $body))
250 daniel-mar 580
                        throw new OIDplusException("Cannot call getLogsForUpdate (Request failed)");
171 daniel-mar 581
 
216 daniel-mar 582
                $arrOutput = self::xmlParse($body);
171 daniel-mar 583
 
172 daniel-mar 584
                $revlogs = array();
585
 
171 daniel-mar 586
                $array = array();
227 daniel-mar 587
                if (!isset($arrOutput['children'])) $arrOutput['children'] = array();
171 daniel-mar 588
                foreach ($arrOutput['children'] as $value) {
172 daniel-mar 589
                        /*
590
                        <S:log-item>
591
                        <D:version-name>164</D:version-name>
592
                        <S:date>2019-08-13T13:12:13.915920Z</S:date>
593
                        <D:comment>Update assistant bugfix</D:comment>
594
                        <D:creator-displayname>daniel-marschall</D:creator-displayname>
595
                        <S:modified-path node-kind="file" text-mods="true" prop-mods="false">/trunk/update/index.php</S:modified-path>
596
                        <S:modified-path node-kind="file" text-mods="true" prop-mods="false">/trunk/update/phpsvnclient.inc.php</S:modified-path>
597
                        </S:log-item>
598
                        */
599
 
600
                        $versionName = '';
601
                        $date = '';
602
                        $comment = '';
171 daniel-mar 603
                        foreach ($value['children'] as $entry) {
604
                                if (($entry['name'] == 'S:ADDED-PATH') || ($entry['name'] == 'S:MODIFIED-PATH') || ($entry['name'] == 'S:DELETED-PATH')) {
605
                                        if ($entry['attrs']['NODE-KIND'] == "file") {
606
                                                $array['objects'][] = array(
607
                                                        'object_name' => $entry['tagData'],
608
                                                        'action' => $entry['name'],
609
                                                        'type' => 'file'
610
                                                );
611
                                        } else if ($entry['attrs']['NODE-KIND'] == "dir") {
612
                                                $array['objects'][] = array(
613
                                                        'object_name' => $entry['tagData'],
614
                                                        'action' => $entry['name'],
615
                                                        'type' => 'dir'
616
                                                );
617
                                        }
172 daniel-mar 618
                                } else if ($entry['name'] == 'D:VERSION-NAME') {
619
                                        $versionName = isset($entry['tagData']) ? $entry['tagData'] : '';
620
                                } else if ($entry['name'] == 'S:DATE') {
621
                                        $date = isset($entry['tagData']) ? $entry['tagData'] : '';
622
                                } else if ($entry['name'] == 'D:COMMENT') {
623
                                        $comment = isset($entry['tagData']) ? $entry['tagData'] : '';
624
                                } else if ($entry['name'] == 'D:CREATOR-DISPLAYNAME') {
625
                                        $creator = isset($entry['tagData']) ? $entry['tagData'] : '';
171 daniel-mar 626
                                }
627
                        }
172 daniel-mar 628
                        $revlogs[] = array('versionName' => $versionName,
629
                                           'date' => $date,
630
                                           'comment' => $comment,
631
                                           'creator' => $creator);
171 daniel-mar 632
                }
216 daniel-mar 633
                $files       = array();
634
                $filesDelete = array();
635
                $dirs        = array();
315 daniel-mar 636
                $dirsNew     = array();
637
                $dirsMod     = array();
216 daniel-mar 638
                $dirsDelete  = array();
171 daniel-mar 639
 
227 daniel-mar 640
                if (!isset($array['objects'])) $array['objects'] = array();
171 daniel-mar 641
                foreach ($array['objects'] as $objects) {
216 daniel-mar 642
                        // This section was completely changed by Daniel Marschall
171 daniel-mar 643
                        if ($objects['type'] == "file") {
644
                                if ($objects['action'] == "S:ADDED-PATH" || $objects['action'] == "S:MODIFIED-PATH") {
216 daniel-mar 645
                                        self::xarray_add($objects['object_name'], $files);
646
                                        self::xarray_remove($objects['object_name'], $filesDelete);
171 daniel-mar 647
                                }
648
                                if ($objects['action'] == "S:DELETED-PATH") {
216 daniel-mar 649
                                        self::xarray_add($objects['object_name'], $filesDelete);
650
                                        self::xarray_remove($objects['object_name'], $files);
171 daniel-mar 651
                                }
652
                        }
653
                        if ($objects['type'] == "dir") {
315 daniel-mar 654
                                if ($objects['action'] == "S:ADDED-PATH") {
216 daniel-mar 655
                                        self::xarray_add($objects['object_name'], $dirs);
315 daniel-mar 656
                                        self::xarray_add($objects['object_name'], $dirsNew);
216 daniel-mar 657
                                        self::xarray_remove($objects['object_name'], $dirsDelete);
171 daniel-mar 658
                                }
315 daniel-mar 659
                                if ($objects['action'] == "S:MODIFIED-PATH") {
660
                                        self::xarray_add($objects['object_name'], $dirs);
661
                                        self::xarray_add($objects['object_name'], $dirsMod);
662
                                        self::xarray_remove($objects['object_name'], $dirsDelete);
663
                                }
171 daniel-mar 664
                                if ($objects['action'] == "S:DELETED-PATH") {
665
                                        // Delete files from filelist
216 daniel-mar 666
                                        $files_copy = $files;
667
                                        foreach ($files_copy as $file) {
668
                                                if (strpos($file, $objects['object_name'].'/') === 0) self::xarray_remove($file, $files);
171 daniel-mar 669
                                        }
670
                                        // END OF Delete files from filelist
671
                                        // Delete dirs from dirslist
216 daniel-mar 672
                                        self::xarray_add($objects['object_name'], $dirsDelete);
673
                                        self::xarray_remove($objects['object_name'], $dirs);
315 daniel-mar 674
                                        self::xarray_remove($objects['object_name'], $dirsMod);
675
                                        self::xarray_remove($objects['object_name'], $dirsNew);
171 daniel-mar 676
                                        // END OF Delete dirs from dirslist
677
                                }
678
                        }
679
                }
315 daniel-mar 680
                foreach ($dirsNew as $dir) {
681
                        // For new directories, also download all its contents
316 daniel-mar 682
                        try {
683
                                $contents = $this->getDirectoryTree($dir, $vend, true);
684
                        } catch (Exception $e) {
685
                                // 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
686
                                // In this case, we don't need it and can ignore the error
687
                                $contents = array();
688
                        }
302 daniel-mar 689
                        foreach ($contents as $cont) {
690
                                if ($cont['type'] == 'directory') {
316 daniel-mar 691
                                        $dirname = '/'.urldecode($cont['path']);
302 daniel-mar 692
                                        self::xarray_add($dirname, $dirs);
693
                                        self::xarray_remove($dirname, $dirsDelete);
694
                                } else if ($cont['type'] == 'file') {
316 daniel-mar 695
                                        $filename = '/'.urldecode($cont['path']);
302 daniel-mar 696
                                        self::xarray_add($filename, $files);
697
                                        self::xarray_remove($filename, $filesDelete);
698
                                }
699
                        }
700
                }
171 daniel-mar 701
                $out                = array();
702
                $out['files']       = $files;
703
                $out['filesDelete'] = $filesDelete;
704
                $out['dirs']        = $dirs;
705
                $out['dirsDelete']  = $dirsDelete;
172 daniel-mar 706
                $out['revisions']   = $revlogs;
171 daniel-mar 707
                return $out;
708
        }
709
 
710
        /**
711
         *  Returns the repository version
712
         *
713
         *  @return integer Repository version
714
         *  @access public
715
         */
716
        public function getVersion()
717
        {
718
                if ($this->_repVersion > 0)
719
                        return $this->_repVersion;
720
 
721
                $this->_repVersion = -1;
722
                $this->initQuery($args, "PROPFIND", $this->cleanURL($this->_url . "/!svn/vcc/default"));
251 daniel-mar 723
                $args['Body']                      = self::PHPSVN_VERSION_REQUEST;
724
                $args['Headers']['Content-Length'] = strlen(self::PHPSVN_NORMAL_REQUEST);
171 daniel-mar 725
                $args['Headers']['Depth']          = 0;
726
 
727
                if (!$this->Request($args, $tmp, $body))
250 daniel-mar 728
                        throw new OIDplusException("Cannot get repository revision (Request failed)");
171 daniel-mar 729
 
730
                $this->_repVersion = null;
731
                if (preg_match('@/(\d+)\s*</D:href>@ismU', $body, $m)) {
732
                        $this->_repVersion = $m[1];
733
                } else {
250 daniel-mar 734
                        throw new OIDplusException("Cannot get repository revision (RegEx failed)");
171 daniel-mar 735
                }
736
 
737
                return $this->_repVersion;
738
        }
739
 
740
        /**
741
         *  Private Functions
742
         */
743
 
744
        /**
745
         *  Prepare HTTP CLIENT object
746
         *
747
         *  @param array &$arguments Byreferences variable.
748
         *  @param string $method Method for the request (GET,POST,PROPFIND, REPORT,ETC).
749
         *  @param string $url URL for the action.
750
         *  @access private
751
         */
752
        private function initQuery(&$arguments, $method, $url)
753
        {
754
                $http =& $this->_http;
755
                $http->GetRequestArguments($url, $arguments);
756
                $arguments["RequestMethod"]           = $method;
757
                $arguments["Headers"]["Content-Type"] = "text/xml";
758
                $arguments["Headers"]["Depth"]        = 1;
759
        }
760
 
761
        /**
762
         *  Open a connection, send request, read header
763
         *  and body.
764
         *
765
         *  @param Array $args Connetion's argument
766
         *  @param Array &$headers Array with the header response.
767
         *  @param string &$body Body response.
768
         *  @return boolean True is query success
769
         *  @access private
770
         */
771
        private function Request($args, &$headers, &$body)
772
        {
773
                $args['RequestURI'] = str_replace(' ', '%20', $args['RequestURI']); //Hack to make filenames with spaces work.
774
                $http =& $this->_http;
775
                $http->Open($args);
776
                $http->SendRequest($args);
777
                $http->ReadReplyHeaders($headers);
778
                if ($http->response_status[0] != 2) {
779
                        switch ($http->response_status) {
780
                                case 404:
251 daniel-mar 781
                                        $this->errNro = self::NOT_FOUND;
171 daniel-mar 782
                                        break;
783
                                case 401:
251 daniel-mar 784
                                        $this->errNro = self::AUTH_REQUIRED;
171 daniel-mar 785
                                        break;
786
                                default:
251 daniel-mar 787
                                        $this->errNro = self::UNKNOWN_ERROR;
171 daniel-mar 788
                                        break;
789
                        }
790
                        //            trigger_error("request to $args[RequestURI] failed: $http->response_status
791
                        //Error: $http->error");
792
                        $http->close();
793
                        return false;
794
                }
251 daniel-mar 795
                $this->errNro = self::NO_ERROR;
171 daniel-mar 796
                $body         = '';
797
                $tbody        = '';
798
                for (;;) {
799
                        $error = $http->ReadReplyBody($tbody, 1000);
800
                        if ($error != "" || strlen($tbody) == 0) {
801
                                break;
802
                        }
803
                        $body .= ($tbody);
804
                }
805
                $http->close();
806
                return true;
807
        }
808
 
809
        /**
810
         *  Returns $url stripped of '//'
811
         *
812
         *  Delete "//" on URL requests.
813
         *
814
         *  @param string $url URL
815
         *  @return string New cleaned URL.
816
         *  @access private
817
         */
818
        private function cleanURL($url)
819
        {
820
                return preg_replace("/((^:)\/\/)/", "//", $url);
821
        }
822
 
823
        /*
824
          Taken from http://www.php.net/manual/en/function.xml-parse.php#52567
825
          Modified by Martin Guppy <http://www.deadpan110.com/>
826
          Usage
827
          Grab some XML data, either from a file, URL, etc. however you want.
828
          Assume storage in $strYourXML;
829
          Converted "class" into a single function by Daniel Marschall, ViaThinkSoft
830
         */
831
        private static function xmlParse($strInputXML) {
832
                $arrOutput = array();
833
 
834
                $resParser = xml_parser_create();
835
                xml_set_element_handler($resParser,
836
                        function /*tagOpen*/($parser, $name, $attrs) use (&$arrOutput) {
837
                                $tag = array("name" => $name, "attrs" => $attrs);
838
                                array_push($arrOutput, $tag);
839
                        },
840
                        function /*tagClosed*/($parser, $name) use (&$arrOutput) {
841
                                $arrOutput[count($arrOutput) - 2]['children'][] = $arrOutput[count($arrOutput) - 1];
842
                                array_pop($arrOutput);
843
                        }
844
                );
845
                xml_set_character_data_handler($resParser,
846
                        function /*tagData*/($parser, $tagData) use (&$arrOutput) {
847
                                if (trim($tagData)) {
848
                                        if (isset($arrOutput[count($arrOutput) - 1]['tagData'])) {
849
                                                $arrOutput[count($arrOutput) - 1]['tagData'] .= $tagData;
850
                                        } else {
851
                                                $arrOutput[count($arrOutput) - 1]['tagData'] = $tagData;
852
                                        }
853
                                }
854
                        }
855
                );
856
 
857
                if (!xml_parse($resParser, $strInputXML)) {
858
                        die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($resParser)), xml_get_current_line_number($resParser)));
859
                }
860
 
861
                xml_parser_free($resParser);
862
 
863
                return $arrOutput[0];
864
        }
216 daniel-mar 865
 
866
        /*
867
          Small helper functions
868
        */
869
 
870
        private static function xarray_add($needle, &$array) {
871
                $key = array_search($needle, $array);
872
                if ($key === false) {
873
                        $array[] = $needle;
874
                }
875
        }
876
 
877
        private static function xarray_remove($needle, &$array) {
878
                while (true) {
879
                        $key = array_search($needle, $array);
880
                        if ($key === false) break;
881
                        unset($array[$key]);
882
                }
883
        }
171 daniel-mar 884
}