/* ui-shared.c: common web output functions
 *
 * Copyright (C) 2006 Lars Hjemli
 *
 * Licensed under GNU General Public License v2
 *   (see COPYING for full license text)
 */

#include "cgit.h"
#include "cmd.h"
#include "html.h"

const char cgit_doctype[] =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";

static char *http_date(time_t t)
{
	static char day[][4] =
		{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	static char month[][4] =
		{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
		 "Jul", "Aug", "Sep", "Oct", "Now", "Dec"};
	struct tm *tm = gmtime(&t);
	return fmt("%s, %02d %s %04d %02d:%02d:%02d GMT", day[tm->tm_wday],
		   tm->tm_mday, month[tm->tm_mon], 1900+tm->tm_year,
		   tm->tm_hour, tm->tm_min, tm->tm_sec);
}

void cgit_print_error(char *msg)
{
	html("<div class='error'>");
	html_txt(msg);
	html("</div>\n");
}

char *cgit_httpscheme()
{
	if (ctx.env.https && !strcmp(ctx.env.https, "on"))
		return "https://";
	else
		return "http://";
}

char *cgit_hosturl()
{
	if (ctx.env.http_host)
		return ctx.env.http_host;
	if (!ctx.env.server_name)
		return NULL;
	if (!ctx.env.server_port || atoi(ctx.env.server_port) == 80)
		return ctx.env.server_name;
	return xstrdup(fmt("%s:%s", ctx.env.server_name, ctx.env.server_port));
}

char *cgit_rooturl()
{
	if (ctx.cfg.virtual_root)
		return fmt("%s/", ctx.cfg.virtual_root);
	else
		return ctx.cfg.script_name;
}

char *cgit_repourl(const char *reponame)
{
	if (ctx.cfg.virtual_root) {
		return fmt("%s/%s/", ctx.cfg.virtual_root, reponame);
	} else {
		return fmt("?r=%s", reponame);
	}
}

char *cgit_fileurl(const char *reponame, const char *pagename,
		   const char *filename, const char *query)
{
	char *tmp;
	char *delim;

	if (ctx.cfg.virtual_root) {
		tmp = fmt("%s/%s/%s/%s", ctx.cfg.virtual_root, reponame,
			  pagename, (filename ? filename:""));
		delim = "?";
	} else {
		tmp = fmt("?url=%s/%s/%s", reponame, pagename,
			  (filename ? filename : ""));
		delim = "&";
	}
	if (query)
		tmp = fmt("%s%s%s", tmp, delim, query);
	return tmp;
}

char *cgit_pageurl(const char *reponame, const char *pagename,
		   const char *query)
{
	return cgit_fileurl(reponame,pagename,0,query);
}

const char *cgit_repobasename(const char *reponame)
{
	/* I assume we don't need to store more than one repo basename */
	static char rvbuf[1024];
	int p;
	const char *rv;
	strncpy(rvbuf,reponame,sizeof(rvbuf));
	if(rvbuf[sizeof(rvbuf)-1])
		die("cgit_repobasename: truncated repository name '%s'", reponame);
	p = strlen(rvbuf)-1;
	/* strip trailing slashes */
	while(p && rvbuf[p]=='/') rvbuf[p--]=0;
	/* strip trailing .git */
	if(p>=3 && !strncmp(&rvbuf[p-3],".git",4)) {
		p -= 3; rvbuf[p--] = 0;
	}
	/* strip more trailing slashes if any */
	while( p && rvbuf[p]=='/') rvbuf[p--]=0;
	/* find last slash in the remaining string */
	rv = strrchr(rvbuf,'/');
	if(rv)
		return ++rv;
	return rvbuf;
}

char *cgit_currurl()
{
	if (!ctx.cfg.virtual_root)
		return ctx.cfg.script_name;
	else if (ctx.qry.page)
		return fmt("%s/%s/%s/", ctx.cfg.virtual_root, ctx.qry.repo, ctx.qry.page);
	else if (ctx.qry.repo)
		return fmt("%s/%s/", ctx.cfg.virtual_root, ctx.qry.repo);
	else
		return fmt("%s/", ctx.cfg.virtual_root);
}

static void site_url(char *page, char *search, int ofs)
{
	char *delim = "?";

	if (ctx.cfg.virtual_root) {
		html_attr(ctx.cfg.virtual_root);
		if (ctx.cfg.virtual_root[strlen(ctx.cfg.virtual_root) - 1] != '/')
			html("/");
	} else
		html(ctx.cfg.script_name);

	if (page) {
		htmlf("?p=%s", page);
		delim = "&";
	}
	if (search) {
		html(delim);
		html("q=");
		html_attr(search);
		delim = "&";
	}
	if (ofs) {
		html(delim);
		htmlf("ofs=%d", ofs);
	}
}

static void site_link(char *page, char *name, char *title, char *class,
		      char *search, int ofs)
{
	html("<a");
	if (title) {
		html(" title='");
		html_attr(title);
		html("'");
	}
	if (class) {
		html(" class='");
		html_attr(class);
		html("'");
	}
	html(" href='");
	site_url(page, search, ofs);
	html("'>");
	html_txt(name);
	html("</a>");
}

void cgit_index_link(char *name, char *title, char *class, char *pattern,
<style>pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */</style><div class="highlight"><pre><span></span><span class="ch">#!/bin/sh</span>

.<span class="w"> </span>./setup.sh


test_url<span class="o">()</span>
<span class="o">{</span>
<span class="w">	</span><span class="nv">tidy_opt</span><span class="o">=</span><span class="s2">&quot;-eq&quot;</span>
<span class="w">	</span><span class="nb">test</span><span class="w"> </span>-z<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$NO_TIDY_WARNINGS</span><span class="s2">&quot;</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="nv">tidy_opt</span><span class="o">+=</span><span class="s2">&quot; --show-warnings no&quot;</span>
<span class="w">	</span>cgit_url<span class="w"> </span><span class="s2">&quot;</span><span class="nv">$1</span><span class="s2">&quot;</span><span class="w"> </span>&gt;trash/tidy-<span class="nv">$test_count</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="k">return</span>
<span class="w">	</span>sed<span class="w"> </span>-ie<span class="w"> </span><span class="s2">&quot;1,4d&quot;</span><span class="w"> </span>trash/tidy-<span class="nv">$test_count</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="k">return</span>
<span class="w">	</span>tidy<span class="w"> </span><span class="nv">$tidy_opt</span><span class="w"> </span>trash/tidy-<span class="nv">$test_count</span>
<span class="w">	</span><span class="nv">rc</span><span class="o">=</span><span class="nv">$?</span>

<span class="w">	</span><span class="c1"># tidy returns with exitcode 1 on warnings, 2 on error</span>
<span class="w">	</span><span class="k">if</span><span class="w"> </span><span class="nb">test</span><span class="w"> </span><span class="nv">$rc</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2</span>
<span class="w">	</span><span class="k">then</span>
<span class="w">		</span><span class="nb">false</span>
<span class="w">	</span><span class="k">else</span>
<span class="w">		</span>:
<span class="w">	</span><span class="k">fi</span>
<span class="o">}</span>

prepare_tests<span class="w"> </span><span class="s1">&#39;Validate html with tidy&#39;</span>

run_test<span class="w"> </span><span class="s1">&#39;index page&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;&quot;&#39;</span>
run_test<span class="w"> </span><span class="s1">&#39;foo&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;foo&quot;&#39;</span>
run_test<span class="w"> </span><span class="s1">&#39;foo/log&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;foo/log&quot;&#39;</span>
run_test<span class="w"> </span><span class="s1">&#39;foo/tree&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;foo/tree&quot;&#39;</span>
run_test<span class="w"> </span><span class="s1">&#39;foo/tree/file-1&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;foo/tree/file-1&quot;&#39;</span>
run_test<span class="w"> </span><span class="s1">&#39;foo/commit&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;foo/commit&quot;&#39;</span>
run_test<span class="w"> </span><span class="s1">&#39;foo/diff&#39;</span><span class="w"> </span><span class="s1">&#39;test_url &quot;foo/diff&quot;&#39;</span>

tests_done
</pre></div>
</code></pre></td></tr></table>
</div> <!-- class=content -->
<div class='footer'>generated by <a href='https://git.zx2c4.com/cgit/about/'>cgit v1.2.3-54-g00ecf</a> (<a href='https://git-scm.com/'>git 2.39.0</a>) at 2025-03-20 06:44:38 +0000</div>
</div> <!-- id=cgit -->
</body>
</html>
bj;
	char buf[256], *url;
	unsigned char fileid[20];
	int *header = (int *)cb_data;

	if (prefixcmp(refname, "refs/archives"))
		return 0;
	strncpy(buf, refname+14, sizeof(buf));
	obj = parse_object(sha1);
	if (!obj)
		return 1;
	if (obj->type == OBJ_TAG) {
		tag = lookup_tag(sha1);
		if (!tag || parse_tag(tag) || !(info = cgit_parse_tag(tag)))
			return 0;
		hashcpy(fileid, tag->tagged->sha1);
	} else if (obj->type != OBJ_BLOB) {
		return 0;
	} else {
		hashcpy(fileid, sha1);
	}
	if (!*header) {
		html("<h1>download</h1>\n");
		*header = 1;
	}
	url = cgit_pageurl(ctx.qry.repo, "blob",
			   fmt("id=%s&amp;path=%s", sha1_to_hex(fileid),
			       buf));
	html_link_open(url, NULL, "menu");
	html_txt(strlpart(buf, 20));
	html_link_close();
	return 0;
}

void cgit_add_hidden_formfields(int incl_head, int incl_search, char *page)
{
	char *url;

	if (!ctx.cfg.virtual_root) {
		url = fmt("%s/%s", ctx.qry.repo, page);
		if (ctx.qry.path)
			url = fmt("%s/%s", url, ctx.qry.path);
		html_hidden("url", url);
	}

	if (incl_head && ctx.qry.head && ctx.repo->defbranch &&
	    strcmp(ctx.qry.head, ctx.repo->defbranch))
		html_hidden("h", ctx.qry.head);

	if (ctx.qry.sha1)
		html_hidden("id", ctx.qry.sha1);
	if (ctx.qry.sha2)
		html_hidden("id2", ctx.qry.sha2);
	if (ctx.qry.showmsg)
		html_hidden("showmsg", "1");

	if (incl_search) {
		if (ctx.qry.grep)
			html_hidden("qt", ctx.qry.grep);
		if (ctx.qry.search)
			html_hidden("q", ctx.qry.search);
	}
}

const char *fallback_cmd = "repolist";

char *hc(struct cgit_cmd *cmd, const char *page)
{
	return (strcmp(cmd ? cmd->name : fallback_cmd, page) ? NULL : "active");
}

static void print_header(struct cgit_context *ctx)
{
	html("<table id='header'>\n");
	html("<tr>\n");

	if (ctx->cfg.logo && ctx->cfg.logo[0] != 0) {
		html("<td class='logo' rowspan='2'><a href='");
		if (ctx->cfg.logo_link)
			html_attr(ctx->cfg.logo_link);
		else
			html_attr(cgit_rooturl());
		html("'><img src='");
		html_attr(ctx->cfg.logo);
		html("' alt='cgit logo'/></a></td>\n");
	}

	html("<td class='main'>");
	if (ctx->repo) {
		cgit_index_link("index", NULL, NULL, NULL, 0);
		html(" : ");
		cgit_summary_link(ctx->repo->name, ctx->repo->name, NULL, NULL);
		html("</td><td class='form'>");
		html("<form method='get' action=''>\n");
		cgit_add_hidden_formfields(0, 1, ctx->qry.page);
		html("<select name='h' onchange='this.form.submit();'>\n");
		for_each_branch_ref(print_branch_option, ctx->qry.head);
		html("</select> ");
		html("<input type='submit' name='' value='switch'/>");
		html("</form>");
	} else
		html_txt(ctx->cfg.root_title);
	html("</td></tr>\n");

	html("<tr><td class='sub'>");
	if (ctx->repo) {
		html_txt(ctx->repo->desc);
		html("</td><td class='sub right'>");
		html_txt(ctx->repo->owner);
	} else {
		if (ctx->cfg.root_desc)
			html_txt(ctx->cfg.root_desc);
		else if (ctx->cfg.index_info)
			html_include(ctx->cfg.index_info);
	}
	html("</td></tr></table>\n");
}

void cgit_print_pageheader(struct cgit_context *ctx)
{
	struct cgit_cmd *cmd = cgit_get_cmd(ctx);

	if (!cmd && ctx->repo)
		fallback_cmd = "summary";

	html("<div id='cgit'>");
	if (!ctx->cfg.noheader)
		print_header(ctx);

	html("<table class='tabs'><tr><td>\n");
	if (ctx->repo) {
		cgit_summary_link("summary", NULL, hc(cmd, "summary"),
				  ctx->qry.head);
		cgit_refs_link("refs", NULL, hc(cmd, "refs"), ctx->qry.head,
			       ctx->qry.sha1, NULL);
		cgit_log_link("log", NULL, hc(cmd, "log"), ctx->qry.head,
			      NULL, NULL, 0, NULL, NULL, ctx->qry.showmsg);
		cgit_tree_link("tree", NULL, hc(cmd, "tree"), ctx->qry.head,
			       ctx->qry.sha1, NULL);
		cgit_commit_link("commit", NULL, hc(cmd, "commit"),
				 ctx->qry.head, ctx->qry.sha1);
		cgit_diff_link("diff", NULL, hc(cmd, "diff"), ctx->qry.head,
			       ctx->qry.sha1, ctx->qry.sha2, NULL);
		if (ctx->repo->max_stats)
			cgit_stats_link("stats", NULL, hc(cmd, "stats"),
					ctx->qry.head, NULL);
		if (ctx->repo->readme)
			reporevlink("about", "about", NULL,
				    hc(cmd, "about"), ctx->qry.head, NULL,
				    NULL);
		html("</td><td class='form'>");
		html("<form class='right' method='get' action='");
		if (ctx->cfg.virtual_root)
			html_url_path(cgit_fileurl(ctx->qry.repo, "log",
						   ctx->qry.path, NULL));
		html("'>\n");
		cgit_add_hidden_formfields(1, 0, "log");
		html("<select name='qt'>\n");
		html_option("grep", "log msg", ctx->qry.grep);
		html_option("author", "author", ctx->qry.grep);
		html_option("committer", "committer", ctx->qry.grep);
		html("</select>\n");
		html("<input class='txt' type='text' size='10' name='q' value='");
		html_attr(ctx->qry.search);
		html("'/>\n");
		html("<input type='submit' value='search'/>\n");
		html("</form>\n");
	} else {
		site_link(NULL, "index", NULL, hc(cmd, "repolist"), NULL, 0);
		if (ctx->cfg.root_readme)
			site_link("about", "about", NULL, hc(cmd, "about"),
				  NULL, 0);
		html("</td><td class='form'>");
		html("<form method='get' action='");
		html_attr(cgit_rooturl());
		html("'>\n");
		html("<input type='text' name='q' size='10' value='");
		html_attr(ctx->qry.search);
		html("'/>\n");
		html("<input type='submit' value='search'/>\n");
		html("</form>");
	}
	html("</td></tr></table>\n");
	html("<div class='content'>");
}

void cgit_print_filemode(unsigned short mode)
{
	if (S_ISDIR(mode))
		html("d");
	else if (S_ISLNK(mode))
		html("l");
	else if (S_ISGITLINK(mode))
		html("m");
	else
		html("-");
	html_fileperm(mode >> 6);
	html_fileperm(mode >> 3);
	html_fileperm(mode);
}

void cgit_print_snapshot_links(const char *repo, const char *head,
			       const char *hex, int snapshots)
{
	const struct cgit_snapshot_format* f;
    	char *filename;

	for (f = cgit_snapshot_formats; f->suffix; f++) {
		if (!(snapshots & f->bit))
			continue;
		filename = fmt("%s-%s%s", cgit_repobasename(repo), hex,
			       f->suffix);
		cgit_snapshot_link(filename, NULL, NULL, NULL, NULL, filename);
		html("<br/>");
	}
}