2 /** FusionForge Subversion plugin
4 * Copyright 2003-2010, Roland Mas, Franck Villaume
5 * Copyright 2004, GForge, LLC
6 * Copyright 2010, Alain Peyrat <aljeux@free.fr>
7 * Copyright 2012, Franck Villaume - TrivialDev
9 * This file is part of FusionForge.
11 * FusionForge is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published
13 * by the Free Software Foundation; either version 2 of the License,
14 * or (at your option) any later version.
16 * FusionForge is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 forge_define_config_item('default_server', 'scmsvn', forge_get_config ('web_host'));
27 forge_define_config_item('repos_path', 'scmsvn', forge_get_config('chroot').'/scmrepos/svn');
28 forge_define_config_item('use_ssh', 'scmsvn', false);
29 forge_set_config_item_bool('use_ssh', 'scmsvn');
30 forge_define_config_item('use_dav', 'scmsvn', true);
31 forge_set_config_item_bool('use_dav', 'scmsvn');
32 forge_define_config_item('use_ssl', 'scmsvn', true);
33 forge_set_config_item_bool('use_ssl', 'scmsvn');
34 forge_define_config_item('anonsvn_login','scmsvn', 'anonsvn');
35 forge_define_config_item('anonsvn_password','scmsvn', 'anonsvn');
37 class SVNPlugin extends SCMPlugin {
38 function SVNPlugin() {
40 $this->name = 'scmsvn';
41 $this->text = 'Subversion';
42 $this->svn_root_fs = '/scmrepos/svn';
43 if (!file_exists($this->svn_root_fs.'/.')) {
44 $this->svn_root_fs = forge_get_config('repos_path',
47 $this->svn_root_dav = '/svn';
48 $this->_addHook('scm_browser_page');
49 $this->_addHook('scm_update_repolist');
50 $this->_addHook('scm_generate_snapshots');
51 $this->_addHook('scm_gather_stats');
53 $this->provides['svn'] = true;
58 function getDefaultServer() {
59 return forge_get_config('default_server', 'scmsvn') ;
62 function printShortStats($params) {
63 $project = $this->checkParams($params);
68 if ($project->usesPlugin($this->name)) {
69 $result = db_query_params('SELECT sum(commits) AS commits, sum(adds) AS adds FROM stats_cvs_group WHERE group_id=$1',
70 array ($project->getID())) ;
71 $commit_num = db_result($result,0,'commits');
72 $add_num = db_result($result,0,'adds');
79 echo ' (Subversion: '.sprintf(_('<strong>%1$s</strong> commits, <strong>%2$s</strong> adds'), number_format($commit_num, 0), number_format($add_num, 0)).")";
84 return '<p>' . _('Documentation for Subversion (sometimes referred to as "SVN") is available <a href="http://svnbook.red-bean.com/">here</a>.') . '</p>';
87 function topModule($project) {
88 // Check toplevel module presence
89 $repo = 'file://' . forge_get_config('repos_path', $this->name).'/'.$project->getUnixName().'/';
92 if (!(exec("svn ls '$repo'", $res) && in_array($module.'/', $res)))
100 function getInstructionsForAnon($project) {
101 $b = '<h2>' . _('Anonymous Subversion Access') . '</h2>';
103 $b .= _("This project's SVN repository can be checked out through anonymous access with the following command(s).");
107 $module = $this->topModule($project);
108 if (forge_get_config('use_ssh', 'scmsvn')) {
109 $b .= '<tt>svn checkout svn://'.$this->getBoxForProject($project).$this->svn_root_fs.'/'.$project->getUnixName().$module.'</tt><br />';
111 if (forge_get_config('use_dav', 'scmsvn')) {
112 $b .= '<tt>svn checkout --username '.forge_get_config('anonsvn_login', 'scmsvn').' http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://' . $this->getBoxForProject($project). $this->svn_root_dav .'/'. $project->getUnixName() .$module.'</tt><br />';
113 $b .= _('The password is ').forge_get_config('anonsvn_password', 'scmsvn').'<br />';
119 function getInstructionsForRW($project) {
122 $module = $this->topModule($project);
124 if (session_loggedin()) {
125 $u =& user_get_object(user_getid());
126 $d = $u->getUnixName() ;
127 if (forge_get_config('use_ssh', 'scmsvn')) {
129 $b .= _('Developer Subversion Access via SSH');
132 $b .= _('Only project developers can access the SVN tree via this method. SSH must be installed on your client machine. Enter your site password when prompted.');
134 $b .= '<p><tt>svn checkout svn+ssh://'.$d.'@' . $this->getBoxForProject($project) . $this->svn_root_fs .'/'. $project->getUnixName().$module.'</tt></p>' ;
136 if (forge_get_config('use_dav', 'scmsvn')) {
138 $b .= _('Developer Subversion Access via DAV');
141 $b .= _('Only project developers can access the SVN tree via this method. Enter your site password when prompted.');
143 $b .= '<p><tt>svn checkout --username '.$d.' http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://'. $this->getBoxForProject($project) . $this->svn_root_dav .'/'.$project->getUnixName().$module.'</tt></p>' ;
146 if (forge_get_config('use_ssh', 'scmsvn')) {
148 $b .= _('Developer Subversion Access via SSH');
151 $b .= _('Only project developers can access the SVN tree via this method. SSH must be installed on your client machine. Substitute <i>developername</i> with the proper values. Enter your site password when prompted.');
153 $b .= '<p><tt>svn checkout svn+ssh://<i>'._('developername').'</i>@' . $this->getBoxForProject($project) . $this->svn_root_fs .'/'. $project->getUnixName().$module.'</tt></p>' ;
155 if (forge_get_config('use_dav', 'scmsvn')) {
157 $b .= _('Developer Subversion Access via DAV');
160 $b .= _('Only project developers can access the SVN tree via this method. Substitute <i>developername</i> with the proper values. Enter your site password when prompted.');
162 $b .= '<p><tt>svn checkout --username <i>'._('developername').'</i> http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://'. $this->getBoxForProject($project) . $this->svn_root_dav .'/'.$project->getUnixName().$module.'</tt></p>' ;
168 function getSnapshotPara($project) {
172 function getBrowserLinkBlock($project) {
174 $b = $HTML->boxMiddle(_('Subversion Repository Browser'));
176 $b .= _('Browsing the Subversion tree gives you a view into the current status of this project\'s code. You may also view the complete histories of any file in the repository.');
179 $b .= util_make_link ("/scm/browser.php?group_id=".$project->getID(),
180 _('Browse Subversion Repository')
186 function getStatsBlock($project) {
190 $result = db_query_params('SELECT u.realname, u.user_name, u.user_id, sum(commits) as commits, sum(adds) as adds, sum(adds+commits) as combined FROM stats_cvs_user s, users u WHERE group_id=$1 AND s.user_id=u.user_id AND (commits>0 OR adds >0) GROUP BY u.user_id, realname, user_name, u.user_id ORDER BY combined DESC, realname',
191 array ($project->getID()));
193 if (db_numrows($result) > 0) {
194 $b .= $HTML->boxMiddle(_('Repository Statistics'));
196 $tableHeaders = array(
201 $b .= $HTML->listTableTop($tableHeaders);
204 $total = array('adds' => 0, 'commits' => 0);
206 while($data = db_fetch_array($result)) {
207 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
208 $b .= '<td width="50%">' ;
209 $b .= util_make_link_u ($data['user_name'], $data['user_id'], $data['realname']) ;
210 $b .= '</td><td width="25%" align="right">'.$data['adds']. '</td>'.
211 '<td width="25%" align="right">'.$data['commits'].'</td></tr>';
212 $total['adds'] += $data['adds'];
213 $total['commits'] += $data['commits'];
216 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
217 $b .= '<td width="50%"><strong>'._('Total').':</strong></td>'.
218 '<td width="25%" align="right"><strong>'.$total['adds']. '</strong></td>'.
219 '<td width="25%" align="right"><strong>'.$total['commits'].'</strong></td>';
221 $b .= $HTML->listTableBottom();
227 function printBrowserPage($params) {
228 $project = $this->checkParams($params);
233 if ($project->usesPlugin($this->name)) {
234 if ($this->browserDisplayable($project)) {
235 session_redirect("/scm/viewvc.php/?root=".$project->getUnixName());
240 function createOrUpdateRepo($params) {
241 $project = $this->checkParams($params);
246 if (! $project->usesPlugin($this->name)) {
250 $repo = forge_get_config('repos_path', 'scmsvn') . '/' . $project->getUnixName();
252 if (!is_dir ($repo) || !is_file ("$repo/format")) {
253 system("svnadmin create $repo") ;
254 system("svn mkdir -m 'Init' file:///$repo/trunk file:///$repo/tags file:///$repo/branches >/dev/null");
257 $this->installOrUpdateCmds($project, $project->getUnixName(), $repo);
259 if (forge_get_config('use_ssh', 'scmsvn')) {
260 $unix_group = 'scm_' . $project->getUnixName();
261 system("find $repo -type d | xargs chmod g+s");
262 system("chgrp -R $unix_group $repo");
263 if ($project->enableAnonSCM() || forge_get_config('use_dav', 'scmsvn')) {
264 system("chmod -R g+wX,o+rX-w $repo");
266 system("chmod -R g+wX,o-rwx $repo");
269 $unix_user = forge_get_config('apache_user');
270 $unix_group = forge_get_config('apache_group');
271 system("chown -R $unix_user:$unix_group $repo");
272 system("chmod -R g-rwx,o-rwx $repo");
276 function updateRepositoryList($params) {
277 $groups = $this->getGroups();
279 // Update WebDAV stuff
280 if (!forge_get_config('use_dav', 'scmsvn')) {
288 foreach ($groups as $project) {
289 if ( !$project->isActive()) {
292 if ( !$project->usesSCM()) {
295 $access_data .= '[' . $project->getUnixName() . ":/]\n";
297 $users = $project->getMembers();
298 foreach ($users as $user) {
299 if (forge_check_perm_for_user($user,
303 $access_data .= $user->getUnixName() . "= rw\n";
304 $svnusers[$user->getID()] = $user;
305 } elseif (forge_check_perm_for_user($user,
309 $access_data .= $user->getUnixName() . "= r\n";
310 $svnusers[$user->getID()] = $user;
314 if ($project->enableAnonSCM()) {
315 $access_data .= forge_get_config('anonsvn_login', 'scmsvn')." = r\n";
316 $access_data .= "* = r\n";
319 $access_data .= "\n";
322 foreach ($svnusers as $user_id => $user) {
323 $password_data .= $user->getUnixName().':'.$user->getUnixPasswd()."\n";
325 $password_data .= forge_get_config('anonsvn_login', 'scmsvn').":".htpasswd_apr1_md5(forge_get_config('anonsvn_password', 'scmsvn'))."\n";
327 $fname = forge_get_config('data_path').'/svnroot-authfile';
328 $f = fopen($fname.'.new', 'w');
329 fwrite($f, $password_data);
331 chmod($fname.'.new', 0644);
332 rename($fname.'.new', $fname);
334 $fname = forge_get_config('data_path').'/svnroot-access';
335 $f = fopen($fname.'.new', 'w');
336 fwrite($f, $access_data);
338 chmod($fname.'.new', 0644);
339 rename($fname.'.new', $fname);
342 function gatherStats($params) {
343 global $last_user, $last_time, $last_tag, $time_ok, $start_time, $end_time,
344 $adds, $deletes, $updates, $commits, $date_key,
345 $usr_adds, $usr_deletes, $usr_updates;
349 $project = $this->checkParams($params);
354 if (! $project->usesPlugin($this->name)) {
358 if ($params['mode'] == 'day') {
361 $year = $params['year'];
362 $month = $params['month'];
363 $day = $params['day'];
364 $month_string = sprintf("%04d%02d", $year, $month);
365 $start_time = gmmktime(0, 0, 0, $month, $day, $year);
366 $end_time = $start_time + 86400;
371 $usr_updates = array();
373 $repo = forge_get_config('repos_path', 'scmsvn') . '/' . $project->getUnixName() ;
374 if (!is_dir ($repo) || !is_file ("$repo/format")) {
375 echo "No repository\n";
380 $d1 = date('Y-m-d', $start_time - 150000);
381 $d2 = date('Y-m-d', $end_time + 150000);
383 $pipe = popen ("svn log file://$repo --xml -v -q -r '".'{'.$d2.'}:{'.$d1.'}'."' 2> /dev/null", 'r' ) ;
385 // cleaning stats_cvs_* table for the current day
386 $res = db_query_params('DELETE FROM stats_cvs_group WHERE month=$1 AND day=$2 AND group_id=$3',
391 echo "Error while cleaning stats_cvs_group\n" ;
396 $res = db_query_params ('DELETE FROM stats_cvs_user WHERE month=$1 AND day=$2 AND group_id=$3',
397 array ($month_string,
399 $project->getID())) ;
401 echo "Error while cleaning stats_cvs_user\n" ;
406 $xml_parser = xml_parser_create();
407 xml_set_element_handler($xml_parser, "SVNPluginStartElement", "SVNPluginEndElement");
408 xml_set_character_data_handler($xml_parser, "SVNPluginCharData");
410 // Analyzing history stream
411 while (!feof($pipe) &&
412 $data = fgets ($pipe, 4096)) {
414 if (!xml_parse ($xml_parser, $data, feof ($pipe))) {
415 debug("Unable to parse XML with error " .
416 xml_error_string(xml_get_error_code($xml_parser)) .
418 xml_get_current_line_number($xml_parser));
425 xml_parser_free ($xml_parser);
427 // inserting group results in stats_cvs_groups
428 if ($updates > 0 || $adds > 0) {
429 if (!db_query_params ('INSERT INTO stats_cvs_group (month,day,group_id,checkouts,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
430 array ($month_string,
436 echo "Error while inserting into stats_cvs_group\n" ;
442 // building the user list
443 $user_list = array_unique( array_merge( array_keys( $usr_adds ), array_keys( $usr_updates ) ) );
445 foreach ( $user_list as $user ) {
446 // trying to get user id from user name
447 $u = &user_get_object_by_name ($user) ;
449 $user_id = $u->getID();
454 $uu = isset($usr_updates[$user]) ? $usr_updates[$user] : 0 ;
455 $ua = isset($usr_adds[$user]) ? $usr_adds[$user] : 0 ;
456 if ($uu > 0 || $ua > 0) {
457 if (!db_query_params ('INSERT INTO stats_cvs_user (month,day,group_id,user_id,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
458 array ($month_string,
464 echo "Error while inserting into stats_cvs_user\n" ;
474 function generateSnapshots($params) {
476 $project = $this->checkParams($params);
481 $group_name = $project->getUnixName();
483 $snapshot = forge_get_config('scm_snapshots_path').'/'.$group_name.'-scm-latest.tar'.util_get_compressed_file_extension();
484 $tarball = forge_get_config('scm_tarballs_path').'/'.$group_name.'-scmroot.tar'.util_get_compressed_file_extension();
486 if (! $project->usesPlugin($this->name)) {
490 if (! $project->enableAnonSCM()) {
491 if (is_file($snapshot)) {
494 if (is_file($tarball)) {
500 $toprepo = forge_get_config('repos_path', 'scmsvn');
501 $repo = $toprepo . '/' . $project->getUnixName();
503 if (!is_dir ($repo) || !is_file ("$repo/format")) {
504 if (is_file($snapshot)) {
507 if (is_file($tarball)) {
513 $tmp = trim (`mktemp -d`) ;
517 $today = date ('Y-m-d') ;
518 $dir = $project->getUnixName ()."-$today" ;
519 system ("mkdir -p $tmp") ;
521 system ("svn ls file://$repo/trunk > /dev/null", $code) ;
523 system ("cd $tmp ; svn export file://$repo/trunk $dir > /dev/null 2>&1") ;
524 system ("tar cCf $tmp - $dir |".forge_get_config('compression_method')."> $tmp/snapshot") ;
525 chmod ("$tmp/snapshot", 0644) ;
526 copy ("$tmp/snapshot", $snapshot) ;
527 unlink ("$tmp/snapshot") ;
528 system ("rm -rf $tmp/$dir") ;
530 if (is_file($snapshot)) {
535 system ("tar cCf $toprepo - ".$project->getUnixName() ."|".forge_get_config('compression_method')."> $tmp/tarball") ;
536 chmod ("$tmp/tarball", 0644) ;
537 copy ("$tmp/tarball", $tarball) ;
538 unlink ("$tmp/tarball") ;
539 system ("rm -rf $tmp") ;
542 function installOrUpdateCmds($project, $unix_group_name, $repos) {
546 $params['unix_group_name'] = $unix_group_name;
547 $group = group_get_object_by_name($unix_group_name);
548 $params['group_id'] = $group->getID();
549 $params['repos'] = $repos;
550 $params['hooks'] = &$hooks;
551 plugin_hook_by_reference('cmd_for_post_commit_hook', $params);
553 foreach ($params['hooks'] as $plugin => $cmd ) {
554 if (getenv('sys_localinc')) {
555 $cmd = 'sys_localinc='.getenv(sys_localinc).' '.$cmd;
557 $contents = @file_get_contents($repos."/hooks/post-commit");
558 if ($project->usesPlugin($plugin)) {
559 if (strstr($contents, "#begin added by $plugin") === false ) {
560 $this->installCmdInHook($repos, $plugin, $cmd);
562 $this->updateCmdInHook($repos, $plugin, $cmd);
564 } elseif (!$project->usesPlugin($plugin) &&
565 (strstr($contents, "#begin added by $plugin") !== false )) {
566 $this->removeCmdInHook($repos, $plugin);
571 function installCmdInHook($repos, $name, $text) {
573 if (file_exists($repos.'/hooks/post-commit')) {
574 $FOut = fopen($repos.'/hooks/post-commit', "a+");
577 $FOut = fopen($repos.'/hooks/post-commit', "w");
578 $Line = '#!/bin/sh'."\n"; // add this line to first line or else the script fails
582 $Line .= "\n#begin added by $name\n$text\n#end added by $name\n";
584 fwrite($FOut, $Line);
586 system("chmod 700 $repos/hooks/post-commit");
591 function updateCmdInHook($repos, $plugin, $text) {
593 $contents = @file_get_contents($repos."/hooks/post-commit");
595 $new = preg_replace("/(#begin added by $plugin\n)(.*)(\n#end added by $plugin)/s", '$1{COMMAND}$3', $contents);
596 $new = str_replace('{COMMAND}', $text, $new);
598 if ($contents !== $new) {
599 $fout = fopen($repos.'/hooks/post-commit', "w");
605 function removeCmdInHook($repos, $plugin) {
607 $contents = @file_get_contents($repos."/hooks/post-commit");
608 $new = preg_replace("/#begin added by $plugin\n.*?\n#end added by $plugin/s", '', $contents);
610 if ($contents !== $new) {
611 if (preg_match("/^#\!\/bin\/sh(\n+)$/s", $new)) {
612 unlink($repos.'/hooks/post-commit');
614 $fout = fopen($repos.'/hooks/post-commit', "w");
622 // End of class, helper functions now
624 function SVNPluginCharData ($parser, $chars) {
625 global $last_tag, $last_user, $last_time, $start_time, $end_time,
626 $time_ok, $user_list;
629 $last_user = ereg_replace ('[^a-z0-9_-]', '',
630 strtolower (trim ($chars))) ;
633 $chars = preg_replace('/T(\d\d:\d\d:\d\d)\.\d+Z?$/', ' ${1}', $chars);
634 $last_time = strtotime($chars);
635 if ($start_time <= $last_time && $last_time < $end_time) {
644 function SVNPluginStartElement($parser, $name, $attrs) {
645 global $last_user, $last_time, $last_tag, $time_ok,
646 $adds, $updates, $usr_adds, $usr_updates;
650 // Make sure we clean up before doing a new log entry
656 if ($attrs['ACTION'] == "M") {
659 $usr_updates[$last_user] = isset($usr_updates[$last_user]) ? ($usr_updates[$last_user]+1) : 0 ;
661 } elseif ($attrs['ACTION'] == "A") {
664 $usr_adds[$last_user] = isset($usr_adds[$last_user]) ? ($usr_adds[$last_user]+1) : 0 ;
672 function SVNPluginEndElement ($parser, $name) {
673 global $time_ok, $last_tag, $commits;
674 if ($name == "LOGENTRY" && $time_ok) {
682 // c-file-style: "bsd"