You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

html.go 30 kB

Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
5 years ago
Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package markup
  5. import (
  6. "bytes"
  7. "fmt"
  8. "net/url"
  9. "path"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/emoji"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/markup/common"
  18. "code.gitea.io/gitea/modules/references"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. "github.com/unknwon/com"
  22. "golang.org/x/net/html"
  23. "golang.org/x/net/html/atom"
  24. "mvdan.cc/xurls/v2"
  25. )
  26. // Issue name styles
  27. const (
  28. IssueNameStyleNumeric = "numeric"
  29. IssueNameStyleAlphanumeric = "alphanumeric"
  30. )
  31. var (
  32. // NOTE: All below regex matching do not perform any extra validation.
  33. // Thus a link is produced even if the linked entity does not exist.
  34. // While fast, this is also incorrect and lead to false positives.
  35. // TODO: fix invalid linking issue
  36. // sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  37. // Although SHA1 hashes are 40 chars long, the regex matches the hash from 7 to 40 chars in length
  38. // so that abbreviated hash links can be used as well. This matches git and github useability.
  39. sha1CurrentPattern = regexp.MustCompile(`(?:\s|^|\(|\[)([0-9a-f]{7,40})(?:\s|$|\)|\]|\.(\s|$))`)
  40. // shortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  41. shortLinkPattern = regexp.MustCompile(`\[\[(.*?)\]\](\w*)`)
  42. // anySHA1Pattern allows to split url containing SHA into parts
  43. anySHA1Pattern = regexp.MustCompile(`https?://(?:\S+/){4}([0-9a-f]{40})(/[^#\s]+)?(#\S+)?`)
  44. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  45. // While this email regex is definitely not perfect and I'm sure you can come up
  46. // with edge cases, it is still accepted by the CommonMark specification, as
  47. // well as the HTML5 spec:
  48. // http://spec.commonmark.org/0.28/#email-address
  49. // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
  50. emailRegex = regexp.MustCompile("(?:\\s|^|\\(|\\[)([a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9]{2,}(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+)(?:\\s|$|\\)|\\]|\\.(\\s|$))")
  51. // blackfriday extensions create IDs like fn:user-content-footnote
  52. blackfridayExtRegex = regexp.MustCompile(`[^:]*:user-content-`)
  53. // EmojiShortCodeRegex find emoji by alias like :smile:
  54. EmojiShortCodeRegex = regexp.MustCompile(`\:[\w\+\-]+\:{1}`)
  55. // find emoji literal: search all emoji hex range as many times as they appear as
  56. // some emojis (skin color etc..) are just two or more chained together
  57. emojiRegex = regexp.MustCompile(`[\x{1F000}-\x{1FFFF}|\x{2000}-\x{32ff}|\x{fe4e5}-\x{fe4ee}|\x{200D}|\x{FE0F}|\x{e0000}-\x{e007f}]+`)
  58. )
  59. // CSS class for action keywords (e.g. "closes: #1")
  60. const keywordClass = "issue-keyword"
  61. // regexp for full links to issues/pulls
  62. var issueFullPattern *regexp.Regexp
  63. // IsLink reports whether link fits valid format.
  64. func IsLink(link []byte) bool {
  65. return isLink(link)
  66. }
  67. // isLink reports whether link fits valid format.
  68. func isLink(link []byte) bool {
  69. return validLinksPattern.Match(link)
  70. }
  71. func isLinkStr(link string) bool {
  72. return validLinksPattern.MatchString(link)
  73. }
  74. func getIssueFullPattern() *regexp.Regexp {
  75. if issueFullPattern == nil {
  76. appURL := setting.AppURL
  77. if len(appURL) > 0 && appURL[len(appURL)-1] != '/' {
  78. appURL += "/"
  79. }
  80. issueFullPattern = regexp.MustCompile(appURL +
  81. `\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
  82. }
  83. return issueFullPattern
  84. }
  85. // CustomLinkURLSchemes allows for additional schemes to be detected when parsing links within text
  86. func CustomLinkURLSchemes(schemes []string) {
  87. schemes = append(schemes, "http", "https")
  88. withAuth := make([]string, 0, len(schemes))
  89. validScheme := regexp.MustCompile(`^[a-z]+$`)
  90. for _, s := range schemes {
  91. if !validScheme.MatchString(s) {
  92. continue
  93. }
  94. without := false
  95. for _, sna := range xurls.SchemesNoAuthority {
  96. if s == sna {
  97. without = true
  98. break
  99. }
  100. }
  101. if without {
  102. s += ":"
  103. } else {
  104. s += "://"
  105. }
  106. withAuth = append(withAuth, s)
  107. }
  108. common.LinkRegex, _ = xurls.StrictMatchingScheme(strings.Join(withAuth, "|"))
  109. }
  110. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  111. func IsSameDomain(s string) bool {
  112. if strings.HasPrefix(s, "/") {
  113. return true
  114. }
  115. if uapp, err := url.Parse(setting.AppURL); err == nil {
  116. if u, err := url.Parse(s); err == nil {
  117. return u.Host == uapp.Host
  118. }
  119. return false
  120. }
  121. return false
  122. }
  123. type postProcessError struct {
  124. context string
  125. err error
  126. }
  127. func (p *postProcessError) Error() string {
  128. return "PostProcess: " + p.context + ", " + p.err.Error()
  129. }
  130. type processor func(ctx *postProcessCtx, node *html.Node)
  131. var defaultProcessors = []processor{
  132. fullIssuePatternProcessor,
  133. fullSha1PatternProcessor,
  134. shortLinkProcessor,
  135. linkProcessor,
  136. mentionProcessor,
  137. issueIndexPatternProcessor,
  138. sha1CurrentPatternProcessor,
  139. emailAddressProcessor,
  140. emojiProcessor,
  141. emojiShortCodeProcessor,
  142. }
  143. type postProcessCtx struct {
  144. metas map[string]string
  145. urlPrefix string
  146. isWikiMarkdown bool
  147. // processors used by this context.
  148. procs []processor
  149. }
  150. // PostProcess does the final required transformations to the passed raw HTML
  151. // data, and ensures its validity. Transformations include: replacing links and
  152. // emails with HTML links, parsing shortlinks in the format of [[Link]], like
  153. // MediaWiki, linking issues in the format #ID, and mentions in the format
  154. // @user, and others.
  155. func PostProcess(
  156. rawHTML []byte,
  157. urlPrefix string,
  158. metas map[string]string,
  159. isWikiMarkdown bool,
  160. ) ([]byte, error) {
  161. // create the context from the parameters
  162. ctx := &postProcessCtx{
  163. metas: metas,
  164. urlPrefix: urlPrefix,
  165. isWikiMarkdown: isWikiMarkdown,
  166. procs: defaultProcessors,
  167. }
  168. return ctx.postProcess(rawHTML)
  169. }
  170. var commitMessageProcessors = []processor{
  171. fullIssuePatternProcessor,
  172. fullSha1PatternProcessor,
  173. linkProcessor,
  174. mentionProcessor,
  175. issueIndexPatternProcessor,
  176. sha1CurrentPatternProcessor,
  177. emailAddressProcessor,
  178. emojiProcessor,
  179. emojiShortCodeProcessor,
  180. }
  181. // RenderCommitMessage will use the same logic as PostProcess, but will disable
  182. // the shortLinkProcessor and will add a defaultLinkProcessor if defaultLink is
  183. // set, which changes every text node into a link to the passed default link.
  184. func RenderCommitMessage(
  185. rawHTML []byte,
  186. urlPrefix, defaultLink string,
  187. metas map[string]string,
  188. ) ([]byte, error) {
  189. ctx := &postProcessCtx{
  190. metas: metas,
  191. urlPrefix: urlPrefix,
  192. procs: commitMessageProcessors,
  193. }
  194. if defaultLink != "" {
  195. // we don't have to fear data races, because being
  196. // commitMessageProcessors of fixed len and cap, every time we append
  197. // something to it the slice is realloc+copied, so append always
  198. // generates the slice ex-novo.
  199. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  200. }
  201. return ctx.postProcess(rawHTML)
  202. }
  203. var commitMessageSubjectProcessors = []processor{
  204. fullIssuePatternProcessor,
  205. fullSha1PatternProcessor,
  206. linkProcessor,
  207. mentionProcessor,
  208. issueIndexPatternProcessor,
  209. sha1CurrentPatternProcessor,
  210. emojiShortCodeProcessor,
  211. emojiProcessor,
  212. }
  213. var emojiProcessors = []processor{
  214. emojiShortCodeProcessor,
  215. emojiProcessor,
  216. }
  217. // RenderCommitMessageSubject will use the same logic as PostProcess and
  218. // RenderCommitMessage, but will disable the shortLinkProcessor and
  219. // emailAddressProcessor, will add a defaultLinkProcessor if defaultLink is set,
  220. // which changes every text node into a link to the passed default link.
  221. func RenderCommitMessageSubject(
  222. rawHTML []byte,
  223. urlPrefix, defaultLink string,
  224. metas map[string]string,
  225. ) ([]byte, error) {
  226. ctx := &postProcessCtx{
  227. metas: metas,
  228. urlPrefix: urlPrefix,
  229. procs: commitMessageSubjectProcessors,
  230. }
  231. if defaultLink != "" {
  232. // we don't have to fear data races, because being
  233. // commitMessageSubjectProcessors of fixed len and cap, every time we
  234. // append something to it the slice is realloc+copied, so append always
  235. // generates the slice ex-novo.
  236. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  237. }
  238. return ctx.postProcess(rawHTML)
  239. }
  240. // RenderDescriptionHTML will use similar logic as PostProcess, but will
  241. // use a single special linkProcessor.
  242. func RenderDescriptionHTML(
  243. rawHTML []byte,
  244. urlPrefix string,
  245. metas map[string]string,
  246. ) ([]byte, error) {
  247. ctx := &postProcessCtx{
  248. metas: metas,
  249. urlPrefix: urlPrefix,
  250. procs: []processor{
  251. descriptionLinkProcessor,
  252. },
  253. }
  254. return ctx.postProcess(rawHTML)
  255. }
  256. // RenderEmoji for when we want to just process emoji and shortcodes
  257. // in various places it isn't already run through the normal markdown procesor
  258. func RenderEmoji(
  259. rawHTML []byte,
  260. ) ([]byte, error) {
  261. ctx := &postProcessCtx{
  262. procs: emojiProcessors,
  263. }
  264. return ctx.postProcess(rawHTML)
  265. }
  266. var byteBodyTag = []byte("<body>")
  267. var byteBodyTagClosing = []byte("</body>")
  268. func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) {
  269. if ctx.procs == nil {
  270. ctx.procs = defaultProcessors
  271. }
  272. // give a generous extra 50 bytes
  273. res := make([]byte, 0, len(rawHTML)+50)
  274. res = append(res, byteBodyTag...)
  275. res = append(res, rawHTML...)
  276. res = append(res, byteBodyTagClosing...)
  277. // parse the HTML
  278. nodes, err := html.ParseFragment(bytes.NewReader(res), nil)
  279. if err != nil {
  280. return nil, &postProcessError{"invalid HTML", err}
  281. }
  282. for _, node := range nodes {
  283. ctx.visitNode(node, true)
  284. }
  285. // Create buffer in which the data will be placed again. We know that the
  286. // length will be at least that of res; to spare a few alloc+copy, we
  287. // reuse res, resetting its length to 0.
  288. buf := bytes.NewBuffer(res[:0])
  289. // Render everything to buf.
  290. for _, node := range nodes {
  291. err = html.Render(buf, node)
  292. if err != nil {
  293. return nil, &postProcessError{"error rendering processed HTML", err}
  294. }
  295. }
  296. // remove initial parts - because Render creates a whole HTML page.
  297. res = buf.Bytes()
  298. res = res[bytes.Index(res, byteBodyTag)+len(byteBodyTag) : bytes.LastIndex(res, byteBodyTagClosing)]
  299. // Everything done successfully, return parsed data.
  300. return res, nil
  301. }
  302. func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {
  303. // Add user-content- to IDs if they don't already have them
  304. for idx, attr := range node.Attr {
  305. if attr.Key == "id" && !(strings.HasPrefix(attr.Val, "user-content-") || blackfridayExtRegex.MatchString(attr.Val)) {
  306. node.Attr[idx].Val = "user-content-" + attr.Val
  307. }
  308. if attr.Key == "class" && attr.Val == "emoji" {
  309. visitText = false
  310. }
  311. }
  312. // We ignore code, pre and already generated links.
  313. switch node.Type {
  314. case html.TextNode:
  315. if visitText {
  316. ctx.textNode(node)
  317. }
  318. case html.ElementNode:
  319. if node.Data == "img" {
  320. attrs := node.Attr
  321. for idx, attr := range attrs {
  322. if attr.Key != "src" {
  323. continue
  324. }
  325. link := []byte(attr.Val)
  326. if len(link) > 0 && !IsLink(link) {
  327. prefix := ctx.urlPrefix
  328. if ctx.isWikiMarkdown {
  329. prefix = util.URLJoin(prefix, "wiki", "raw")
  330. }
  331. prefix = strings.Replace(prefix, "/src/", "/media/", 1)
  332. lnk := string(link)
  333. lnk = util.URLJoin(prefix, lnk)
  334. link = []byte(lnk)
  335. }
  336. node.Attr[idx].Val = string(link)
  337. }
  338. } else if node.Data == "a" {
  339. visitText = false
  340. } else if node.Data == "code" || node.Data == "pre" {
  341. return
  342. } else if node.Data == "i" {
  343. for _, attr := range node.Attr {
  344. if attr.Key != "class" {
  345. continue
  346. }
  347. classes := strings.Split(attr.Val, " ")
  348. for i, class := range classes {
  349. if class == "icon" {
  350. classes[0], classes[i] = classes[i], classes[0]
  351. attr.Val = strings.Join(classes, " ")
  352. // Remove all children of icons
  353. child := node.FirstChild
  354. for child != nil {
  355. node.RemoveChild(child)
  356. child = node.FirstChild
  357. }
  358. break
  359. }
  360. }
  361. }
  362. }
  363. for n := node.FirstChild; n != nil; n = n.NextSibling {
  364. ctx.visitNode(n, visitText)
  365. }
  366. }
  367. // ignore everything else
  368. }
  369. // textNode runs the passed node through various processors, in order to handle
  370. // all kinds of special links handled by the post-processing.
  371. func (ctx *postProcessCtx) textNode(node *html.Node) {
  372. for _, processor := range ctx.procs {
  373. processor(ctx, node)
  374. }
  375. }
  376. // createKeyword() renders a highlighted version of an action keyword
  377. func createKeyword(content string) *html.Node {
  378. span := &html.Node{
  379. Type: html.ElementNode,
  380. Data: atom.Span.String(),
  381. Attr: []html.Attribute{},
  382. }
  383. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: keywordClass})
  384. text := &html.Node{
  385. Type: html.TextNode,
  386. Data: content,
  387. }
  388. span.AppendChild(text)
  389. return span
  390. }
  391. func createEmoji(content, class, name string) *html.Node {
  392. span := &html.Node{
  393. Type: html.ElementNode,
  394. Data: atom.Span.String(),
  395. Attr: []html.Attribute{},
  396. }
  397. if class != "" {
  398. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: class})
  399. }
  400. if name != "" {
  401. span.Attr = append(span.Attr, html.Attribute{Key: "aria-label", Val: name})
  402. }
  403. text := &html.Node{
  404. Type: html.TextNode,
  405. Data: content,
  406. }
  407. span.AppendChild(text)
  408. return span
  409. }
  410. func createCustomEmoji(alias, class string) *html.Node {
  411. span := &html.Node{
  412. Type: html.ElementNode,
  413. Data: atom.Span.String(),
  414. Attr: []html.Attribute{},
  415. }
  416. if class != "" {
  417. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: class})
  418. span.Attr = append(span.Attr, html.Attribute{Key: "aria-label", Val: alias})
  419. }
  420. img := &html.Node{
  421. Type: html.ElementNode,
  422. DataAtom: atom.Img,
  423. Data: "img",
  424. Attr: []html.Attribute{},
  425. }
  426. if class != "" {
  427. img.Attr = append(img.Attr, html.Attribute{Key: "src", Val: fmt.Sprintf(`%s/img/emoji/%s.png`, setting.StaticURLPrefix, alias)})
  428. }
  429. span.AppendChild(img)
  430. return span
  431. }
  432. func createLink(href, content, class string) *html.Node {
  433. a := &html.Node{
  434. Type: html.ElementNode,
  435. Data: atom.A.String(),
  436. Attr: []html.Attribute{{Key: "href", Val: href}},
  437. }
  438. if class != "" {
  439. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  440. }
  441. text := &html.Node{
  442. Type: html.TextNode,
  443. Data: content,
  444. }
  445. a.AppendChild(text)
  446. return a
  447. }
  448. func createCodeLink(href, content, class string) *html.Node {
  449. a := &html.Node{
  450. Type: html.ElementNode,
  451. Data: atom.A.String(),
  452. Attr: []html.Attribute{{Key: "href", Val: href}},
  453. }
  454. if class != "" {
  455. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  456. }
  457. text := &html.Node{
  458. Type: html.TextNode,
  459. Data: content,
  460. }
  461. code := &html.Node{
  462. Type: html.ElementNode,
  463. Data: atom.Code.String(),
  464. Attr: []html.Attribute{{Key: "class", Val: "nohighlight"}},
  465. }
  466. code.AppendChild(text)
  467. a.AppendChild(code)
  468. return a
  469. }
  470. // replaceContent takes text node, and in its content it replaces a section of
  471. // it with the specified newNode.
  472. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  473. replaceContentList(node, i, j, []*html.Node{newNode})
  474. }
  475. // replaceContentList takes text node, and in its content it replaces a section of
  476. // it with the specified newNodes. An example to visualize how this can work can
  477. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  478. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  479. // get the data before and after the match
  480. before := node.Data[:i]
  481. after := node.Data[j:]
  482. // Replace in the current node the text, so that it is only what it is
  483. // supposed to have.
  484. node.Data = before
  485. // Get the current next sibling, before which we place the replaced data,
  486. // and after that we place the new text node.
  487. nextSibling := node.NextSibling
  488. for _, n := range newNodes {
  489. node.Parent.InsertBefore(n, nextSibling)
  490. }
  491. if after != "" {
  492. node.Parent.InsertBefore(&html.Node{
  493. Type: html.TextNode,
  494. Data: after,
  495. }, nextSibling)
  496. }
  497. }
  498. func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
  499. // We replace only the first mention; other mentions will be addressed later
  500. found, loc := references.FindFirstMentionBytes([]byte(node.Data))
  501. if !found {
  502. return
  503. }
  504. mention := node.Data[loc.Start:loc.End]
  505. var teams string
  506. teams, ok := ctx.metas["teams"]
  507. if ok && strings.Contains(teams, ","+strings.ToLower(mention[1:])+",") {
  508. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, "org", ctx.metas["org"], "teams", mention[1:]), mention, "mention"))
  509. } else {
  510. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, mention[1:]), mention, "mention"))
  511. }
  512. }
  513. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  514. shortLinkProcessorFull(ctx, node, false)
  515. }
  516. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  517. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  518. if m == nil {
  519. return
  520. }
  521. content := node.Data[m[2]:m[3]]
  522. tail := node.Data[m[4]:m[5]]
  523. props := make(map[string]string)
  524. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  525. // It makes page handling terrible, but we prefer GitHub syntax
  526. // And fall back to MediaWiki only when it is obvious from the look
  527. // Of text and link contents
  528. sl := strings.Split(content, "|")
  529. for _, v := range sl {
  530. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  531. // There is no equal in this argument; this is a mandatory arg
  532. if props["name"] == "" {
  533. if isLinkStr(v) {
  534. // If we clearly see it is a link, we save it so
  535. // But first we need to ensure, that if both mandatory args provided
  536. // look like links, we stick to GitHub syntax
  537. if props["link"] != "" {
  538. props["name"] = props["link"]
  539. }
  540. props["link"] = strings.TrimSpace(v)
  541. } else {
  542. props["name"] = v
  543. }
  544. } else {
  545. props["link"] = strings.TrimSpace(v)
  546. }
  547. } else {
  548. // There is an equal; optional argument.
  549. sep := strings.IndexByte(v, '=')
  550. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  551. // When parsing HTML, x/net/html will change all quotes which are
  552. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  553. // be enough, since that only checks a single byte.
  554. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  555. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  556. const lenQuote = len("‘")
  557. val = val[lenQuote : len(val)-lenQuote]
  558. } else if (strings.HasPrefix(val, "\"") && strings.HasSuffix(val, "\"")) ||
  559. (strings.HasPrefix(val, "'") && strings.HasSuffix(val, "'")) {
  560. val = val[1 : len(val)-1]
  561. } else if strings.HasPrefix(val, "'") && strings.HasSuffix(val, "’") {
  562. const lenQuote = len("‘")
  563. val = val[1 : len(val)-lenQuote]
  564. }
  565. props[key] = val
  566. }
  567. }
  568. var name, link string
  569. if props["link"] != "" {
  570. link = props["link"]
  571. } else if props["name"] != "" {
  572. link = props["name"]
  573. }
  574. if props["title"] != "" {
  575. name = props["title"]
  576. } else if props["name"] != "" {
  577. name = props["name"]
  578. } else {
  579. name = link
  580. }
  581. name += tail
  582. image := false
  583. switch ext := filepath.Ext(link); ext {
  584. // fast path: empty string, ignore
  585. case "":
  586. break
  587. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  588. image = true
  589. }
  590. childNode := &html.Node{}
  591. linkNode := &html.Node{
  592. FirstChild: childNode,
  593. LastChild: childNode,
  594. Type: html.ElementNode,
  595. Data: "a",
  596. DataAtom: atom.A,
  597. }
  598. childNode.Parent = linkNode
  599. absoluteLink := isLinkStr(link)
  600. if !absoluteLink {
  601. if image {
  602. link = strings.Replace(link, " ", "+", -1)
  603. } else {
  604. link = strings.Replace(link, " ", "-", -1)
  605. }
  606. if !strings.Contains(link, "/") {
  607. link = url.PathEscape(link)
  608. }
  609. }
  610. urlPrefix := ctx.urlPrefix
  611. if image {
  612. if !absoluteLink {
  613. if IsSameDomain(urlPrefix) {
  614. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  615. }
  616. if ctx.isWikiMarkdown {
  617. link = util.URLJoin("wiki", "raw", link)
  618. }
  619. link = util.URLJoin(urlPrefix, link)
  620. }
  621. title := props["title"]
  622. if title == "" {
  623. title = props["alt"]
  624. }
  625. if title == "" {
  626. title = path.Base(name)
  627. }
  628. alt := props["alt"]
  629. if alt == "" {
  630. alt = name
  631. }
  632. // make the childNode an image - if we can, we also place the alt
  633. childNode.Type = html.ElementNode
  634. childNode.Data = "img"
  635. childNode.DataAtom = atom.Img
  636. childNode.Attr = []html.Attribute{
  637. {Key: "src", Val: link},
  638. {Key: "title", Val: title},
  639. {Key: "alt", Val: alt},
  640. }
  641. if alt == "" {
  642. childNode.Attr = childNode.Attr[:2]
  643. }
  644. } else {
  645. if !absoluteLink {
  646. if ctx.isWikiMarkdown {
  647. link = util.URLJoin("wiki", link)
  648. }
  649. link = util.URLJoin(urlPrefix, link)
  650. }
  651. childNode.Type = html.TextNode
  652. childNode.Data = name
  653. }
  654. if noLink {
  655. linkNode = childNode
  656. } else {
  657. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  658. }
  659. replaceContent(node, m[0], m[1], linkNode)
  660. }
  661. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  662. if ctx.metas == nil {
  663. return
  664. }
  665. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  666. if m == nil {
  667. return
  668. }
  669. link := node.Data[m[0]:m[1]]
  670. id := "#" + node.Data[m[2]:m[3]]
  671. // extract repo and org name from matched link like
  672. // http://localhost:3000/gituser/myrepo/issues/1
  673. linkParts := strings.Split(path.Clean(link), "/")
  674. matchOrg := linkParts[len(linkParts)-4]
  675. matchRepo := linkParts[len(linkParts)-3]
  676. if matchOrg == ctx.metas["user"] && matchRepo == ctx.metas["repo"] {
  677. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  678. // and we should indicate that in the text somehow
  679. replaceContent(node, m[0], m[1], createLink(link, id, "ref-issue"))
  680. } else {
  681. orgRepoID := matchOrg + "/" + matchRepo + id
  682. replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "ref-issue"))
  683. }
  684. }
  685. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  686. if ctx.metas == nil {
  687. return
  688. }
  689. var (
  690. found bool
  691. ref *references.RenderizableReference
  692. )
  693. _, exttrack := ctx.metas["format"]
  694. alphanum := ctx.metas["style"] == IssueNameStyleAlphanumeric
  695. // Repos with external issue trackers might still need to reference local PRs
  696. // We need to concern with the first one that shows up in the text, whichever it is
  697. found, ref = references.FindRenderizableReferenceNumeric(node.Data, exttrack && alphanum)
  698. if exttrack && alphanum {
  699. if found2, ref2 := references.FindRenderizableReferenceAlphanumeric(node.Data); found2 {
  700. if !found || ref2.RefLocation.Start < ref.RefLocation.Start {
  701. found = true
  702. ref = ref2
  703. }
  704. }
  705. }
  706. if !found {
  707. return
  708. }
  709. var link *html.Node
  710. reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
  711. if exttrack && !ref.IsPull {
  712. ctx.metas["index"] = ref.Issue
  713. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), reftext, "ref-issue")
  714. } else {
  715. // Path determines the type of link that will be rendered. It's unknown at this point whether
  716. // the linked item is actually a PR or an issue. Luckily it's of no real consequence because
  717. // Gitea will redirect on click as appropriate.
  718. path := "issues"
  719. if ref.IsPull {
  720. path = "pulls"
  721. }
  722. if ref.Owner == "" {
  723. link = createLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], path, ref.Issue), reftext, "ref-issue")
  724. } else {
  725. link = createLink(util.URLJoin(setting.AppURL, ref.Owner, ref.Name, path, ref.Issue), reftext, "ref-issue")
  726. }
  727. }
  728. if ref.Action == references.XRefActionNone {
  729. replaceContent(node, ref.RefLocation.Start, ref.RefLocation.End, link)
  730. return
  731. }
  732. // Decorate action keywords if actionable
  733. var keyword *html.Node
  734. if references.IsXrefActionable(ref, exttrack, alphanum) {
  735. keyword = createKeyword(node.Data[ref.ActionLocation.Start:ref.ActionLocation.End])
  736. } else {
  737. keyword = &html.Node{
  738. Type: html.TextNode,
  739. Data: node.Data[ref.ActionLocation.Start:ref.ActionLocation.End],
  740. }
  741. }
  742. spaces := &html.Node{
  743. Type: html.TextNode,
  744. Data: node.Data[ref.ActionLocation.End:ref.RefLocation.Start],
  745. }
  746. replaceContentList(node, ref.ActionLocation.Start, ref.RefLocation.End, []*html.Node{keyword, spaces, link})
  747. }
  748. // fullSha1PatternProcessor renders SHA containing URLs
  749. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  750. if ctx.metas == nil {
  751. return
  752. }
  753. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  754. if m == nil {
  755. return
  756. }
  757. urlFull := node.Data[m[0]:m[1]]
  758. text := base.ShortSha(node.Data[m[2]:m[3]])
  759. // 3rd capture group matches a optional path
  760. subpath := ""
  761. if m[5] > 0 {
  762. subpath = node.Data[m[4]:m[5]]
  763. }
  764. // 4th capture group matches a optional url hash
  765. hash := ""
  766. if m[7] > 0 {
  767. hash = node.Data[m[6]:m[7]][1:]
  768. }
  769. start := m[0]
  770. end := m[1]
  771. // If url ends in '.', it's very likely that it is not part of the
  772. // actual url but used to finish a sentence.
  773. if strings.HasSuffix(urlFull, ".") {
  774. end--
  775. urlFull = urlFull[:len(urlFull)-1]
  776. if hash != "" {
  777. hash = hash[:len(hash)-1]
  778. } else if subpath != "" {
  779. subpath = subpath[:len(subpath)-1]
  780. }
  781. }
  782. if subpath != "" {
  783. text += subpath
  784. }
  785. if hash != "" {
  786. text += " (" + hash + ")"
  787. }
  788. replaceContent(node, start, end, createCodeLink(urlFull, text, "commit"))
  789. }
  790. // emojiShortCodeProcessor for rendering text like :smile: into emoji
  791. func emojiShortCodeProcessor(ctx *postProcessCtx, node *html.Node) {
  792. m := EmojiShortCodeRegex.FindStringSubmatchIndex(node.Data)
  793. if m == nil {
  794. return
  795. }
  796. alias := node.Data[m[0]:m[1]]
  797. alias = strings.Replace(alias, ":", "", -1)
  798. converted := emoji.FromAlias(alias)
  799. if converted == nil {
  800. // check if this is a custom reaction
  801. s := strings.Join(setting.UI.Reactions, " ") + "gitea"
  802. if strings.Contains(s, alias) {
  803. replaceContent(node, m[0], m[1], createCustomEmoji(alias, "emoji"))
  804. return
  805. }
  806. return
  807. }
  808. replaceContent(node, m[0], m[1], createEmoji(converted.Emoji, "emoji", converted.Description))
  809. }
  810. // emoji processor to match emoji and add emoji class
  811. func emojiProcessor(ctx *postProcessCtx, node *html.Node) {
  812. m := emojiRegex.FindStringSubmatchIndex(node.Data)
  813. if m == nil {
  814. return
  815. }
  816. codepoint := node.Data[m[0]:m[1]]
  817. val := emoji.FromCode(codepoint)
  818. if val != nil {
  819. replaceContent(node, m[0], m[1], createEmoji(codepoint, "emoji", val.Description))
  820. }
  821. }
  822. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  823. // are assumed to be in the same repository.
  824. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  825. if ctx.metas == nil || ctx.metas["user"] == "" || ctx.metas["repo"] == "" || ctx.metas["repoPath"] == "" {
  826. return
  827. }
  828. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  829. if m == nil {
  830. return
  831. }
  832. hash := node.Data[m[2]:m[3]]
  833. // The regex does not lie, it matches the hash pattern.
  834. // However, a regex cannot know if a hash actually exists or not.
  835. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  836. // but that is not always the case.
  837. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  838. // as used by git and github for linking and thus we have to do similar.
  839. // Because of this, we check to make sure that a matched hash is actually
  840. // a commit in the repository before making it a link.
  841. if _, err := git.NewCommand("rev-parse", "--verify", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil {
  842. if !strings.Contains(err.Error(), "fatal: Needed a single revision") {
  843. log.Debug("sha1CurrentPatternProcessor git rev-parse: %v", err)
  844. }
  845. return
  846. }
  847. replaceContent(node, m[2], m[3],
  848. createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash), "commit"))
  849. }
  850. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  851. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  852. m := emailRegex.FindStringSubmatchIndex(node.Data)
  853. if m == nil {
  854. return
  855. }
  856. mail := node.Data[m[2]:m[3]]
  857. replaceContent(node, m[2], m[3], createLink("mailto:"+mail, mail, "mailto"))
  858. }
  859. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  860. // markdown.
  861. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  862. m := common.LinkRegex.FindStringIndex(node.Data)
  863. if m == nil {
  864. return
  865. }
  866. uri := node.Data[m[0]:m[1]]
  867. replaceContent(node, m[0], m[1], createLink(uri, uri, "link"))
  868. }
  869. func genDefaultLinkProcessor(defaultLink string) processor {
  870. return func(ctx *postProcessCtx, node *html.Node) {
  871. ch := &html.Node{
  872. Parent: node,
  873. Type: html.TextNode,
  874. Data: node.Data,
  875. }
  876. node.Type = html.ElementNode
  877. node.Data = "a"
  878. node.DataAtom = atom.A
  879. node.Attr = []html.Attribute{
  880. {Key: "href", Val: defaultLink},
  881. {Key: "class", Val: "default-link"},
  882. }
  883. node.FirstChild, node.LastChild = ch, ch
  884. }
  885. }
  886. // descriptionLinkProcessor creates links for DescriptionHTML
  887. func descriptionLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  888. m := common.LinkRegex.FindStringIndex(node.Data)
  889. if m == nil {
  890. return
  891. }
  892. uri := node.Data[m[0]:m[1]]
  893. replaceContent(node, m[0], m[1], createDescriptionLink(uri, uri))
  894. }
  895. func createDescriptionLink(href, content string) *html.Node {
  896. textNode := &html.Node{
  897. Type: html.TextNode,
  898. Data: content,
  899. }
  900. linkNode := &html.Node{
  901. FirstChild: textNode,
  902. LastChild: textNode,
  903. Type: html.ElementNode,
  904. Data: "a",
  905. DataAtom: atom.A,
  906. Attr: []html.Attribute{
  907. {Key: "href", Val: href},
  908. {Key: "target", Val: "_blank"},
  909. {Key: "rel", Val: "noopener noreferrer"},
  910. },
  911. }
  912. textNode.Parent = linkNode
  913. return linkNode
  914. }