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.

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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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. emojiShortCodeProcessor,
  253. emojiProcessor,
  254. },
  255. }
  256. return ctx.postProcess(rawHTML)
  257. }
  258. // RenderEmoji for when we want to just process emoji and shortcodes
  259. // in various places it isn't already run through the normal markdown procesor
  260. func RenderEmoji(
  261. rawHTML []byte,
  262. ) ([]byte, error) {
  263. ctx := &postProcessCtx{
  264. procs: emojiProcessors,
  265. }
  266. return ctx.postProcess(rawHTML)
  267. }
  268. var byteBodyTag = []byte("<body>")
  269. var byteBodyTagClosing = []byte("</body>")
  270. func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) {
  271. if ctx.procs == nil {
  272. ctx.procs = defaultProcessors
  273. }
  274. // give a generous extra 50 bytes
  275. res := make([]byte, 0, len(rawHTML)+50)
  276. res = append(res, byteBodyTag...)
  277. res = append(res, rawHTML...)
  278. res = append(res, byteBodyTagClosing...)
  279. // parse the HTML
  280. nodes, err := html.ParseFragment(bytes.NewReader(res), nil)
  281. if err != nil {
  282. return nil, &postProcessError{"invalid HTML", err}
  283. }
  284. for _, node := range nodes {
  285. ctx.visitNode(node, true)
  286. }
  287. // Create buffer in which the data will be placed again. We know that the
  288. // length will be at least that of res; to spare a few alloc+copy, we
  289. // reuse res, resetting its length to 0.
  290. buf := bytes.NewBuffer(res[:0])
  291. // Render everything to buf.
  292. for _, node := range nodes {
  293. err = html.Render(buf, node)
  294. if err != nil {
  295. return nil, &postProcessError{"error rendering processed HTML", err}
  296. }
  297. }
  298. // remove initial parts - because Render creates a whole HTML page.
  299. res = buf.Bytes()
  300. res = res[bytes.Index(res, byteBodyTag)+len(byteBodyTag) : bytes.LastIndex(res, byteBodyTagClosing)]
  301. // Everything done successfully, return parsed data.
  302. return res, nil
  303. }
  304. func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {
  305. // Add user-content- to IDs if they don't already have them
  306. for idx, attr := range node.Attr {
  307. if attr.Key == "id" && !(strings.HasPrefix(attr.Val, "user-content-") || blackfridayExtRegex.MatchString(attr.Val)) {
  308. node.Attr[idx].Val = "user-content-" + attr.Val
  309. }
  310. if attr.Key == "class" && attr.Val == "emoji" {
  311. visitText = false
  312. }
  313. }
  314. // We ignore code, pre and already generated links.
  315. switch node.Type {
  316. case html.TextNode:
  317. if visitText {
  318. ctx.textNode(node)
  319. }
  320. case html.ElementNode:
  321. if node.Data == "img" {
  322. attrs := node.Attr
  323. for idx, attr := range attrs {
  324. if attr.Key != "src" {
  325. continue
  326. }
  327. link := []byte(attr.Val)
  328. if len(link) > 0 && !IsLink(link) {
  329. prefix := ctx.urlPrefix
  330. if ctx.isWikiMarkdown {
  331. prefix = util.URLJoin(prefix, "wiki", "raw")
  332. }
  333. prefix = strings.Replace(prefix, "/src/", "/media/", 1)
  334. lnk := string(link)
  335. lnk = util.URLJoin(prefix, lnk)
  336. link = []byte(lnk)
  337. }
  338. node.Attr[idx].Val = string(link)
  339. }
  340. } else if node.Data == "a" {
  341. visitText = false
  342. } else if node.Data == "code" || node.Data == "pre" {
  343. return
  344. } else if node.Data == "i" {
  345. for _, attr := range node.Attr {
  346. if attr.Key != "class" {
  347. continue
  348. }
  349. classes := strings.Split(attr.Val, " ")
  350. for i, class := range classes {
  351. if class == "icon" {
  352. classes[0], classes[i] = classes[i], classes[0]
  353. attr.Val = strings.Join(classes, " ")
  354. // Remove all children of icons
  355. child := node.FirstChild
  356. for child != nil {
  357. node.RemoveChild(child)
  358. child = node.FirstChild
  359. }
  360. break
  361. }
  362. }
  363. }
  364. }
  365. for n := node.FirstChild; n != nil; n = n.NextSibling {
  366. ctx.visitNode(n, visitText)
  367. }
  368. }
  369. // ignore everything else
  370. }
  371. // textNode runs the passed node through various processors, in order to handle
  372. // all kinds of special links handled by the post-processing.
  373. func (ctx *postProcessCtx) textNode(node *html.Node) {
  374. for _, processor := range ctx.procs {
  375. processor(ctx, node)
  376. }
  377. }
  378. // createKeyword() renders a highlighted version of an action keyword
  379. func createKeyword(content string) *html.Node {
  380. span := &html.Node{
  381. Type: html.ElementNode,
  382. Data: atom.Span.String(),
  383. Attr: []html.Attribute{},
  384. }
  385. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: keywordClass})
  386. text := &html.Node{
  387. Type: html.TextNode,
  388. Data: content,
  389. }
  390. span.AppendChild(text)
  391. return span
  392. }
  393. func createEmoji(content, class, name string) *html.Node {
  394. span := &html.Node{
  395. Type: html.ElementNode,
  396. Data: atom.Span.String(),
  397. Attr: []html.Attribute{},
  398. }
  399. if class != "" {
  400. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: class})
  401. }
  402. if name != "" {
  403. span.Attr = append(span.Attr, html.Attribute{Key: "aria-label", Val: name})
  404. }
  405. text := &html.Node{
  406. Type: html.TextNode,
  407. Data: content,
  408. }
  409. span.AppendChild(text)
  410. return span
  411. }
  412. func createCustomEmoji(alias, class string) *html.Node {
  413. span := &html.Node{
  414. Type: html.ElementNode,
  415. Data: atom.Span.String(),
  416. Attr: []html.Attribute{},
  417. }
  418. if class != "" {
  419. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: class})
  420. span.Attr = append(span.Attr, html.Attribute{Key: "aria-label", Val: alias})
  421. }
  422. img := &html.Node{
  423. Type: html.ElementNode,
  424. DataAtom: atom.Img,
  425. Data: "img",
  426. Attr: []html.Attribute{},
  427. }
  428. if class != "" {
  429. img.Attr = append(img.Attr, html.Attribute{Key: "src", Val: fmt.Sprintf(`%s/img/emoji/%s.png`, setting.StaticURLPrefix, alias)})
  430. }
  431. span.AppendChild(img)
  432. return span
  433. }
  434. func createLink(href, content, class string) *html.Node {
  435. a := &html.Node{
  436. Type: html.ElementNode,
  437. Data: atom.A.String(),
  438. Attr: []html.Attribute{{Key: "href", Val: href}},
  439. }
  440. if class != "" {
  441. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  442. }
  443. text := &html.Node{
  444. Type: html.TextNode,
  445. Data: content,
  446. }
  447. a.AppendChild(text)
  448. return a
  449. }
  450. func createCodeLink(href, content, class string) *html.Node {
  451. a := &html.Node{
  452. Type: html.ElementNode,
  453. Data: atom.A.String(),
  454. Attr: []html.Attribute{{Key: "href", Val: href}},
  455. }
  456. if class != "" {
  457. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  458. }
  459. text := &html.Node{
  460. Type: html.TextNode,
  461. Data: content,
  462. }
  463. code := &html.Node{
  464. Type: html.ElementNode,
  465. Data: atom.Code.String(),
  466. Attr: []html.Attribute{{Key: "class", Val: "nohighlight"}},
  467. }
  468. code.AppendChild(text)
  469. a.AppendChild(code)
  470. return a
  471. }
  472. // replaceContent takes text node, and in its content it replaces a section of
  473. // it with the specified newNode.
  474. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  475. replaceContentList(node, i, j, []*html.Node{newNode})
  476. }
  477. // replaceContentList takes text node, and in its content it replaces a section of
  478. // it with the specified newNodes. An example to visualize how this can work can
  479. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  480. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  481. // get the data before and after the match
  482. before := node.Data[:i]
  483. after := node.Data[j:]
  484. // Replace in the current node the text, so that it is only what it is
  485. // supposed to have.
  486. node.Data = before
  487. // Get the current next sibling, before which we place the replaced data,
  488. // and after that we place the new text node.
  489. nextSibling := node.NextSibling
  490. for _, n := range newNodes {
  491. node.Parent.InsertBefore(n, nextSibling)
  492. }
  493. if after != "" {
  494. node.Parent.InsertBefore(&html.Node{
  495. Type: html.TextNode,
  496. Data: after,
  497. }, nextSibling)
  498. }
  499. }
  500. func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
  501. // We replace only the first mention; other mentions will be addressed later
  502. found, loc := references.FindFirstMentionBytes([]byte(node.Data))
  503. if !found {
  504. return
  505. }
  506. mention := node.Data[loc.Start:loc.End]
  507. var teams string
  508. teams, ok := ctx.metas["teams"]
  509. if ok && strings.Contains(teams, ","+strings.ToLower(mention[1:])+",") {
  510. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, "org", ctx.metas["org"], "teams", mention[1:]), mention, "mention"))
  511. } else {
  512. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, mention[1:]), mention, "mention"))
  513. }
  514. }
  515. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  516. shortLinkProcessorFull(ctx, node, false)
  517. }
  518. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  519. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  520. if m == nil {
  521. return
  522. }
  523. content := node.Data[m[2]:m[3]]
  524. tail := node.Data[m[4]:m[5]]
  525. props := make(map[string]string)
  526. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  527. // It makes page handling terrible, but we prefer GitHub syntax
  528. // And fall back to MediaWiki only when it is obvious from the look
  529. // Of text and link contents
  530. sl := strings.Split(content, "|")
  531. for _, v := range sl {
  532. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  533. // There is no equal in this argument; this is a mandatory arg
  534. if props["name"] == "" {
  535. if isLinkStr(v) {
  536. // If we clearly see it is a link, we save it so
  537. // But first we need to ensure, that if both mandatory args provided
  538. // look like links, we stick to GitHub syntax
  539. if props["link"] != "" {
  540. props["name"] = props["link"]
  541. }
  542. props["link"] = strings.TrimSpace(v)
  543. } else {
  544. props["name"] = v
  545. }
  546. } else {
  547. props["link"] = strings.TrimSpace(v)
  548. }
  549. } else {
  550. // There is an equal; optional argument.
  551. sep := strings.IndexByte(v, '=')
  552. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  553. // When parsing HTML, x/net/html will change all quotes which are
  554. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  555. // be enough, since that only checks a single byte.
  556. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  557. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  558. const lenQuote = len("‘")
  559. val = val[lenQuote : len(val)-lenQuote]
  560. } else if (strings.HasPrefix(val, "\"") && strings.HasSuffix(val, "\"")) ||
  561. (strings.HasPrefix(val, "'") && strings.HasSuffix(val, "'")) {
  562. val = val[1 : len(val)-1]
  563. } else if strings.HasPrefix(val, "'") && strings.HasSuffix(val, "’") {
  564. const lenQuote = len("‘")
  565. val = val[1 : len(val)-lenQuote]
  566. }
  567. props[key] = val
  568. }
  569. }
  570. var name, link string
  571. if props["link"] != "" {
  572. link = props["link"]
  573. } else if props["name"] != "" {
  574. link = props["name"]
  575. }
  576. if props["title"] != "" {
  577. name = props["title"]
  578. } else if props["name"] != "" {
  579. name = props["name"]
  580. } else {
  581. name = link
  582. }
  583. name += tail
  584. image := false
  585. switch ext := filepath.Ext(link); ext {
  586. // fast path: empty string, ignore
  587. case "":
  588. break
  589. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  590. image = true
  591. }
  592. childNode := &html.Node{}
  593. linkNode := &html.Node{
  594. FirstChild: childNode,
  595. LastChild: childNode,
  596. Type: html.ElementNode,
  597. Data: "a",
  598. DataAtom: atom.A,
  599. }
  600. childNode.Parent = linkNode
  601. absoluteLink := isLinkStr(link)
  602. if !absoluteLink {
  603. if image {
  604. link = strings.Replace(link, " ", "+", -1)
  605. } else {
  606. link = strings.Replace(link, " ", "-", -1)
  607. }
  608. if !strings.Contains(link, "/") {
  609. link = url.PathEscape(link)
  610. }
  611. }
  612. urlPrefix := ctx.urlPrefix
  613. if image {
  614. if !absoluteLink {
  615. if IsSameDomain(urlPrefix) {
  616. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  617. }
  618. if ctx.isWikiMarkdown {
  619. link = util.URLJoin("wiki", "raw", link)
  620. }
  621. link = util.URLJoin(urlPrefix, link)
  622. }
  623. title := props["title"]
  624. if title == "" {
  625. title = props["alt"]
  626. }
  627. if title == "" {
  628. title = path.Base(name)
  629. }
  630. alt := props["alt"]
  631. if alt == "" {
  632. alt = name
  633. }
  634. // make the childNode an image - if we can, we also place the alt
  635. childNode.Type = html.ElementNode
  636. childNode.Data = "img"
  637. childNode.DataAtom = atom.Img
  638. childNode.Attr = []html.Attribute{
  639. {Key: "src", Val: link},
  640. {Key: "title", Val: title},
  641. {Key: "alt", Val: alt},
  642. }
  643. if alt == "" {
  644. childNode.Attr = childNode.Attr[:2]
  645. }
  646. } else {
  647. if !absoluteLink {
  648. if ctx.isWikiMarkdown {
  649. link = util.URLJoin("wiki", link)
  650. }
  651. link = util.URLJoin(urlPrefix, link)
  652. }
  653. childNode.Type = html.TextNode
  654. childNode.Data = name
  655. }
  656. if noLink {
  657. linkNode = childNode
  658. } else {
  659. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  660. }
  661. replaceContent(node, m[0], m[1], linkNode)
  662. }
  663. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  664. if ctx.metas == nil {
  665. return
  666. }
  667. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  668. if m == nil {
  669. return
  670. }
  671. link := node.Data[m[0]:m[1]]
  672. id := "#" + node.Data[m[2]:m[3]]
  673. // extract repo and org name from matched link like
  674. // http://localhost:3000/gituser/myrepo/issues/1
  675. linkParts := strings.Split(path.Clean(link), "/")
  676. matchOrg := linkParts[len(linkParts)-4]
  677. matchRepo := linkParts[len(linkParts)-3]
  678. if matchOrg == ctx.metas["user"] && matchRepo == ctx.metas["repo"] {
  679. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  680. // and we should indicate that in the text somehow
  681. replaceContent(node, m[0], m[1], createLink(link, id, "ref-issue"))
  682. } else {
  683. orgRepoID := matchOrg + "/" + matchRepo + id
  684. replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "ref-issue"))
  685. }
  686. }
  687. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  688. if ctx.metas == nil {
  689. return
  690. }
  691. var (
  692. found bool
  693. ref *references.RenderizableReference
  694. )
  695. _, exttrack := ctx.metas["format"]
  696. alphanum := ctx.metas["style"] == IssueNameStyleAlphanumeric
  697. // Repos with external issue trackers might still need to reference local PRs
  698. // We need to concern with the first one that shows up in the text, whichever it is
  699. found, ref = references.FindRenderizableReferenceNumeric(node.Data, exttrack && alphanum)
  700. if exttrack && alphanum {
  701. if found2, ref2 := references.FindRenderizableReferenceAlphanumeric(node.Data); found2 {
  702. if !found || ref2.RefLocation.Start < ref.RefLocation.Start {
  703. found = true
  704. ref = ref2
  705. }
  706. }
  707. }
  708. if !found {
  709. return
  710. }
  711. var link *html.Node
  712. reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
  713. if exttrack && !ref.IsPull {
  714. ctx.metas["index"] = ref.Issue
  715. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), reftext, "ref-issue")
  716. } else {
  717. // Path determines the type of link that will be rendered. It's unknown at this point whether
  718. // the linked item is actually a PR or an issue. Luckily it's of no real consequence because
  719. // Gitea will redirect on click as appropriate.
  720. path := "issues"
  721. if ref.IsPull {
  722. path = "pulls"
  723. }
  724. if ref.Owner == "" {
  725. link = createLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], path, ref.Issue), reftext, "ref-issue")
  726. } else {
  727. link = createLink(util.URLJoin(setting.AppURL, ref.Owner, ref.Name, path, ref.Issue), reftext, "ref-issue")
  728. }
  729. }
  730. if ref.Action == references.XRefActionNone {
  731. replaceContent(node, ref.RefLocation.Start, ref.RefLocation.End, link)
  732. return
  733. }
  734. // Decorate action keywords if actionable
  735. var keyword *html.Node
  736. if references.IsXrefActionable(ref, exttrack, alphanum) {
  737. keyword = createKeyword(node.Data[ref.ActionLocation.Start:ref.ActionLocation.End])
  738. } else {
  739. keyword = &html.Node{
  740. Type: html.TextNode,
  741. Data: node.Data[ref.ActionLocation.Start:ref.ActionLocation.End],
  742. }
  743. }
  744. spaces := &html.Node{
  745. Type: html.TextNode,
  746. Data: node.Data[ref.ActionLocation.End:ref.RefLocation.Start],
  747. }
  748. replaceContentList(node, ref.ActionLocation.Start, ref.RefLocation.End, []*html.Node{keyword, spaces, link})
  749. }
  750. // fullSha1PatternProcessor renders SHA containing URLs
  751. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  752. if ctx.metas == nil {
  753. return
  754. }
  755. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  756. if m == nil {
  757. return
  758. }
  759. urlFull := node.Data[m[0]:m[1]]
  760. text := base.ShortSha(node.Data[m[2]:m[3]])
  761. // 3rd capture group matches a optional path
  762. subpath := ""
  763. if m[5] > 0 {
  764. subpath = node.Data[m[4]:m[5]]
  765. }
  766. // 4th capture group matches a optional url hash
  767. hash := ""
  768. if m[7] > 0 {
  769. hash = node.Data[m[6]:m[7]][1:]
  770. }
  771. start := m[0]
  772. end := m[1]
  773. // If url ends in '.', it's very likely that it is not part of the
  774. // actual url but used to finish a sentence.
  775. if strings.HasSuffix(urlFull, ".") {
  776. end--
  777. urlFull = urlFull[:len(urlFull)-1]
  778. if hash != "" {
  779. hash = hash[:len(hash)-1]
  780. } else if subpath != "" {
  781. subpath = subpath[:len(subpath)-1]
  782. }
  783. }
  784. if subpath != "" {
  785. text += subpath
  786. }
  787. if hash != "" {
  788. text += " (" + hash + ")"
  789. }
  790. replaceContent(node, start, end, createCodeLink(urlFull, text, "commit"))
  791. }
  792. // emojiShortCodeProcessor for rendering text like :smile: into emoji
  793. func emojiShortCodeProcessor(ctx *postProcessCtx, node *html.Node) {
  794. m := EmojiShortCodeRegex.FindStringSubmatchIndex(node.Data)
  795. if m == nil {
  796. return
  797. }
  798. alias := node.Data[m[0]:m[1]]
  799. alias = strings.Replace(alias, ":", "", -1)
  800. converted := emoji.FromAlias(alias)
  801. if converted == nil {
  802. // check if this is a custom reaction
  803. s := strings.Join(setting.UI.Reactions, " ") + "gitea"
  804. if strings.Contains(s, alias) {
  805. replaceContent(node, m[0], m[1], createCustomEmoji(alias, "emoji"))
  806. return
  807. }
  808. return
  809. }
  810. replaceContent(node, m[0], m[1], createEmoji(converted.Emoji, "emoji", converted.Description))
  811. }
  812. // emoji processor to match emoji and add emoji class
  813. func emojiProcessor(ctx *postProcessCtx, node *html.Node) {
  814. m := emojiRegex.FindStringSubmatchIndex(node.Data)
  815. if m == nil {
  816. return
  817. }
  818. codepoint := node.Data[m[0]:m[1]]
  819. val := emoji.FromCode(codepoint)
  820. if val != nil {
  821. replaceContent(node, m[0], m[1], createEmoji(codepoint, "emoji", val.Description))
  822. }
  823. }
  824. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  825. // are assumed to be in the same repository.
  826. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  827. if ctx.metas == nil || ctx.metas["user"] == "" || ctx.metas["repo"] == "" || ctx.metas["repoPath"] == "" {
  828. return
  829. }
  830. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  831. if m == nil {
  832. return
  833. }
  834. hash := node.Data[m[2]:m[3]]
  835. // The regex does not lie, it matches the hash pattern.
  836. // However, a regex cannot know if a hash actually exists or not.
  837. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  838. // but that is not always the case.
  839. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  840. // as used by git and github for linking and thus we have to do similar.
  841. // Because of this, we check to make sure that a matched hash is actually
  842. // a commit in the repository before making it a link.
  843. if _, err := git.NewCommand("rev-parse", "--verify", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil {
  844. if !strings.Contains(err.Error(), "fatal: Needed a single revision") {
  845. log.Debug("sha1CurrentPatternProcessor git rev-parse: %v", err)
  846. }
  847. return
  848. }
  849. replaceContent(node, m[2], m[3],
  850. createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash), "commit"))
  851. }
  852. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  853. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  854. m := emailRegex.FindStringSubmatchIndex(node.Data)
  855. if m == nil {
  856. return
  857. }
  858. mail := node.Data[m[2]:m[3]]
  859. replaceContent(node, m[2], m[3], createLink("mailto:"+mail, mail, "mailto"))
  860. }
  861. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  862. // markdown.
  863. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  864. m := common.LinkRegex.FindStringIndex(node.Data)
  865. if m == nil {
  866. return
  867. }
  868. uri := node.Data[m[0]:m[1]]
  869. replaceContent(node, m[0], m[1], createLink(uri, uri, "link"))
  870. }
  871. func genDefaultLinkProcessor(defaultLink string) processor {
  872. return func(ctx *postProcessCtx, node *html.Node) {
  873. ch := &html.Node{
  874. Parent: node,
  875. Type: html.TextNode,
  876. Data: node.Data,
  877. }
  878. node.Type = html.ElementNode
  879. node.Data = "a"
  880. node.DataAtom = atom.A
  881. node.Attr = []html.Attribute{
  882. {Key: "href", Val: defaultLink},
  883. {Key: "class", Val: "default-link"},
  884. }
  885. node.FirstChild, node.LastChild = ch, ch
  886. }
  887. }
  888. // descriptionLinkProcessor creates links for DescriptionHTML
  889. func descriptionLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  890. m := common.LinkRegex.FindStringIndex(node.Data)
  891. if m == nil {
  892. return
  893. }
  894. uri := node.Data[m[0]:m[1]]
  895. replaceContent(node, m[0], m[1], createDescriptionLink(uri, uri))
  896. }
  897. func createDescriptionLink(href, content string) *html.Node {
  898. textNode := &html.Node{
  899. Type: html.TextNode,
  900. Data: content,
  901. }
  902. linkNode := &html.Node{
  903. FirstChild: textNode,
  904. LastChild: textNode,
  905. Type: html.ElementNode,
  906. Data: "a",
  907. DataAtom: atom.A,
  908. Attr: []html.Attribute{
  909. {Key: "href", Val: href},
  910. {Key: "target", Val: "_blank"},
  911. {Key: "rel", Val: "noopener noreferrer"},
  912. },
  913. }
  914. textNode.Parent = linkNode
  915. return linkNode
  916. }