Add Troubleshooting section to README.
[viewgit.git] / inc / functions.php
blob9cb3f8f29cae3f4f654b3c107442fb19df018291
1 <?php
2 /** @file
3 * Functions used by ViewGit.
4 */
6 function debug($msg)
8 global $conf;
10 if ($conf['debug']) {
11 file_put_contents('php://stderr', strftime('%H:%M:%S') ." viewgit: $_SERVER[REMOTE_ADDR]:$_SERVER[REMOTE_PORT] $msg\n", FILE_APPEND);
15 function fix_encoding($in_str)
17 if (function_exists("mb_detect_encoding") && function_exists("mb_check_encoding")) {
18 $cur_encoding = mb_detect_encoding($in_str) ;
19 if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")) {
20 return $in_str;
21 } else {
22 return utf8_encode($in_str);
24 } else {
25 return utf8_encode($in_str);
29 /**
30 * Format author's name & wrap it to links etc.
32 function format_author($author)
34 global $page;
36 if (isset($page['project'])) {
37 // FIXME 'h' - use only if available
38 return '<a href="'. makelink(array('a' => 'search', 'p' => $page['project'], 'h' => 'HEAD', 'st' => 'author', 's' => $author)) .'">'. htmlentities_wrapper($author) .'</a>';
39 } else {
40 return htmlentities_wrapper($author);
44 /**
45 * Formats "git diff" output into xhtml.
46 * @return array(array of filenames, xhtml)
48 function format_diff($text)
50 $files = array();
52 // match every "^diff --git a/<path> b/<path>$" line
53 foreach (explode("\n", $text) as $line) {
54 if (preg_match('#^diff --git a/(.*) b/(.*)$#', $line, $matches) > 0) {
55 $files[$matches[1]] = urlencode($matches[1]);
59 $text = htmlentities_wrapper($text);
61 $text = preg_replace(
62 array(
63 '/^(\+.*)$/m',
64 '/^(-.*)$/m',
65 '/^(@.*)$/m',
66 '/^([^d\+-@].*)$/m',
68 array(
69 '<span class="add">$1</span>',
70 '<span class="del">$1</span>',
71 '<span class="pos">$1</span>',
72 '<span class="etc">$1</span>',
74 $text);
75 $text = preg_replace_callback('#^diff --git a/(.*) b/(.*)$#m',
76 create_function(
77 '$m',
78 'return "<span class=\"diffline\"><a name=\"". urlencode($m[1]) ."\">diff --git a/$m[1] b/$m[2]</a></span>";'
80 $text);
82 return array($files, $text);
85 /**
86 * Get project information from config and git, name/description and HEAD
87 * commit info are returned in an array.
89 function get_project_info($name)
91 global $conf;
93 $info = $conf['projects'][$name];
94 $info['name'] = $name;
96 // If description is not set, read it from the repository's description
97 if (!isset($info['description'])) {
98 $info['description'] = @file_get_contents($info['repo'] .'/description');
101 $headinfo = git_get_commit_info($name, 'HEAD');
102 $info['head_stamp'] = $headinfo['author_utcstamp'];
103 $info['head_datetime'] = strftime($conf['datetime'], $headinfo['author_utcstamp']);
104 $info['head_hash'] = $headinfo['h'];
105 $info['head_tree'] = $headinfo['tree'];
106 $info['message'] = $headinfo['message'];
108 return $info;
111 function git_describe($project, $commit)
113 $output = run_git($project, "describe --always ". escapeshellarg($commit));
114 return $output[0];
118 * Get diff between given revisions as text.
120 function git_diff($project, $from, $to)
122 return join("\n", run_git($project, "diff \"$from..$to\""));
125 function git_diffstat($project, $commit, $commit_base = null)
127 if (is_null($commit_base)) {
128 $commit_base = "$commit^";
130 return join("\n", run_git($project, "diff --stat $commit_base..$commit"));
134 * Get array of changed paths for a commit.
136 function git_get_changed_paths($project, $hash = 'HEAD')
138 $result = array();
139 $affected_files = run_git($project, "show --pretty=\"format:\" --name-only $hash");
140 foreach ($affected_files as $file ) {
141 // The format above contains a blank line; Skip it.
142 if ($file == '') {
143 continue;
146 $output = run_git($project, "ls-tree $hash $file");
147 foreach ($output as $line) {
148 $parts = preg_split('/\s+/', $line, 4);
149 $result[] = array('name' => $parts[3], 'hash' => $parts[2]);
152 return $result;
156 * Get details of a commit: tree, parents, author/committer (name, mail, date), message
158 function git_get_commit_info($project, $hash = 'HEAD', $path = null)
160 global $conf;
162 $info = array();
163 $info['h_name'] = $hash;
164 $info['message_full'] = '';
165 $info['parents'] = array();
167 $extra = '';
168 if (isset($path)) {
169 $extra = '-- '. escapeshellarg($path);
172 $output = run_git($project, "rev-list --header --max-count=1 $hash $extra");
173 // tree <h>
174 // parent <h>
175 // author <name> "<"<mail>">" <stamp> <timezone>
176 // committer
177 // <empty>
178 // <message>
179 $pattern = '/^(author|committer) ([^<]+) <([^>]*)> ([0-9]+) (.*)$/';
180 foreach ($output as $line) {
181 if (substr($line, 0, 4) === 'tree') {
182 $info['tree'] = substr($line, 5);
184 // may be repeated multiple times for merge/octopus
185 elseif (substr($line, 0, 6) === 'parent') {
186 $info['parents'][] = substr($line, 7);
188 elseif (preg_match($pattern, $line, $matches) > 0) {
189 $info[$matches[1] .'_name'] = $matches[2];
190 $info[$matches[1] .'_mail'] = $matches[3];
191 $info[$matches[1] .'_stamp'] = $matches[4] + ((intval($matches[5]) / 100.0) * 3600);
192 $info[$matches[1] .'_timezone'] = $matches[5];
193 $info[$matches[1] .'_utcstamp'] = $matches[4];
195 if (isset($conf['mail_filter'])) {
196 $info[$matches[1] .'_mail'] = $conf['mail_filter']($info[$matches[1] .'_mail']);
199 // Lines starting with four spaces and empty lines after first such line are part of commit message
200 elseif (substr($line, 0, 4) === ' ' || (strlen($line) == 0 && isset($info['message']))) {
201 $info['message_full'] .= substr($line, 4) ."\n";
202 if (!isset($info['message'])) {
203 $info['message'] = substr($line, 4, $conf['commit_message_maxlen']);
204 $info['message_firstline'] = substr($line, 4);
207 elseif (preg_match('/^[0-9a-f]{40}$/', $line) > 0) {
208 $info['h'] = $line;
212 // This is a workaround for the unlikely situation where a commit does
213 // not have a message. Such a commit can be created with the following
214 // command:
215 // git commit --allow-empty -m '' --cleanup=verbatim
216 if (!array_key_exists('message', $info)) {
217 $info['message'] = '(no message)';
218 $info['message_firstline'] = '(no message)';
221 $info['author_datetime'] = strftime($conf['datetime_full'], $info['author_utcstamp']);
222 $info['author_datetime_local'] = strftime($conf['datetime_full'], $info['author_stamp']) .' '. $info['author_timezone'];
223 $info['committer_datetime'] = strftime($conf['datetime_full'], $info['committer_utcstamp']);
224 $info['committer_datetime_local'] = strftime($conf['datetime_full'], $info['committer_stamp']) .' '. $info['committer_timezone'];
226 return $info;
230 * Get list of heads (branches) for a project.
232 function git_get_heads($project)
234 $heads = array();
236 $output = run_git($project, 'show-ref --heads');
237 foreach ($output as $line) {
238 $fullname = substr($line, 41);
239 $tmp = explode('/', $fullname);
240 $name = array_pop($tmp);
241 $pre = array_pop($tmp);
242 if ($pre != 'heads')
244 $name = $pre . '/' . $name;
246 $heads[] = array('h' => substr($line, 0, 40), 'fullname' => "$fullname", 'name' => "$name");
249 return $heads;
253 * Get array containing path information for parts, starting from root_hash.
255 * @param root_hash commit/tree hash for the root tree
256 * @param path path
258 function git_get_path_info($project, $root_hash, $path)
260 if (strlen($path) > 0) {
261 $parts = explode('/', $path);
262 } else {
263 $parts = array();
266 $pathinfo = array();
268 $tid = $root_hash;
269 $pathinfo = array();
270 foreach ($parts as $p) {
271 $entry = git_ls_tree_part($project, $tid, $p);
272 if (is_null($entry)) {
273 die('Invalid path info.');
275 $pathinfo[] = $entry;
276 $tid = $entry['hash'];
279 return $pathinfo;
283 * Get revision list starting from given commit.
284 * @param skip how many hashes to skip from the beginning
285 * @param max_count number of commit hashes to return, or all if not given
286 * @param start revision to start from, or HEAD if not given
288 function git_get_rev_list($project, $skip = 0, $max_count = null, $start = 'HEAD')
290 $cmd = "rev-list ";
291 if ($skip != 0) {
292 $cmd .= "--skip=$skip ";
294 if (!is_null($max_count)) {
295 $cmd .= "--max-count=$max_count ";
297 $cmd .= $start;
299 return run_git($project, $cmd);
303 * Get list of tags for a project.
305 function git_get_tags($project)
307 $tags = array();
309 $output = run_git($project, 'show-ref --tags');
310 foreach ($output as $line) {
311 $fullname = substr($line, 41);
312 $tmp = explode('/', $fullname);
313 $name = array_pop($tmp);
314 $tags[] = array('h' => substr($line, 0, 40), 'fullname' => $fullname, 'name' => $name);
316 return $tags;
320 * Get information about objects in a tree.
321 * @param tree tree or commit hash
322 * @return list of arrays containing name, mode, type, hash
324 function git_ls_tree($project, $tree)
326 $entries = array();
327 $output = run_git($project, "ls-tree $tree");
328 // 100644 blob 493b7fc4296d64af45dac64bceac2d9a96c958c1 .gitignore
329 // 040000 tree 715c78b1011dc58106da2a1af2fe0aa4c829542f doc
330 foreach ($output as $line) {
331 $parts = preg_split('/\s+/', $line, 4);
332 $entries[] = array('name' => $parts[3], 'mode' => $parts[0], 'type' => $parts[1], 'hash' => $parts[2]);
335 return $entries;
339 * Get information about the given object in a tree, or null if not in the tree.
341 function git_ls_tree_part($project, $tree, $name)
343 $entries = git_ls_tree($project, $tree);
344 foreach ($entries as $entry) {
345 if ($entry['name'] === $name) {
346 return $entry;
349 return null;
353 * Get the ref list as dict: hash -> list of names.
354 * @param tags whether to show tags
355 * @param heads whether to show heads
356 * @param remotes whether to show remote heads, currently implies tags and heads too.
358 function git_ref_list($project, $tags = true, $heads = true, $remotes = true)
360 $cmd = "show-ref --dereference";
361 if (!$remotes) {
362 if ($tags) { $cmd .= " --tags"; }
363 if ($heads) { $cmd .= " --heads"; }
366 $result = array();
367 $output = run_git($project, $cmd);
368 foreach ($output as $line) {
369 // <hash> <ref>
370 $parts = explode(' ', $line, 2);
371 $name = str_replace(array('refs/', '^{}'), array('', ''), $parts[1]);
372 $result[$parts[0]][] = $name;
374 return $result;
378 * Find commits based on search type and string.
380 function git_search_commits($project, $branch, $type, $string)
382 // git log -sFOO
383 if ($type == 'change') {
384 $cmd = 'log -S'. escapeshellarg($string);
386 elseif ($type == 'commit') {
387 $cmd = 'log -i --grep='. escapeshellarg($string);
389 elseif ($type == 'author') {
390 $cmd = 'log -i --author='. escapeshellarg($string);
392 elseif ($type == 'committer') {
393 $cmd = 'log -i --committer='. escapeshellarg($string);
395 else {
396 die('Unsupported type');
398 $cmd .= ' '. $branch;
399 $lines = run_git($project, $cmd);
401 $result = array();
402 foreach ($lines as $line) {
403 if (preg_match('/^commit (.*?)$/', $line, $matches)) {
404 $result[] = $matches[1];
407 return $result;
411 * Get shortlog entries for the given project.
413 function handle_shortlog($project, $hash = 'HEAD', $page = 0)
415 global $conf;
417 $refs_by_hash = git_ref_list($project, true, true, $conf['shortlog_remote_labels']);
419 $result = array();
420 $revs = git_get_rev_list($project, $page * $conf['summary_shortlog'], $conf['summary_shortlog'], $hash);
421 foreach ($revs as $rev) {
422 $info = git_get_commit_info($project, $rev);
423 $refs = array();
424 if (in_array($rev, array_keys($refs_by_hash))) {
425 $refs = $refs_by_hash[$rev];
427 $result[] = array(
428 'author' => $info['author_name'],
429 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
430 'message' => $info['message'],
431 'commit_id' => $rev,
432 'tree' => $info['tree'],
433 'refs' => $refs,
436 #print_r($result);
437 #die();
439 return $result;
443 * Fetch tags data, newest first.
445 * @param limit maximum number of tags to return
447 function handle_tags($project, $limit = 0)
449 global $conf;
451 $tags = git_get_tags($project);
452 $result = array();
453 foreach ($tags as $tag) {
454 $info = git_get_commit_info($project, $tag['h']);
455 $result[] = array(
456 'stamp' => $info['author_utcstamp'],
457 'date' => strftime($conf['datetime'], $info['author_utcstamp']),
458 'h' => $tag['h'],
459 'fullname' => $tag['fullname'],
460 'name' => $tag['name'],
464 // sort tags newest first
465 // aka. two more reasons to hate PHP (figuring those out is your homework:)
466 usort($result, create_function(
467 '$x, $y',
468 '$a = $x["stamp"]; $b = $y["stamp"]; return ($a == $b ? 0 : ($a > $b ? -1 : 1));'
471 // TODO optimize this some way, currently all tags are fetched when only a
472 // few are shown. The problem is that without fetching the commit info
473 // above, we can't sort using dates, only by tag name...
474 if ($limit > 0) {
475 $result = array_splice($result, 0, $limit);
478 return $result;
481 function htmlentities_wrapper($text)
483 return htmlentities(@iconv('UTF-8', 'UTF-8//IGNORE', $text), ENT_NOQUOTES, 'UTF-8');
486 function xmlentities_wrapper($text)
488 return str_replace(array('&', '<'), array('&#x26;', '&#x3C;'), @iconv('UTF-8', 'UTF-8//IGNORE', $text));
492 * Return a URL that contains the given parameters.
494 function makelink($dict)
496 $params = array();
497 foreach ($dict as $k => $v) {
498 $params[] = rawurlencode($k) .'='. str_replace('%2F', '/', rawurlencode($v));
500 if (count($params) > 0) {
501 return '?'. htmlentities_wrapper(join('&', $params));
503 return '';
507 * Obfuscate the e-mail address.
509 function obfuscate_mail($mail)
511 return str_replace(array('@', '.'), array(' at ', ' dot '), $mail);
515 * Used to format RSS item title and description.
517 * @param info commit info from git_get_commit_info()
519 function rss_item_format($format, $info)
521 return preg_replace(array(
522 '/{AUTHOR}/',
523 '/{AUTHOR_MAIL}/',
524 '/{SHORTLOG}/',
525 '/{LOG}/',
526 '/{COMMITTER}/',
527 '/{COMMITTER_MAIL}/',
528 '/{DIFFSTAT}/',
529 ), array(
530 htmlentities_wrapper($info['author_name']),
531 htmlentities_wrapper($info['author_mail']),
532 htmlentities_wrapper($info['message_firstline']),
533 htmlentities_wrapper($info['message_full']),
534 htmlentities_wrapper($info['committer_name']),
535 htmlentities_wrapper($info['committer_mail']),
536 htmlentities_wrapper(isset($info['diffstat']) ? $info['diffstat'] : ''),
537 ), $format);
540 function rss_pubdate($secs)
542 return gmdate('D, d M Y H:i:s O', $secs);
546 * Executes a git command in the project repo.
547 * @return array of output lines
549 function run_git($project, $command)
551 global $conf;
553 $output = array();
554 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
555 $ret = 0;
556 exec($cmd, $output, $ret);
557 if ($conf['debug_command_trace']) {
558 static $count = 0;
559 $count++;
560 trigger_error("[$count]\$ $cmd [exit $ret]");
562 //if ($ret != 0) { die('FATAL: exec() for git failed, is the path properly configured?'); }
563 return $output;
567 * Executes a git command in the project repo, sending output directly to the
568 * client.
570 function run_git_passthru($project, $command)
572 global $conf;
574 $cmd = $conf['git'] ." --git-dir=". escapeshellarg($conf['projects'][$project]['repo']) ." $command";
575 $result = 0;
576 passthru($cmd, $result);
577 return $result;
580 function tpl_extlink($link)
582 echo "<a href=\"$link\" class=\"external\">&#8599;</a>";
586 * Makes sure the given project is valid. If it's not, this function will
587 * die().
588 * @return the project
590 function validate_project($project)
592 global $conf;
594 if (!in_array($project, array_keys($conf['projects']))) {
595 die('Invalid project');
597 return $project;
601 * Makes sure the given hash is valid. If it's not, this function will die().
602 * @return the hash
604 function validate_hash($hash)
606 if (!preg_match('/^[0-9a-z]{40}$/', $hash) && !preg_match('!^refs/(heads|tags)/[-_.0-9a-zA-Z/]+$!', $hash) && $hash !== 'HEAD') {
607 die('Invalid hash');
610 return $hash;
614 * Custom error handler for ViewGit. The errors are pushed to $page['notices']
615 * and displayed by templates/header.php.
617 function vg_error_handler($errno, $errstr, $errfile, $errline)
619 global $page;
621 $mask = ini_get('error_reporting');
623 $class = 'error';
625 // If mask for this error is not enabled, return silently
626 if (!($errno & $mask)) {
627 return true;
630 // Remove any preceding path until viewgit's directory
631 $file = $errfile;
632 $file = strstr($file, 'viewgit/');
634 $message = "$file:$errline $errstr [$errno]";
636 switch ($errno) {
637 case E_ERROR:
638 $class = 'error';
639 break;
640 case E_WARNING:
641 $class = 'warning';
642 break;
643 case E_NOTICE:
644 case E_STRICT:
645 default:
646 $class = 'info';
647 break;
650 $page['notices'][] = array(
651 'message' => $message,
652 'class' => $class,
655 return true;