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>
8 * This file is part of FusionForge.
10 * FusionForge is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published
12 * by the Free Software Foundation; either version 2 of the License,
13 * or (at your option) any later version.
15 * FusionForge is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with FusionForge; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
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 = '/svn';
43 $this->hooks[] = 'scm_browser_page';
44 $this->hooks[] = 'scm_update_repolist' ;
45 $this->hooks[] = 'scm_generate_snapshots' ;
46 $this->hooks[] = 'scm_gather_stats' ;
48 $this->provides['svn'] = true;
53 function getDefaultServer() {
54 return forge_get_config('default_server', 'scmsvn') ;
57 function printShortStats ($params) {
58 $project = $this->checkParams ($params) ;
63 if ($project->usesPlugin($this->name)) {
64 $result = db_query_params('SELECT sum(commits) AS commits, sum(adds) AS adds FROM stats_cvs_group WHERE group_id=$1',
65 array ($project->getID())) ;
66 $commit_num = db_result($result,0,'commits');
67 $add_num = db_result($result,0,'adds');
74 echo ' (Subversion: '.sprintf(_('<strong>%1$s</strong> commits, <strong>%2$s</strong> adds'), number_format($commit_num, 0), number_format($add_num, 0)).")";
78 function getBlurb () {
79 return '<p>' . _('Documentation for Subversion (sometimes referred to as "SVN") is available <a href="http://svnbook.red-bean.com/">here</a>.') . '</p>';
82 function topModule ($project) {
83 // Check toplevel module presence
84 $repo = 'file://' . forge_get_config('repos_path', $this->name).'/'.$project->getUnixName().'/';
87 if (!(exec("svn ls '$repo'", $res) && in_array($module.'/', $res)))
95 function getInstructionsForAnon ($project) {
96 $b = '<h2>' . _('Anonymous Subversion Access') . '</h2>';
98 $b .= _("This project's SVN repository can be checked out through anonymous access with the following command(s).");
102 $module = $this->topModule($project);
103 if (forge_get_config('use_ssh', 'scmsvn')) {
104 $b .= '<tt>svn checkout svn://'.$project->getSCMBox().$this->svn_root.'/'.$project->getUnixName().$module.'</tt><br />';
106 if (forge_get_config('use_dav', 'scmsvn')) {
107 $b .= '<tt>svn checkout --username '.forge_get_config('anonsvn_login', 'scmsvn').' http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://' . $project->getSCMBox(). $this->svn_root .'/'. $project->getUnixName() .$module.'</tt><br/><br/>';
108 $b .= _('The password is ').forge_get_config('anonsvn_password', 'scmsvn').'<br/>';
114 function getInstructionsForRW ($project) {
117 $module = $this->topModule($project);
119 if (session_loggedin()) {
120 $u =& user_get_object(user_getid()) ;
121 $d = $u->getUnixName() ;
122 if (forge_get_config('use_ssh', 'scmsvn')) {
124 $b .= _('Developer Subversion Access via SSH');
127 $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.');
129 $b .= '<p><tt>svn checkout svn+ssh://'.$d.'@' . $project->getSCMBox() . $this->svn_root .'/'. $project->getUnixName().$module.'</tt></p>' ;
131 if (forge_get_config('use_dav', 'scmsvn')) {
133 $b .= _('Developer Subversion Access via DAV');
136 $b .= _('Only project developers can access the SVN tree via this method. Enter your site password when prompted.');
138 $b .= '<p><tt>svn checkout --username '.$d.' http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://'. $project->getSCMBox() . $this->svn_root .'/'.$project->getUnixName().$module.'</tt></p>' ;
141 if (forge_get_config('use_ssh', 'scmsvn')) {
143 $b .= _('Developer Subversion Access via SSH');
146 $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.');
148 $b .= '<p><tt>svn checkout svn+ssh://<i>'._('developername').'</i>@' . $project->getSCMBox() . $this->svn_root .'/'. $project->getUnixName().$module.'</tt></p>' ;
150 if (forge_get_config('use_dav', 'scmsvn')) {
152 $b .= _('Developer Subversion Access via DAV');
155 $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.');
157 $b .= '<p><tt>svn checkout --username <i>'._('developername').'</i> http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://'. $project->getSCMBox() . $this->svn_root .'/'.$project->getUnixName().$module.'</tt></p>' ;
163 function getSnapshotPara ($project) {
167 function getBrowserLinkBlock ($project) {
169 $b = $HTML->boxMiddle(_('Subversion Repository Browser'));
171 $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.');
174 $b .= util_make_link ("/scm/browser.php?group_id=".$project->getID(),
175 _('Browse Subversion Repository')
181 function getStatsBlock ($project) {
185 $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',
186 array ($project->getID()));
188 if (db_numrows($result) > 0) {
189 $b .= $HTML->boxMiddle(_('Repository Statistics'));
191 $tableHeaders = array(
196 $b .= $HTML->listTableTop($tableHeaders);
199 $total = array('adds' => 0, 'commits' => 0);
201 while($data = db_fetch_array($result)) {
202 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
203 $b .= '<td width="50%">' ;
204 $b .= util_make_link_u ($data['user_name'], $data['user_id'], $data['realname']) ;
205 $b .= '</td><td width="25%" align="right">'.$data['adds']. '</td>'.
206 '<td width="25%" align="right">'.$data['commits'].'</td></tr>';
207 $total['adds'] += $data['adds'];
208 $total['commits'] += $data['commits'];
211 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
212 $b .= '<td width="50%"><strong>'._('Total').':</strong></td>'.
213 '<td width="25%" align="right"><strong>'.$total['adds']. '</strong></td>'.
214 '<td width="25%" align="right"><strong>'.$total['commits'].'</strong></td>';
216 $b .= $HTML->listTableBottom();
222 function printBrowserPage ($params) {
223 $project = $this->checkParams ($params) ;
228 if ($project->usesPlugin ($this->name)) {
229 if ($this->browserDisplayable ($project)) {
230 session_redirect("/scm/viewvc.php/?root=".$project->getUnixName());
235 function createOrUpdateRepo ($params) {
236 $project = $this->checkParams ($params) ;
241 if (! $project->usesPlugin ($this->name)) {
245 $repo = forge_get_config('repos_path', 'scmsvn') . '/' . $project->getUnixName() ;
247 if (!is_dir ($repo) || !is_file ("$repo/format")) {
248 system ("svnadmin create $repo") ;
249 system ("svn mkdir -m'Init' file:///$repo/trunk file:///$repo/tags file:///$repo/branches >/dev/null") ;
252 $this->installOrUpdateCmds($project, $project->getUnixName(), $repo);
254 if (forge_get_config('use_ssh', 'scmsvn')) {
255 $unix_group = 'scm_' . $project->getUnixName() ;
256 system ("find $repo -type d | xargs chmod g+s") ;
257 system ("chgrp -R $unix_group $repo") ;
258 if ($project->enableAnonSCM()) {
259 system ("chmod -R g+wX,o+rX-w $repo") ;
261 system ("chmod -R g+wX,o-rwx $repo") ;
264 $unix_user = forge_get_config('apache_user');
265 $unix_group = forge_get_config('apache_group');
266 system ("chown -R $unix_user:$unix_group $repo") ;
267 system ("chmod -R g-rwx,o-rwx $repo") ;
271 function updateRepositoryList ($params) {
272 $groups = $this->getGroups () ;
274 // Update WebDAV stuff
275 if (!forge_get_config('use_dav', 'scmsvn')) {
280 $password_data = '' ;
282 $svnusers = array () ;
283 foreach ($groups as $project) {
284 if ( !$project->isActive()) {
287 $access_data .= '[' . $project->getUnixName () . ":/]\n" ;
289 $users = $project->getMembers () ;
290 foreach ($users as $user) {
291 if (forge_check_perm_for_user ($user,
295 $access_data .= $user->getUnixName() . "= rw\n" ;
296 $svnusers[$user->getID()] = $user ;
297 } elseif (forge_check_perm_for_user ($user,
301 $access_data .= $user->getUnixName() . "= r\n" ;
302 $svnusers[$user->getID()] = $user ;
306 if ( $project->enableAnonSCM() ) {
307 $access_data .= forge_get_config('anonsvn_login', 'scmsvn')." = r\n" ;
308 $access_data .= "* = r\n" ;
311 $access_data .= "\n" ;
314 foreach ($svnusers as $user_id => $user) {
315 $password_data .= $user->getUnixName().':'.$user->getUnixPasswd()."\n" ;
317 $password_data .= forge_get_config('anonsvn_login', 'scmsvn').":".htpasswd_apr1_md5(forge_get_config('anonsvn_password', 'scmsvn'))."\n";
319 $fname = forge_get_config('data_path').'/svnroot-authfile' ;
320 $f = fopen ($fname.'.new', 'w') ;
321 fwrite ($f, $password_data) ;
323 chmod ($fname.'.new', 0644) ;
324 rename ($fname.'.new', $fname) ;
326 $fname = forge_get_config('data_path').'/svnroot-access' ;
327 $f = fopen ($fname.'.new', 'w') ;
328 fwrite ($f, $access_data) ;
330 chmod ($fname.'.new', 0644) ;
331 rename ($fname.'.new', $fname) ;
334 function gatherStats ($params) {
335 global $last_user, $last_time, $last_tag, $time_ok, $start_time, $end_time,
336 $adds, $deletes, $updates, $commits, $date_key,
337 $usr_adds, $usr_deletes, $usr_updates;
341 $project = $this->checkParams ($params) ;
346 if (! $project->usesPlugin ($this->name)) {
350 if ($params['mode'] == 'day') {
353 $year = $params ['year'] ;
354 $month = $params ['month'] ;
355 $day = $params ['day'] ;
356 $month_string = sprintf( "%04d%02d", $year, $month );
357 $start_time = gmmktime( 0, 0, 0, $month, $day, $year);
358 $end_time = $start_time + 86400;
362 $usr_adds = array () ;
363 $usr_updates = array () ;
365 $repo = forge_get_config('repos_path', 'scmsvn') . '/' . $project->getUnixName() ;
366 if (!is_dir ($repo) || !is_file ("$repo/format")) {
367 echo "No repository\n" ;
372 $d1 = date ('Y-m-d', $start_time - 150000) ;
373 $d2 = date ('Y-m-d', $end_time + 150000) ;
375 $pipe = popen ("svn log file://$repo --xml -v -q -r '".'{'.$d2.'}:{'.$d1.'}'."' 2> /dev/null", 'r' ) ;
377 // cleaning stats_cvs_* table for the current day
378 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE month=$1 AND day=$2 AND group_id=$3',
379 array ($month_string,
381 $project->getID())) ;
383 echo "Error while cleaning stats_cvs_group\n" ;
388 $res = db_query_params ('DELETE FROM stats_cvs_user WHERE month=$1 AND day=$2 AND group_id=$3',
389 array ($month_string,
391 $project->getID())) ;
393 echo "Error while cleaning stats_cvs_user\n" ;
398 $xml_parser = xml_parser_create();
399 xml_set_element_handler($xml_parser, "SVNPluginStartElement", "SVNPluginEndElement");
400 xml_set_character_data_handler($xml_parser, "SVNPluginCharData");
402 // Analyzing history stream
403 while (!feof($pipe) &&
404 $data = fgets ($pipe, 4096)) {
406 if (!xml_parse ($xml_parser, $data, feof ($pipe))) {
407 debug("Unable to parse XML with error " .
408 xml_error_string(xml_get_error_code($xml_parser)) .
410 xml_get_current_line_number($xml_parser));
417 xml_parser_free ($xml_parser);
419 // inserting group results in stats_cvs_groups
420 if ($updates > 0 || $adds > 0) {
421 if (!db_query_params ('INSERT INTO stats_cvs_group (month,day,group_id,checkouts,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
422 array ($month_string,
428 echo "Error while inserting into stats_cvs_group\n" ;
434 // building the user list
435 $user_list = array_unique( array_merge( array_keys( $usr_adds ), array_keys( $usr_updates ) ) );
437 foreach ( $user_list as $user ) {
438 // trying to get user id from user name
439 $u = &user_get_object_by_name ($user) ;
441 $user_id = $u->getID();
446 $uu = isset($usr_updates[$user]) ? $usr_updates[$user] : 0 ;
447 $ua = isset($usr_adds[$user]) ? $usr_adds[$user] : 0 ;
448 if ($uu > 0 || $ua > 0) {
449 if (!db_query_params ('INSERT INTO stats_cvs_user (month,day,group_id,user_id,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
450 array ($month_string,
456 echo "Error while inserting into stats_cvs_user\n" ;
466 function generateSnapshots ($params) {
468 $project = $this->checkParams ($params) ;
473 $group_name = $project->getUnixName() ;
475 $snapshot = forge_get_config('scm_snapshots_path').'/'.$group_name.'-scm-latest.tar'.util_get_compressed_file_extension();
476 $tarball = forge_get_config('scm_tarballs_path').'/'.$group_name.'-scmroot.tar'.util_get_compressed_file_extension();
478 if (! $project->usesPlugin ($this->name)) {
482 if (! $project->enableAnonSCM()) {
483 if (is_file($snapshot)) {
486 if (is_file($tarball)) {
492 $toprepo = forge_get_config('repos_path', 'scmsvn') ;
493 $repo = $toprepo . '/' . $project->getUnixName() ;
495 if (!is_dir ($repo) || !is_file ("$repo/format")) {
496 if (is_file($snapshot)) {
499 if (is_file($tarball)) {
505 $tmp = trim (`mktemp -d`) ;
509 $today = date ('Y-m-d') ;
510 $dir = $project->getUnixName ()."-$today" ;
511 system ("mkdir -p $tmp") ;
513 system ("svn ls file://$repo/trunk > /dev/null", $code) ;
515 system ("cd $tmp ; svn export file://$repo/trunk $dir > /dev/null 2>&1") ;
516 system ("tar cCf $tmp - $dir |".forge_get_config('compression_method')."> snapshot") ;
517 chmod ("$tmp/snapshot", 0644) ;
518 copy ("$tmp/snapshot", $snapshot) ;
519 unlink ("$tmp/snapshot") ;
520 system ("rm -rf $tmp/$dir") ;
522 if (is_file($snapshot)) {
527 system ("tar cCf $toprepo - ".$project->getUnixName() ."|".forge_get_config('compression_method')."> $tmp/tarball") ;
528 chmod ("$tmp/tarball", 0644) ;
529 copy ("$tmp/tarball", $tarball) ;
530 unlink ("$tmp/tarball") ;
531 system ("rm -rf $tmp") ;
534 function installOrUpdateCmds($project, $unix_group_name, $repos) {
538 $params['unix_group_name'] = $unix_group_name;
539 $group = group_get_object_by_name($unix_group_name);
540 $params['group_id'] = $group->getID();
541 $params['repos'] = $repos;
542 $params['hooks'] = &$hooks;
543 plugin_hook('cmd_for_post_commit_hook', $params);
545 foreach ($params['hooks'] as $plugin => $cmd ) {
546 if (getenv('sys_localinc')) {
547 $cmd = 'sys_localinc='.getenv(sys_localinc).' '.$cmd;
549 $contents = @file_get_contents($repos."/hooks/post-commit");
550 if ($project->usesPlugin($plugin)) {
551 if (strstr($contents, "#begin added by $plugin") === false ) {
552 $this->installCmdInHook($repos, $plugin, $cmd);
554 $this->updateCmdInHook($repos, $plugin, $cmd);
556 } elseif (!$project->usesPlugin($plugin) &&
557 (strstr($contents, "#begin added by $plugin") !== false )) {
558 $this->removeCmdInHook($repos, $plugin);
563 function installCmdInHook($repos, $name, $text) {
565 if (file_exists($repos.'/hooks/post-commit')) {
566 $FOut = fopen($repos.'/hooks/post-commit', "a+");
569 $FOut = fopen($repos.'/hooks/post-commit', "w");
570 $Line = '#!/bin/sh'."\n"; // add this line to first line or else the script fails
574 $Line .= "\n#begin added by $name\n$text\n#end added by $name\n";
576 fwrite($FOut, $Line);
578 system("chmod 700 $repos/hooks/post-commit");
583 function updateCmdInHook($repos, $plugin, $text) {
585 $contents = @file_get_contents($repos."/hooks/post-commit");
587 $new = preg_replace("/(#begin added by $plugin\n)(.*)(\n#end added by $plugin)/s", '$1{COMMAND}$3', $contents);
588 $new = str_replace('{COMMAND}', $text, $new);
590 if ($contents !== $new) {
591 $fout = fopen($repos.'/hooks/post-commit', "w");
597 function removeCmdInHook($repos, $plugin) {
599 $contents = @file_get_contents($repos."/hooks/post-commit");
600 $new = preg_replace("/#begin added by $plugin\n.*?\n#end added by $plugin/s", '', $contents);
602 if ($contents !== $new) {
603 if (preg_match("/^#\!\/bin\/sh(\n+)$/s", $new)) {
604 unlink($repos.'/hooks/post-commit');
606 $fout = fopen($repos.'/hooks/post-commit', "w");
614 // End of class, helper functions now
616 function SVNPluginCharData ($parser, $chars) {
617 global $last_tag, $last_user, $last_time, $start_time, $end_time,
618 $time_ok, $user_list;
621 $last_user = ereg_replace ('[^a-z0-9_-]', '',
622 strtolower (trim ($chars))) ;
625 $chars = preg_replace('/T(\d\d:\d\d:\d\d)\.\d+Z?$/', ' ${1}', $chars);
626 $last_time = strtotime($chars);
627 if ($start_time <= $last_time && $last_time < $end_time) {
636 function SVNPluginStartElement($parser, $name, $attrs) {
637 global $last_user, $last_time, $last_tag, $time_ok,
638 $adds, $updates, $usr_adds, $usr_updates;
642 // Make sure we clean up before doing a new log entry
648 if ($attrs['ACTION'] == "M") {
651 $usr_updates[$last_user] = isset($usr_updates[$last_user]) ? ($usr_updates[$last_user]+1) : 0 ;
653 } elseif ($attrs['ACTION'] == "A") {
656 $usr_adds[$last_user] = isset($usr_adds[$last_user]) ? ($usr_adds[$last_user]+1) : 0 ;
664 function SVNPluginEndElement ($parser, $name) {
665 global $time_ok, $last_tag, $commits;
666 if ($name == "LOGENTRY" && $time_ok) {
674 // c-file-style: "bsd"