Subversion Repositories oidplus

Rev

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