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 along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 forge_define_config_item ('default_server', 'scmsvn', forge_get_config ('web_host')) ;
26 forge_define_config_item ('repos_path', 'scmsvn', forge_get_config('chroot').'/scmrepos/svn') ;
27 forge_define_config_item ('use_ssh', 'scmsvn', false) ;
28 forge_set_config_item_bool ('use_ssh', 'scmsvn') ;
29 forge_define_config_item ('use_dav', 'scmsvn', true) ;
30 forge_set_config_item_bool ('use_dav', 'scmsvn') ;
31 forge_define_config_item ('use_ssl', 'scmsvn', true) ;
32 forge_set_config_item_bool ('use_ssl', 'scmsvn') ;
33 forge_define_config_item ('anonsvn_login','scmsvn', 'anonsvn');
34 forge_define_config_item ('anonsvn_password','scmsvn', 'anonsvn');
36 class SVNPlugin extends SCMPlugin {
37 function SVNPlugin () {
39 $this->name = 'scmsvn';
40 $this->text = 'Subversion';
41 $this->svn_root_fs = '/scmrepos/svn';
42 if (!file_exists($this->svn_root_fs.'/.')) {
43 $this->svn_root_fs = forge_get_config('repos_path',
46 $this->svn_root_dav = '/svn';
47 $this->hooks[] = 'scm_browser_page';
48 $this->hooks[] = 'scm_update_repolist' ;
49 $this->hooks[] = 'scm_generate_snapshots' ;
50 $this->hooks[] = 'scm_gather_stats' ;
52 $this->provides['svn'] = true;
57 function getDefaultServer() {
58 return forge_get_config('default_server', 'scmsvn') ;
61 function printShortStats ($params) {
62 $project = $this->checkParams ($params) ;
67 if ($project->usesPlugin($this->name)) {
68 $result = db_query_params('SELECT sum(commits) AS commits, sum(adds) AS adds FROM stats_cvs_group WHERE group_id=$1',
69 array ($project->getID())) ;
70 $commit_num = db_result($result,0,'commits');
71 $add_num = db_result($result,0,'adds');
78 echo ' (Subversion: '.sprintf(_('<strong>%1$s</strong> commits, <strong>%2$s</strong> adds'), number_format($commit_num, 0), number_format($add_num, 0)).")";
82 function getBlurb () {
83 return '<p>' . _('Documentation for Subversion (sometimes referred to as "SVN") is available <a href="http://svnbook.red-bean.com/">here</a>.') . '</p>';
86 function topModule ($project) {
87 // Check toplevel module presence
88 $repo = 'file://' . forge_get_config('repos_path', $this->name).'/'.$project->getUnixName().'/';
91 if (!(exec("svn ls '$repo'", $res) && in_array($module.'/', $res)))
99 function getInstructionsForAnon ($project) {
100 $b = '<h2>' . _('Anonymous Subversion Access') . '</h2>';
102 $b .= _("This project's SVN repository can be checked out through anonymous access with the following command(s).");
106 $module = $this->topModule($project);
107 if (forge_get_config('use_ssh', 'scmsvn')) {
108 $b .= '<tt>svn checkout svn://'.$project->getSCMBox().$this->svn_root_fs.'/'.$project->getUnixName().$module.'</tt><br />';
110 if (forge_get_config('use_dav', 'scmsvn')) {
111 $b .= '<tt>svn checkout --username '.forge_get_config('anonsvn_login', 'scmsvn').' http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://' . $project->getSCMBox(). $this->svn_root_dav .'/'. $project->getUnixName() .$module.'</tt><br />';
112 $b .= _('The password is ').forge_get_config('anonsvn_password', 'scmsvn').'<br />';
118 function getInstructionsForRW ($project) {
121 $module = $this->topModule($project);
123 if (session_loggedin()) {
124 $u =& user_get_object(user_getid()) ;
125 $d = $u->getUnixName() ;
126 if (forge_get_config('use_ssh', 'scmsvn')) {
128 $b .= _('Developer Subversion Access via SSH');
131 $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.');
133 $b .= '<p><tt>svn checkout svn+ssh://'.$d.'@' . $project->getSCMBox() . $this->svn_root_fs .'/'. $project->getUnixName().$module.'</tt></p>' ;
135 if (forge_get_config('use_dav', 'scmsvn')) {
137 $b .= _('Developer Subversion Access via DAV');
140 $b .= _('Only project developers can access the SVN tree via this method. Enter your site password when prompted.');
142 $b .= '<p><tt>svn checkout --username '.$d.' http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://'. $project->getSCMBox() . $this->svn_root_dav .'/'.$project->getUnixName().$module.'</tt></p>' ;
145 if (forge_get_config('use_ssh', 'scmsvn')) {
147 $b .= _('Developer Subversion Access via SSH');
150 $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.');
152 $b .= '<p><tt>svn checkout svn+ssh://<i>'._('developername').'</i>@' . $project->getSCMBox() . $this->svn_root_fs .'/'. $project->getUnixName().$module.'</tt></p>' ;
154 if (forge_get_config('use_dav', 'scmsvn')) {
156 $b .= _('Developer Subversion Access via DAV');
159 $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.');
161 $b .= '<p><tt>svn checkout --username <i>'._('developername').'</i> http'.((forge_get_config('use_ssl', 'scmsvn')) ? 's' : '').'://'. $project->getSCMBox() . $this->svn_root_dav .'/'.$project->getUnixName().$module.'</tt></p>' ;
167 function getSnapshotPara ($project) {
171 function getBrowserLinkBlock ($project) {
173 $b = $HTML->boxMiddle(_('Subversion Repository Browser'));
175 $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.');
178 $b .= util_make_link ("/scm/browser.php?group_id=".$project->getID(),
179 _('Browse Subversion Repository')
185 function getStatsBlock ($project) {
189 $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',
190 array ($project->getID()));
192 if (db_numrows($result) > 0) {
193 $b .= $HTML->boxMiddle(_('Repository Statistics'));
195 $tableHeaders = array(
200 $b .= $HTML->listTableTop($tableHeaders);
203 $total = array('adds' => 0, 'commits' => 0);
205 while($data = db_fetch_array($result)) {
206 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
207 $b .= '<td width="50%">' ;
208 $b .= util_make_link_u ($data['user_name'], $data['user_id'], $data['realname']) ;
209 $b .= '</td><td width="25%" align="right">'.$data['adds']. '</td>'.
210 '<td width="25%" align="right">'.$data['commits'].'</td></tr>';
211 $total['adds'] += $data['adds'];
212 $total['commits'] += $data['commits'];
215 $b .= '<tr '. $HTML->boxGetAltRowStyle($i) .'>';
216 $b .= '<td width="50%"><strong>'._('Total').':</strong></td>'.
217 '<td width="25%" align="right"><strong>'.$total['adds']. '</strong></td>'.
218 '<td width="25%" align="right"><strong>'.$total['commits'].'</strong></td>';
220 $b .= $HTML->listTableBottom();
226 function printBrowserPage ($params) {
227 $project = $this->checkParams ($params) ;
232 if ($project->usesPlugin ($this->name)) {
233 if ($this->browserDisplayable ($project)) {
234 session_redirect("/scm/viewvc.php/?root=".$project->getUnixName());
239 function createOrUpdateRepo ($params) {
240 $project = $this->checkParams ($params) ;
245 if (! $project->usesPlugin ($this->name)) {
249 $repo = forge_get_config('repos_path', 'scmsvn') . '/' . $project->getUnixName() ;
251 if (!is_dir ($repo) || !is_file ("$repo/format")) {
252 system ("svnadmin create $repo") ;
253 system ("svn mkdir -m'Init' file:///$repo/trunk file:///$repo/tags file:///$repo/branches >/dev/null") ;
256 $this->installOrUpdateCmds($project, $project->getUnixName(), $repo);
258 if (forge_get_config('use_ssh', 'scmsvn')) {
259 $unix_group = 'scm_' . $project->getUnixName() ;
260 system ("find $repo -type d | xargs -I{} chmod g+s {}") ;
261 system ("chgrp -R $unix_group $repo") ;
262 if ($project->enableAnonSCM()) {
263 system ("chmod -R g+wX,o+rX-w $repo") ;
265 system ("chmod -R g+wX,o-rwx $repo") ;
268 $unix_user = forge_get_config('apache_user');
269 $unix_group = forge_get_config('apache_group');
270 system ("chown -R $unix_user:$unix_group $repo") ;
271 system ("chmod -R g-rwx,o-rwx $repo") ;
275 function updateRepositoryList ($params) {
276 $groups = $this->getGroups () ;
278 // Update WebDAV stuff
279 if (!forge_get_config('use_dav', 'scmsvn')) {
284 $password_data = '' ;
285 $engine = RBACEngine::getInstance() ;
288 foreach ($groups as $project) {
289 if ( !$project->isActive()) {
292 if ( !$project->usesSCM()) {
295 $access_data .= '[' . $project->getUnixName () . ":/]\n" ;
297 $users = $engine->getUsersByAllowedAction('scm',$project->getID(),'read');
298 foreach ($users as $user) {
299 $svnusers[$user->getID()] = $user ;
300 if (forge_check_perm_for_user ($user,
304 $access_data .= $user->getUnixName() . "= rw\n" ;
306 $access_data .= $user->getUnixName() . "= r\n" ;
310 if ( $project->enableAnonSCM() ) {
311 $access_data .= forge_get_config('anonsvn_login', 'scmsvn')." = r\n" ;
312 $access_data .= "* = r\n" ;
315 $access_data .= "\n" ;
318 foreach ($svnusers as $user_id => $user) {
319 $password_data .= $user->getUnixName().':'.$user->getUnixPasswd()."\n" ;
321 $password_data .= forge_get_config('anonsvn_login', 'scmsvn').":".htpasswd_apr1_md5(forge_get_config('anonsvn_password', 'scmsvn'))."\n";
323 $fname = forge_get_config('data_path').'/svnroot-authfile' ;
324 $f = fopen ($fname.'.new', 'w') ;
325 fwrite ($f, $password_data) ;
327 chmod ($fname.'.new', 0644) ;
328 rename ($fname.'.new', $fname) ;
330 $fname = forge_get_config('data_path').'/svnroot-access' ;
331 $f = fopen ($fname.'.new', 'w') ;
332 fwrite ($f, $access_data) ;
334 chmod ($fname.'.new', 0644) ;
335 rename ($fname.'.new', $fname) ;
338 function gatherStats ($params) {
339 global $last_user, $last_time, $last_tag, $time_ok, $start_time, $end_time,
340 $adds, $deletes, $updates, $commits, $date_key,
341 $usr_adds, $usr_deletes, $usr_updates;
345 $project = $this->checkParams ($params) ;
350 if (! $project->usesPlugin ($this->name)) {
354 if ($params['mode'] == 'day') {
357 $year = $params ['year'] ;
358 $month = $params ['month'] ;
359 $day = $params ['day'] ;
360 $month_string = sprintf( "%04d%02d", $year, $month );
361 $start_time = gmmktime( 0, 0, 0, $month, $day, $year);
362 $end_time = $start_time + 86400;
366 $usr_adds = array () ;
367 $usr_updates = array () ;
369 $repo = forge_get_config('repos_path', 'scmsvn') . '/' . $project->getUnixName() ;
370 if (!is_dir ($repo) || !is_file ("$repo/format")) {
371 echo "No repository\n" ;
376 $d1 = date ('Y-m-d', $start_time - 150000) ;
377 $d2 = date ('Y-m-d', $end_time + 150000) ;
379 $pipe = popen ("svn log file://$repo --xml -v -q -r '".'{'.$d2.'}:{'.$d1.'}'."' 2> /dev/null", 'r' ) ;
381 // cleaning stats_cvs_* table for the current day
382 $res = db_query_params ('DELETE FROM stats_cvs_group WHERE month=$1 AND day=$2 AND group_id=$3',
383 array ($month_string,
385 $project->getID())) ;
387 echo "Error while cleaning stats_cvs_group\n" ;
392 $res = db_query_params ('DELETE FROM stats_cvs_user WHERE month=$1 AND day=$2 AND group_id=$3',
393 array ($month_string,
395 $project->getID())) ;
397 echo "Error while cleaning stats_cvs_user\n" ;
402 $xml_parser = xml_parser_create();
403 xml_set_element_handler($xml_parser, "SVNPluginStartElement", "SVNPluginEndElement");
404 xml_set_character_data_handler($xml_parser, "SVNPluginCharData");
406 // Analyzing history stream
407 while (!feof($pipe) &&
408 $data = fgets ($pipe, 4096)) {
410 if (!xml_parse ($xml_parser, $data, feof ($pipe))) {
411 debug("Unable to parse XML with error " .
412 xml_error_string(xml_get_error_code($xml_parser)) .
414 xml_get_current_line_number($xml_parser));
421 xml_parser_free ($xml_parser);
423 // inserting group results in stats_cvs_groups
424 if ($updates > 0 || $adds > 0) {
425 if (!db_query_params ('INSERT INTO stats_cvs_group (month,day,group_id,checkouts,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
426 array ($month_string,
432 echo "Error while inserting into stats_cvs_group\n" ;
438 // building the user list
439 $user_list = array_unique( array_merge( array_keys( $usr_adds ), array_keys( $usr_updates ) ) );
441 foreach ( $user_list as $user ) {
442 // trying to get user id from user name
443 $u = &user_get_object_by_name ($user) ;
445 $user_id = $u->getID();
450 $uu = isset($usr_updates[$user]) ? $usr_updates[$user] : 0 ;
451 $ua = isset($usr_adds[$user]) ? $usr_adds[$user] : 0 ;
452 if ($uu > 0 || $ua > 0) {
453 if (!db_query_params ('INSERT INTO stats_cvs_user (month,day,group_id,user_id,commits,adds) VALUES ($1,$2,$3,$4,$5,$6)',
454 array ($month_string,
460 echo "Error while inserting into stats_cvs_user\n" ;
470 function generateSnapshots ($params) {
472 $project = $this->checkParams ($params) ;
477 $group_name = $project->getUnixName() ;
479 $snapshot = forge_get_config('scm_snapshots_path').'/'.$group_name.'-scm-latest.tar.gz';
480 $tarball = forge_get_config('scm_tarballs_path').'/'.$group_name.'-scmroot.tar.gz';
482 if (! $project->usesPlugin ($this->name)) {
486 if (! $project->enableAnonSCM()) {
487 if (is_file($snapshot)) {
490 if (is_file($tarball)) {
496 $toprepo = forge_get_config('repos_path', 'scmsvn') ;
497 $repo = $toprepo . '/' . $project->getUnixName() ;
499 if (!is_dir ($repo) || !is_file ("$repo/format")) {
500 if (is_file($snapshot)) {
503 if (is_file($tarball)) {
509 $tmp = trim (`mktemp -d`) ;
513 $today = date ('Y-m-d') ;
514 $dir = $project->getUnixName ()."-$today" ;
515 system ("mkdir -p $tmp") ;
517 system ("svn ls file://$repo/trunk > /dev/null", $code) ;
519 system ("cd $tmp ; svn export file://$repo/trunk $dir > /dev/null 2>&1") ;
520 system ("tar czCf $tmp $tmp/snapshot.tar.gz $dir") ;
521 chmod ("$tmp/snapshot.tar.gz", 0644) ;
522 copy ("$tmp/snapshot.tar.gz", $snapshot) ;
523 unlink ("$tmp/snapshot.tar.gz") ;
524 system ("rm -rf $tmp/$dir") ;
526 if (is_file($snapshot)) {
531 system ("tar czCf $toprepo $tmp/tarball.tar.gz " . $project->getUnixName()) ;
532 chmod ("$tmp/tarball.tar.gz", 0644) ;
533 copy ("$tmp/tarball.tar.gz", $tarball) ;
534 unlink ("$tmp/tarball.tar.gz") ;
535 system ("rm -rf $tmp") ;
538 function installOrUpdateCmds($project, $unix_group_name, $repos) {
542 $params['unix_group_name'] = $unix_group_name;
543 $group = group_get_object_by_name($unix_group_name);
544 $params['group_id'] = $group->getID();
545 $params['repos'] = $repos;
546 $params['hooks'] = &$hooks;
547 plugin_hook_by_reference('cmd_for_post_commit_hook', $params);
549 foreach ($params['hooks'] as $plugin => $cmd ) {
550 if (getenv('sys_localinc')) {
551 $cmd = 'sys_localinc='.getenv(sys_localinc).' '.$cmd;
553 $contents = @file_get_contents($repos."/hooks/post-commit");
554 if ($project->usesPlugin($plugin)) {
555 if (strstr($contents, "#begin added by $plugin") === false ) {
556 $this->installCmdInHook($repos, $plugin, $cmd);
558 $this->updateCmdInHook($repos, $plugin, $cmd);
560 } elseif (!$project->usesPlugin($plugin) &&
561 (strstr($contents, "#begin added by $plugin") !== false )) {
562 $this->removeCmdInHook($repos, $plugin);
567 function installCmdInHook($repos, $name, $text) {
569 if (file_exists($repos.'/hooks/post-commit')) {
570 $FOut = fopen($repos.'/hooks/post-commit', "a+");
573 $FOut = fopen($repos.'/hooks/post-commit', "w");
574 $Line = '#!/bin/sh'."\n"; // add this line to first line or else the script fails
578 $Line .= "\n#begin added by $name\n$text\n#end added by $name\n";
580 fwrite($FOut, $Line);
582 system("chmod 700 $repos/hooks/post-commit");
587 function updateCmdInHook($repos, $plugin, $text) {
589 $contents = @file_get_contents($repos."/hooks/post-commit");
591 $new = preg_replace("/(#begin added by $plugin\n)(.*)(\n#end added by $plugin)/s", '$1{COMMAND}$3', $contents);
592 $new = str_replace('{COMMAND}', $text, $new);
594 if ($contents !== $new) {
595 $fout = fopen($repos.'/hooks/post-commit', "w");
601 function removeCmdInHook($repos, $plugin) {
603 $contents = @file_get_contents($repos."/hooks/post-commit");
604 $new = preg_replace("/#begin added by $plugin\n.*?\n#end added by $plugin/s", '', $contents);
606 if ($contents !== $new) {
607 if (preg_match("/^#\!\/bin\/sh(\n+)$/s", $new)) {
608 unlink($repos.'/hooks/post-commit');
610 $fout = fopen($repos.'/hooks/post-commit', "w");
618 // End of class, helper functions now
620 function SVNPluginCharData ($parser, $chars) {
621 global $last_tag, $last_user, $last_time, $start_time, $end_time,
622 $time_ok, $user_list;
625 $last_user = ereg_replace ('[^a-z0-9_-]', '',
626 strtolower (trim ($chars))) ;
629 $chars = preg_replace('/T(\d\d:\d\d:\d\d)\.\d+Z?$/', ' ${1}', $chars);
630 $last_time = strtotime($chars);
631 if ($start_time <= $last_time && $last_time < $end_time) {
640 function SVNPluginStartElement($parser, $name, $attrs) {
641 global $last_user, $last_time, $last_tag, $time_ok,
642 $adds, $updates, $usr_adds, $usr_updates;
646 // Make sure we clean up before doing a new log entry
652 if ($attrs['ACTION'] == "M") {
655 $usr_updates[$last_user] = isset($usr_updates[$last_user]) ? ($usr_updates[$last_user]+1) : 1 ;
657 } elseif ($attrs['ACTION'] == "A") {
660 $usr_adds[$last_user] = isset($usr_adds[$last_user]) ? ($usr_adds[$last_user]+1) : 1 ;
668 function SVNPluginEndElement ($parser, $name) {
669 global $time_ok, $last_tag, $commits;
670 if ($name == "LOGENTRY" && $time_ok) {
678 // c-file-style: "bsd"