diff --git a/less/core.less b/less/core.less index 80b2b22..8f6df46 100644 --- a/less/core.less +++ b/less/core.less @@ -1,1458 +1,1473 @@ @primary: rgb(114, 120, 191); @secondary: rgb(114, 191, 133); @subheaders: #444; @headerTextColor: black; @sansFont: 'Open Sans', 'Segoe UI', Tahoma, Arial, sans-serif; @serifFont: Lora, 'Palatino Linotype', 'Book Antiqua', 'New York', 'DejaVu serif', serif; @monoFont: Hack, consolas, Menlo-Regular, Menlo, Monaco, 'ubuntu mono', monospace, monospace; @dangerCol: #e21d27; @errUrgentCol: #ecc63c; @proSelectedCol: #71D571; @textLinkColor: rgb(0, 0, 238); body { font-family: @serifFont; font-size-adjust: 0.5; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #111; - h1 { + h1, header h2 { a { color: @headerTextColor; .transition-duration(0.2s); &:hover { color: #303030; text-decoration: none; } } } h1, h2, h3 { line-height: 1.2; } &#post article, &#collection article p, &#subpage article p { display: block; unicode-bidi: embed; white-space: pre; } &#post { #wrapper, pre { max-width: 40em; margin: 0 auto; a:hover { text-decoration: underline; } } article { margin-bottom: 2em !important; h1, h2, h3, h4, h5, h6, p, ul, ol, code { display: inline; margin: 0; } hr + p, ol, ul { display: block; margin-top: -1em; margin-bottom: -1em; } ol, ul { margin: 0.75em 0 -1em; } ul { padding: 0 0 0 2em; } li { margin-top: -0.5em; margin-bottom: -0.5em; } h2#title { .article-title; } h1 { font-size: 1.5em; } h2 { font-size: 1.17em; } } header { nav { span, a { &.pinned { &.selected { font-weight: bold; } &+.views { margin-left: 2em; } } } } } .owner-visible { display: none; } } &#post, &#collection, &#subpage { code { .article-code; } img, video { max-width: 100%; } pre { .code-block; code { background: transparent; border: 0; padding: 0; font-size: 1em; white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } } blockquote { .article-blockquote; } article { hr { margin-top: 0; margin-bottom: 0; } p.badge { background-color: #aaa; display: inline-block; padding: 0.25em 0.5em; margin: 0; float: right; color: white; .rounded(.25em); } } header { nav { span, a { &.pinned { &+.pinned { margin-left: 1.5em; } } } } } footer { nav { a { margin-top: 0; } } } } &#collection { #welcome, .access { margin: 0 auto; max-width: 35em; h2 { font-weight: normal; margin-bottom: 1em; } p { font-size: 1.2em; line-height: 1.6; } } .access { margin: 8em auto; text-align: center; h2, ul.errors { font-size: 1.2em; margin-bottom: 1.5em !important; } } header { padding: 0 1em; text-align: center; max-width: 50em; margin: 3em auto 4em; .writeas-prefix { a { color: #aaa; } display: block; margin-bottom: 0.5em; } nav { display: block; margin: 1em 0; a:first-child { margin: 0; } } } nav#manage { position: absolute; top: 1em; left: 1.5em; li a.write { font-family: @serifFont; padding-top: 0.2em; padding-bottom: 0.2em; } } pre { line-height: 1.5; } } &#subpage { #wrapper { h1 { font-size: 2.5em; letter-spacing: -2px; padding: 0 2rem 2rem; } } } &#post { pre { font-size: 0.75em; } } &#collection, &#subpage { #wrapper { margin-left: auto; margin-right: auto; article { margin-bottom: 4em; &:hover { .hidden { .opacity(1); } } } h2 { margin-top: 0em; margin-bottom: 0.25em; &+time { display: block; } } time { font-size: 1.1em; &+p { margin-top: 0.25em; } } footer { text-align: left; padding: 0; } } #paging { overflow: visible; padding: 1em 6em 0; } a.read-more { color: #666; } } &#me #official-writing { h2 { font-weight: normal; a { font-size: 0.6em; margin-left: 1em; } a[name] { margin-left: 0; } a:link, a:visited { color: @textLinkColor; } a:hover { text-decoration: underline; } } } &#promo { div.heading { margin: 8em 0; } div.heading, div.attention-form { h1 { font-size: 3.5em; } input { padding-left: 0.75em; padding-right: 0.75em; &[type=email] { max-width: 16em; } &[type=submit] { padding-left: 1.5em; padding-right: 1.5em; } } } h2 { margin-bottom: 0; font-size: 1.8em; font-weight: normal; span.write-as { color: black; } &.soon { color: lighten(@subheaders, 50%); span { &.write-as { color: lighten(#000, 50%); } &.note { color: lighten(#333, 50%); font-variant: small-caps; margin-left: 0.5em; } } } } .half-col a { margin-left: 1em; margin-right: 1em; } } nav#top-nav { display: inline; position: absolute; top: 1.5em; right: 1.5em; font-size: 0.95rem; font-family: @sansFont; text-transform: uppercase; a { color: #777; } a + a { margin-left: 1em; } } footer { nav, ul { a { display: inline-block; margin-top: 0.8em; .transition-duration(0.1s); text-decoration: none; + a { margin-left: 0.8em; } &:link, &:visited { color: #999; } &:hover { color: #666; text-decoration: none; } } } a.home { &:link, &:visited { color: #333; } font-weight: bold; text-decoration: none; &:hover { color: #000; } } ul { list-style: none; text-align: left; padding-left: 0 !important; margin-left: 0 !important; .icons img { height: 16px; width: 16px; fill: #999; } } } } .post-title { a { &:link { color: #333; } &:visited { color: #444; } } time, time a:link, time a:visited, &+.time { color: #999; } } .hidden { -moz-transition-property: opacity; -webkit-transition-property: opacity; -o-transition-property: opacity; transition-property: opacity; .transition-duration(0.4s); .opacity(0); } a { text-decoration: none; &:hover { text-decoration: underline; } &.subdued { color: #999; &:hover { border-bottom: 1px solid #999; text-decoration: none; } } &.danger { color: @dangerCol; font-size: 0.86em; } &.simple-cta { text-decoration: none; border-bottom: 1px solid #ccc; color: #333; padding-bottom: 2px; &:hover { text-decoration: none; } } &.action-btn { font-family: @sansFont; text-transform: uppercase; .rounded(.25em); background-color: red; color: white; font-weight: bold; padding: 0.5em 0.75em; &:hover { background-color: lighten(#f00, 5%); text-decoration: none; } } &.hashtag:hover { text-decoration: none; span + span { text-decoration: underline; } } &.hashtag { span:first-child { color: #999; margin-right: 0.1em; font-size: 0.86em; text-decoration: none; } } } abbr { border-bottom: 1px dotted #999; text-decoration: none; cursor: help; } body#collection article p, body#subpage article p { .article-p; } pre, body#post article, body#collection article, body#subpage article, body#subpage #wrapper h1 { max-width: 40rem; margin: 0 auto; } textarea, pre, body#post article, body#collection article p { &.norm, &.sans, &.wrap { line-height: 1.4em; white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } } textarea, pre, body#post article, body#collection article, body#subpage article, span, .font { &.norm { font-family: @serifFont; } &.sans { font-family: @sansFont; } &.mono, &.wrap, &.code { font-family: @monoFont; } &.mono, &.code { max-width: none !important; } } textarea { &.section { border: 1px solid #ccc; padding: 0.65em 0.75em; .rounded(.25em); &.codable { height: 12em; resize: vertical; } } } .ace_editor { height: 12em; border: 1px solid #333; max-width: initial; width: 100%; font-size: 0.86em !important; border: 1px solid #ccc; padding: 0.65em 0.75em; margin: 0; .rounded(.25em); } p { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; &.intro { font-size: 1.25em; text-align: center; } &.upgrade-prompt { font-size: 0.9em; color: #444; } &.text-cta { font-size: 1.2em; text-align: center; margin-bottom: 0.5em; &+ p { text-align: center; font-size: 0.7em; margin-top: 0; color: #666; } } &.error { font-style: italic; color: @errUrgentCol; } &.headeresque { font-size: 2em; } } table.classy { width: 95%; border-collapse: collapse; margin-bottom: 2em; tr + tr { border-top: 1px solid #ccc; } th { text-transform: uppercase; font-weight: normal; font-size: 95%; font-family: @sansFont; padding: 1rem 0.75rem; text-align: center; } td { height: 3.5rem; } p { margin-top: 0 !important; margin-bottom: 0 !important; } &.export { .disabled { color: #999; } .disabled, a { text-transform: lowercase; } } } body#collection article, body#subpage article { padding-top: 0; padding-bottom: 0; .book { a.hidden.action { color: #666; float: right; font-size: 1em; margin-left: 1em; margin-bottom: 1em; } } } body#post article { p.badge { font-size: 0.9em; } } article { h2.post-title a[rel=nofollow]::after { content: '\a0 \2934'; } } table.downloads { width: 100%; td { text-align: center; } img.os { width: 48px; vertical-align: middle; margin-bottom: 6px; } } select.inputform, textarea.inputform { border: 1px solid #999; } input, button, select.inputform, textarea.inputform { padding: 0.5em; font-family: @serifFont; font-size: 100%; .rounded(.25em); &[type=submit], &.submit { border: 1px solid @primary; background: @primary; color: white; .transition(0.2s); &:hover { background-color: lighten(@primary, 3%); } &:disabled { cursor: default; background-color: desaturate(@primary, 100%) !important; border-color: desaturate(@primary, 100%) !important; } } &.error[type=text], textarea.error { -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; -o-transition: all 0.30s ease-in-out; outline: none; } &.danger { border: 1px solid @dangerCol; background: @dangerCol; color: white; &:hover { background-color: lighten(@dangerCol, 3%); } } &.error[type=text]:focus, textarea.error:focus { box-shadow: 0 0 5px @errUrgentCol; border: 1px solid @errUrgentCol; } } div.flat-select { display: inline-block; position: relative; select { border: 0; background: 0; -webkit-appearance: none; -moz-appearance: none; appearance: none; position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; opacity: 0; } &.action { &:hover { label { text-decoration: underline; } } label, select { cursor: pointer; } } } input { &.underline{ border: none; border-bottom: 1px solid #ccc; padding: 0 .2em .2em; font-size: 0.9em; color: #333; } &.inline { padding: 0.2rem 0.2rem; margin-left: 0; font-size: 1em; border: 0 !important; border-bottom: 1px solid #999 !important; width: 7em; .rounded(0); } &[type=tel], &[type=text], &[type=email], &[type=password] { border: 1px solid #999; } &.boxy { border: 1px solid #999 !important; } } #beta, .content-container { max-width: 50em; margin: 0 auto 3em; font-size: 1.2em; &.tight { max-width: 30em; } &.snug { max-width: 40em; } &.regular { font-size: 1em; } .app { + .app { margin-top: 1.5em; } h2 { margin-bottom: 0.25em; } p { margin-top: 0.25em; } } h2.intro { font-weight: normal; } p { line-height: 1.4; } li { margin: 0.3em 0; } h2 { &.light { font-weight: normal; } a { .transition-duration(0.2s); -moz-transition-property: color; -webkit-transition-property: color; -o-transition-property: color; transition-property: color; &:link, &:visited, &:hover { color: @subheaders; } &:hover { color: lighten(@subheaders, 10%); text-decoration: none; } } } } .content-container { &#pricing { button { cursor: pointer; color: white; margin-top: 1em; margin-bottom: 1em; padding-left: 1.5em; padding-right: 1.5em; border: 0; background: @primary; .rounded(.25em); .transition(0.2s); &:hover { background-color: lighten(@primary, 5%); } &.unselected { cursor: pointer; } } h2 span { font-weight: normal; } .half { margin: 0 0 1em 0; text-align: center; } } div.features { margin-top: 1.5em; text-align: center; font-size: 0.86em; ul { text-align: left; max-width: 26em; margin-left: auto !important; margin-right: auto !important; li.soon, span.soon { color: lighten(#111, 40%); } } } div.blurbs { >h2 { text-align: center; color: #333; font-weight: normal; } p.price { font-size: 1.2em; margin-bottom: 0; color: #333; margin-top: 0.5em; &+p { margin-top: 0; font-size: 0.8em; } } p.text-cta { font-size: 1em; } } } footer div.blurbs { display: flex; flex-flow: row; flex-wrap: wrap; } div.blurbs { .half, .third, .fourth { font-size: 0.86em; h3 { font-weight: normal; } p, ul { color: #595959; } hr { margin: 1em 0; } } .half { padding: 0 1em 0 0; width: ~"calc(50% - 1em)"; &+.half { padding: 0 0 0 1em; } } .third { padding: 0; width: ~"calc(33% - 1em)"; &+.third { padding: 0 0 0 1em; } } .fourth { flex: 1 1 25%; -webkit-flex: 1 1 25%; h3 { margin-bottom: 0.5em; } ul { margin-top: 0.5em; } } } .contain-me { text-align: left; margin: 0 auto 4em; max-width: 50em; h2 + p, h2 + p + p, p.describe-me { margin-left: 1.5em; margin-right: 1.5em; color: #333; } } footer.contain-me { font-size: 1.1em; } #official-writing, #wrapper { h2, h3, h4 { color: @subheaders; } ul { &.collections { margin-left: 0; li { &.collection { a.title { &:link, &:visited { color: @headerTextColor; } } } a.create { color: #444; } } & + p { margin-top: 2em; margin-left: 1em; } } } } #official-writing, #wrapper { h2 { &.major { color: #222; } &.bugfix { color: #666; } +.android-version { a { color: #999; &:hover { text-decoration: underline; } } } } } li { line-height: 1.4; .item-desc, .prog-lang { font-size: 0.6em; font-family: 'Open Sans', sans-serif; font-weight: bold; margin-left: 0.5em; margin-right: 0.5em; text-transform: uppercase; color: #999; } } .success { color: darken(@proSelectedCol, 20%); } .alert { padding: 1em; margin-bottom: 1.25em; border: 1px solid transparent; .rounded(.25em); &.info { color: #31708f; background-color: #d9edf7; border-color: #bce8f1; } &.success { color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6; } p { margin: 0; &+p { margin-top: 0.5em; } } p.dismiss { font-family: @sansFont; text-align: right; font-size: 0.86em; text-transform: uppercase; } } ul.errors { padding: 0; text-indent: 0; li.urgent { list-style: none; font-style: italic; text-align: center; color: @errUrgentCol; a:link, a:visited { color: purple; } } li.info { list-style: none; font-size: 1.1em; text-align: center; } } body#pad #target a.upgrade-prompt { padding-left: 1em; padding-right: 1em; text-align: center; font-style: italic; color: @primary; } body#pad-sub #posts, .atoms { margin-top: 1.5em; h3 { margin-bottom: 0.25em; &+ h4 { margin-top: 0.25em; margin-bottom: 0.5em; &+ p { margin-top: 0.5em; } } .electron { font-weight: normal; margin-left: 0.5em; } } h3, h4 { a { .transition-duration(0.2s); -moz-transition-property: color; -webkit-transition-property: color; -o-transition-property: color; transition-property: color; } } h4 { font-size: 0.9em; font-weight: normal; } date, .electron { margin-right: 0.5em; } .action { font-size: 1em; } #more-posts p { text-align: center; font-size: 1.1em; } p { font-size: 0.86em; } .error { display: inline-block; font-size: 0.8em; font-style: italic; color: @errUrgentCol; strong { font-style: normal; } } .error + nav { display: inline-block; font-size: 0.8em; margin-left: 1em; a + a { margin-left: 0.75em; } } } h2 { a, time { &+.action { margin-left: 0.5em; } } } .action { font-size: 0.7em; font-weight: normal; font-family: @serifFont; &+ .action { margin-left: 0.5em; } &.new-post { font-weight: bold; } } article.moved { p { font-size: 1.2em; color: #999; } } span.as { .opacity(0.2); font-weight: normal; } span.ras { .opacity(0.6); font-weight: normal; } header { nav { .username { font-size: 2em; font-weight: normal; color: #555; } &#user-nav { margin-left: 0; & > a, .tabs > a { &.selected { cursor: default; font-weight: bold; &:hover { text-decoration: none; } } & + a { margin-left: 2em; } } a { font-size: 1.2em; font-family: @sansFont; span { font-size: 0.7em; color: #999; text-transform: uppercase; margin-left: 0.5em; margin-right: 0.5em; - &.pro { - color: @proSelectedCol; - } + } + &.title { + font-size: 1.6em; + font-family: @serifFont; + font-weight: bold; } } nav > ul > li:first-child { &> a { display: inline-block; } img { position: relative; top: -0.5em; right: 0.3em; } } ul ul { font-size: 0.8em; a { padding-top: 0.25em; padding-bottom: 0.25em; } } li { line-height: 1.5; } } &.tabs { + margin: 0 0 0 1em; + } + &+ nav.tabs { margin: 0; } } + &.singleuser { + margin: 0.5em 0.25em; + nav#user-nav { + nav > ul > li:first-child { + img { + top: -0.75em; + } + } + } + } .dash-nav { font-weight: bold; } } li#create-collection { display: none; h4 { margin-top: 0px; margin-bottom: 0px; } input[type=submit] { margin-left: 0.5em; } } #collection-options { .option { textarea { font-size: 0.86em; font-family: @monoFont; } .section > p.explain { font-size: 0.8em; } } } .img-placeholder { text-align: center; img { max-width: 100%; } } dl { &.admin-dl-horizontal { dt { font-weight: bolder; width: 360px; } dd { line-height: 1.5; } } } dt { float: left; clear: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } form { dt, dd { padding: 0.5rem 0; } dt { line-height: 1.8; } dd { font-size: 0.86em; line-height: 2; } } div.row { display: flex; align-items: center; > div { flex: 1; } } @media all and (max-width: 450px) { body#post { header { nav { .xtra-feature { display: none; } } } } } @media all and (min-width: 1280px) { body#promo { div.heading { margin: 10em 0; } } } @media all and (min-width: 1600px) { body#promo { div.heading { margin: 14em 0; } } } @media all and (max-width: 900px) { .half.big { padding: 0 !important; width: 100% !important; } .third { padding: 0 !important; float: none; width: 100% !important; p.introduction { font-size: 0.86em; } } div.blurbs { .fourth { flex: 1 1 15em; -webkit-flex: 1 1 15em; } } .blurbs .third, .blurbs .half { p, ul { text-align: left; } } .half-col, .big { float: none; text-align: center; &+.half-col, &+.big { margin-top: 4em !important; margin-left: 0; } } #beta, .content-container { font-size: 1.15em; } } @media all and (max-width: 600px) { div.row { flex-direction: column; } .half { padding: 0 !important; width: 100% !important; } .third { width: 100% !important; float: none; } body#promo { div.heading { margin: 6em 0; } h2 { font-size: 1.6em; } .half-col a + a { margin-left: 1em; } .half-col a.channel { margin-left: auto !important; margin-right: auto !important; } } ul.add-integrations { li { display: list-item; &+ li { margin-left: 0; } } } } @media all and (max-height: 500px) { body#promo { div.heading { margin: 5em 0; } } } @media all and (max-height: 400px) { body#promo { div.heading { margin: 0em 0; } } } /* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { header { .opacity(1); } } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { .content-container#pricing { .half { float: none; width: 100%; } } header { .opacity(1); } } /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { header { .opacity(1); } } @media (pointer: coarse) { body footer nav a:not(.pubd) { padding: 0.8em 1em; margin-left: 0; margin-top: 0; } } @media print { h1 { page-break-before: always; } h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } table, figure { page-break-inside: avoid; } header, footer { display: none; } article#post-body { margin-top: 2em; margin-left: 0; margin-right: 0; } hr { border: 1px solid #ccc; } } .code-block { padding: 0; max-width: 100%; margin: 0; background: #f8f8f8; border: 1px solid #ccc; padding: 0.375em 0.625em; font-size: 0.86em; .rounded(.25em); } pre.code-block { overflow-x: auto; } diff --git a/less/new-core.less b/less/new-core.less index 7c46203..802f34d 100644 --- a/less/new-core.less +++ b/less/new-core.less @@ -1,258 +1,258 @@ @actionNavColor: #999; body { margin: 0; padding: 0; font-size: 100%; footer { text-align: center; padding: 0 2em; nav { margin: 3em 0 4em; color: #444; a { text-decoration: none; + a { margin-left: 0.8em; } &:link, &:visited { color: #999; } &:hover { color: #666; } &.home { color: #333; font-weight: bold; &:hover { color: #000; } } } } } } header { margin: 1em; - h1 { + h1, h2 { display: inline; } nav { display: inline; margin: 0 1em; line-height: 2.4em; span, a { margin: 0 0 0 1em; } a { color: @actionNavColor; &:hover { text-decoration: underline; } } } p { &.description { color: #666; font-size: 1.1em; margin-top: 0.5em; line-height: 1.5; } &.meta-note { color: #333; font-style: italic; margin-top: 2em; span { text-transform: uppercase; font-variant: small-caps; font-size: 0.9em; color: #666; font-style: normal; } } } } hr { border: 0; height: 1px; background: #ccc; max-width: 40em; margin: 4em auto; text-align: center; } textarea, textarea:focus { border: 0; } textarea, textarea:focus, input { outline: 0; } textarea { width: 100%; resize: none; &#editor { position: fixed; top: 3em; right: 0; bottom: 2em; left: 0; padding: 2em 2em 0 2em; font-size: 2em; box-sizing: border-box; } } #official-writing, #wrapper { margin: 1em 2em; ul { margin: 0; padding: 0 0 0 1em; line-height: 1.4; &.collections, &.posts, &.integrations { list-style: none; margin-left: 1em; li + li { margin-top: 0.4em; } } &.collections li { &.collection { a.title { font-size: 1.3em; font-weight: bold; } } } } } .clearfix { overflow: auto; } .half-col, .half, .third { float: left; + .half-col { margin-left: 4em; } } .half { width: 50%; } .third { width: 33%; } code, textarea#embed { font-family: monospace, monospace; font-size: 1em; } #wrapper { max-width: 50em; } #official-writing, #wrapper { h2 { &.minor { font-size: 1.3em; } &.bugfix { font-size: 1.15em; } +.android-version { margin-top: 0; font-size: 1.1em; a { &:hover { text-decoration: underline; } } } } } #beta, .content-container { max-width: 50em; margin: 0 auto 3em; font-size: 1.2em; &.tight { max-width: 30em; } &.snug { max-width: 40em; } .app { + .app { margin-top: 1.5em; } h2 { margin-bottom: 0.25em; } p { margin-top: 0.25em; } } h2.intro { font-weight: normal; } p { line-height: 1.4; } li { margin: 0.3em 0; } h2 { &.light { font-weight: normal; } } } #collection-options { #title, #description { width: 100%; box-sizing: border-box; } .option { h2 { margin-top: 2em; margin-bottom: 0.5em; } label { &.option-text.disabled { color: #999; #domain-alias { border-color: #ccc; } &+p { color: #555; } } } label+p, p.describe { font-size: 0.8em; margin-top: 0.4em; margin-left: 1.8em; } input.low-profile { padding: 0.25rem 0.5rem; margin-left: 0.25rem; font-size: 0.8em; } .fedi-handle { margin-left: 0.5em; .transition-duration(0.25s); } } } diff --git a/nodeinfo.go b/nodeinfo.go index b2c58fa..fd4b445 100644 --- a/nodeinfo.go +++ b/nodeinfo.go @@ -1,89 +1,97 @@ package writefreely import ( "github.com/writeas/go-nodeinfo" "github.com/writeas/web-core/log" "github.com/writeas/writefreely/config" "strings" ) type nodeInfoResolver struct { cfg *config.Config db *datastore } -func nodeInfoConfig(cfg *config.Config) *nodeinfo.Config { +func nodeInfoConfig(db *datastore, cfg *config.Config) *nodeinfo.Config { name := cfg.App.SiteName + desc := "Minimal, federated blogging platform." + if cfg.App.SingleUser { + // Fetch blog information, instead + coll, err := db.GetCollectionByID(1) + if err == nil { + desc = coll.Description + } + } return &nodeinfo.Config{ BaseURL: cfg.App.Host, InfoURL: "/api/nodeinfo", Metadata: nodeinfo.Metadata{ NodeName: name, - NodeDescription: "Minimal, federated blogging platform.", + NodeDescription: desc, Private: cfg.App.Private, Software: nodeinfo.SoftwareMeta{ HomePage: softwareURL, GitHub: "https://github.com/writeas/writefreely", Follow: "https://writing.exchange/@write_as", }, }, Protocols: []nodeinfo.NodeProtocol{ nodeinfo.ProtocolActivityPub, }, Services: nodeinfo.Services{ Inbound: []nodeinfo.NodeService{}, Outbound: []nodeinfo.NodeService{ nodeinfo.ServiceRSS, }, }, Software: nodeinfo.SoftwareInfo{ Name: strings.ToLower(serverSoftware), Version: softwareVer, }, } } func (r nodeInfoResolver) IsOpenRegistration() (bool, error) { return r.cfg.App.OpenRegistration, nil } func (r nodeInfoResolver) Usage() (nodeinfo.Usage, error) { var collCount, postCount, activeHalfYear, activeMonth int err := r.db.QueryRow(`SELECT COUNT(*) FROM collections`).Scan(&collCount) if err != nil { collCount = 0 } err = r.db.QueryRow(`SELECT COUNT(*) FROM posts`).Scan(&postCount) if err != nil { log.Error("Unable to fetch post counts: %v", err) } if r.cfg.App.PublicStats { // Display bi-yearly / monthly stats err = r.db.QueryRow(`SELECT COUNT(*) FROM ( SELECT DISTINCT collection_id FROM posts INNER JOIN collections c ON collection_id = c.id WHERE collection_id IS NOT NULL AND updated > DATE_SUB(NOW(), INTERVAL 6 MONTH)) co`).Scan(&activeHalfYear) err = r.db.QueryRow(`SELECT COUNT(*) FROM ( SELECT DISTINCT collection_id FROM posts INNER JOIN FROM collections c ON collection_id = c.id WHERE collection_id IS NOT NULL AND updated > DATE_SUB(NOW(), INTERVAL 1 MONTH)) co`).Scan(&activeMonth) } return nodeinfo.Usage{ Users: nodeinfo.UsageUsers{ Total: collCount, ActiveHalfYear: activeHalfYear, ActiveMonth: activeMonth, }, LocalPosts: postCount, }, nil } diff --git a/pad.go b/pad.go index 6a04030..017b8e4 100644 --- a/pad.go +++ b/pad.go @@ -1,144 +1,153 @@ package writefreely import ( "github.com/gorilla/mux" "github.com/writeas/impart" "github.com/writeas/web-core/log" "github.com/writeas/writefreely/page" "net/http" "strings" ) func handleViewPad(app *app, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) action := vars["action"] slug := vars["slug"] collAlias := vars["collection"] + if app.cfg.App.SingleUser { + // TODO: refactor all of this, especially for single-user blogs + c, err := app.db.GetCollectionByID(1) + if err != nil { + return err + } + collAlias = c.Alias + } appData := &struct { page.StaticPage Post *RawPost User *User Blogs *[]Collection Editing bool // True if we're modifying an existing post EditCollection *Collection // Collection of the post we're editing, if any }{ StaticPage: pageForReq(app, r), Post: &RawPost{Font: "norm"}, User: getUserSession(app, r), } var err error if appData.User != nil { appData.Blogs, err = app.db.GetPublishableCollections(appData.User) if err != nil { log.Error("Unable to get user's blogs for Pad: %v", err) } } padTmpl := "pad" if action == "" && slug == "" { // Not editing any post; simply render the Pad if err = templates[padTmpl].ExecuteTemplate(w, "pad", appData); err != nil { log.Error("Unable to execute template: %v", err) } return nil } // Retrieve post information for editing appData.Editing = true // Make sure this isn't cached, so user doesn't accidentally lose data w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Header().Set("Expires", "Thu, 04 Oct 1990 20:00:00 GMT") if slug != "" { + // TODO: refactor all of this, especially for single-user blogs appData.Post = getRawCollectionPost(app, slug, collAlias) if appData.Post.OwnerID != appData.User.ID { // TODO: add ErrForbiddenEditPost message to flashes return impart.HTTPError{http.StatusFound, r.URL.Path[:strings.LastIndex(r.URL.Path, "/edit")]} } appData.EditCollection, err = app.db.GetCollectionForPad(collAlias) if err != nil { return err } } else { // Editing a floating article appData.Post = getRawPost(app, action) appData.Post.Id = action } if appData.Post.Gone { return ErrPostUnpublished } else if appData.Post.Found && appData.Post.Content != "" { // Got the post } else if appData.Post.Found { return ErrPostFetchError } else { return ErrPostNotFound } if err = templates[padTmpl].ExecuteTemplate(w, "pad", appData); err != nil { log.Error("Unable to execute template: %v", err) } return nil } func handleViewMeta(app *app, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) action := vars["action"] slug := vars["slug"] collAlias := vars["collection"] appData := &struct { page.StaticPage Post *RawPost User *User EditCollection *Collection // Collection of the post we're editing, if any Flashes []string NeedsToken bool }{ StaticPage: pageForReq(app, r), Post: &RawPost{Font: "norm"}, User: getUserSession(app, r), } var err error if action == "" && slug == "" { return ErrPostNotFound } // Make sure this isn't cached, so user doesn't accidentally lose data w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Header().Set("Expires", "Thu, 28 Jul 1989 12:00:00 GMT") if slug != "" { appData.Post = getRawCollectionPost(app, slug, collAlias) if appData.Post.OwnerID != appData.User.ID { // TODO: add ErrForbiddenEditPost message to flashes return impart.HTTPError{http.StatusFound, r.URL.Path[:strings.LastIndex(r.URL.Path, "/meta")]} } appData.EditCollection, err = app.db.GetCollectionForPad(collAlias) if err != nil { return err } } else { // Editing a floating article appData.Post = getRawPost(app, action) appData.Post.Id = action } appData.NeedsToken = appData.User == nil || appData.User.ID != appData.Post.OwnerID if appData.Post.Gone { return ErrPostUnpublished } else if appData.Post.Found && appData.Post.Content != "" { // Got the post } else if appData.Post.Found { return ErrPostFetchError } else { return ErrPostNotFound } appData.Flashes, _ = getSessionFlashes(app, w, r, nil) if err = templates["edit-meta"].ExecuteTemplate(w, "edit-meta", appData); err != nil { log.Error("Unable to execute template: %v", err) } return nil } diff --git a/pages/login.tmpl b/pages/login.tmpl index 411da50..9b58523 100644 --- a/pages/login.tmpl +++ b/pages/login.tmpl @@ -1,30 +1,30 @@ {{define "head"}}Log in — {{.SiteName}} - - + + {{end}} {{define "content"}}

Log in to {{.SiteName}}

{{if .Flashes}}{{end}}


{{if .To}}{{end}}
-

{{if .Message}}{{.Message}}{{else}}No account yet? Sign up to start a blog.{{end}}

+ {{if and (not .SingleUser) .OpenRegistration}}

{{if .Message}}{{.Message}}{{else}}No account yet? Sign up to start a blog.{{end}}

{{end}} {{end}} diff --git a/postrender.go b/postrender.go index 5348967..f739bdc 100644 --- a/postrender.go +++ b/postrender.go @@ -1,221 +1,221 @@ package writefreely import ( "bytes" "fmt" "github.com/microcosm-cc/bluemonday" stripmd "github.com/writeas/go-strip-markdown" "github.com/writeas/saturday" "github.com/writeas/web-core/stringmanip" "github.com/writeas/writefreely/parse" "html" "html/template" "regexp" "strings" "unicode" "unicode/utf8" ) var ( blockReg = regexp.MustCompile("<(ul|ol|blockquote)>\n") endBlockReg = regexp.MustCompile("\n") youtubeReg = regexp.MustCompile("(https?://www.youtube.com/embed/[a-zA-Z0-9\\-_]+)(\\?[^\t\n\f\r \"']+)?") titleElementReg = regexp.MustCompile("") hashtagReg = regexp.MustCompile(`#([\p{L}\p{M}\d]+)`) markeddownReg = regexp.MustCompile("

(.+)

") ) func (p *Post) formatContent(c *Collection, isOwner bool) { baseURL := c.CanonicalURL() - if isOwner { + if !isSingleUser { baseURL = "/" + c.Alias + "/" } newCon := hashtagReg.ReplaceAllFunc([]byte(p.Content), func(b []byte) []byte { // Ensure we only replace "hashtags" that have already been extracted. // `hashtagReg` catches everything, including any hash on the end of a // URL, so we rely on p.Tags as the final word on whether or not to link // a tag. for _, t := range p.Tags { if string(b) == "#"+t { return bytes.Replace(b, []byte("#"+t), []byte("#"+t+""), -1) } } return b }) p.HTMLTitle = template.HTML(applyBasicMarkdown([]byte(p.Title.String))) p.HTMLContent = template.HTML(applyMarkdown([]byte(newCon))) if exc := strings.Index(string(newCon), ""); exc > -1 { p.HTMLExcerpt = template.HTML(applyMarkdown([]byte(newCon[:exc]))) } } func (p *PublicPost) formatContent(isOwner bool) { p.Post.formatContent(&p.Collection.Collection, isOwner) } func applyMarkdown(data []byte) string { return applyMarkdownSpecial(data, false) } func applyMarkdownSpecial(data []byte, skipNoFollow bool) string { mdExtensions := 0 | blackfriday.EXTENSION_TABLES | blackfriday.EXTENSION_FENCED_CODE | blackfriday.EXTENSION_AUTOLINK | blackfriday.EXTENSION_STRIKETHROUGH | blackfriday.EXTENSION_SPACE_HEADERS | blackfriday.EXTENSION_AUTO_HEADER_IDS htmlFlags := 0 | blackfriday.HTML_USE_SMARTYPANTS | blackfriday.HTML_SMARTYPANTS_DASHES // Generate Markdown md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions) // Strip out bad HTML policy := getSanitizationPolicy() policy.RequireNoFollowOnLinks(!skipNoFollow) outHTML := string(policy.SanitizeBytes(md)) // Strip newlines on certain block elements that render with them outHTML = blockReg.ReplaceAllString(outHTML, "<$1>") outHTML = endBlockReg.ReplaceAllString(outHTML, "") // Remove all query parameters on YouTube embed links // TODO: make this more specific. Taking the nuclear approach here to strip ?autoplay=1 outHTML = youtubeReg.ReplaceAllString(outHTML, "$1") return outHTML } func applyBasicMarkdown(data []byte) string { mdExtensions := 0 | blackfriday.EXTENSION_STRIKETHROUGH | blackfriday.EXTENSION_SPACE_HEADERS | blackfriday.EXTENSION_HEADER_IDS htmlFlags := 0 | blackfriday.HTML_SKIP_HTML | blackfriday.HTML_USE_SMARTYPANTS | blackfriday.HTML_SMARTYPANTS_DASHES // Generate Markdown md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions) // Strip out bad HTML policy := bluemonday.UGCPolicy() policy.AllowAttrs("class", "id").Globally() outHTML := string(policy.SanitizeBytes(md)) outHTML = markeddownReg.ReplaceAllString(outHTML, "$1") outHTML = strings.TrimRightFunc(outHTML, unicode.IsSpace) return outHTML } func postTitle(content, friendlyId string) string { const maxTitleLen = 80 // Strip HTML tags with bluemonday's StrictPolicy, then unescape the HTML // entities added in by sanitizing the content. content = html.UnescapeString(bluemonday.StrictPolicy().Sanitize(content)) content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace) eol := strings.IndexRune(content, '\n') blankLine := strings.Index(content, "\n\n") if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen { return strings.TrimSpace(content[:blankLine]) } else if utf8.RuneCountInString(content) <= maxTitleLen { return content } return friendlyId } // TODO: fix duplicated code from postTitle. postTitle is a widely used func we // don't have time to investigate right now. func friendlyPostTitle(content, friendlyId string) string { const maxTitleLen = 80 // Strip HTML tags with bluemonday's StrictPolicy, then unescape the HTML // entities added in by sanitizing the content. content = html.UnescapeString(bluemonday.StrictPolicy().Sanitize(content)) content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace) eol := strings.IndexRune(content, '\n') blankLine := strings.Index(content, "\n\n") if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen { return strings.TrimSpace(content[:blankLine]) } else if eol == -1 && utf8.RuneCountInString(content) <= maxTitleLen { return content } title, truncd := parse.TruncToWord(parse.PostLede(content, true), maxTitleLen) if truncd { title += "..." } return title } func getSanitizationPolicy() *bluemonday.Policy { policy := bluemonday.UGCPolicy() policy.AllowAttrs("src", "style").OnElements("iframe", "video") policy.AllowAttrs("frameborder", "width", "height").Matching(bluemonday.Integer).OnElements("iframe") policy.AllowAttrs("allowfullscreen").OnElements("iframe") policy.AllowAttrs("controls", "loop", "muted", "autoplay").OnElements("video") policy.AllowAttrs("target").OnElements("a") policy.AllowAttrs("style", "class", "id").Globally() policy.AllowURLSchemes("http", "https", "mailto", "xmpp") return policy } func sanitizePost(content string) string { return strings.Replace(content, "<", "<", -1) } // postDescription generates a description based on the given post content, // title, and post ID. This doesn't consider a V2 post field, `title` when // choosing what to generate. In case a post has a title, this function will // fail, and logic should instead be implemented to skip this when there's no // title, like so: // var desc string // if title == "" { // desc = postDescription(content, title, friendlyId) // } else { // desc = shortPostDescription(content) // } func postDescription(content, title, friendlyId string) string { maxLen := 140 if content == "" { content = "Write Freely is a painless, simple, federated blogging platform." } else { fmtStr := "%s" truncation := 0 if utf8.RuneCountInString(content) > maxLen { // Post is longer than the max description, so let's show a better description fmtStr = "%s..." truncation = 3 } if title == friendlyId { // No specific title was found; simply truncate the post, starting at the beginning content = fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1)) } else { // There was a title, so return a real description blankLine := strings.Index(content, "\n\n") if blankLine < 0 { blankLine = 0 } truncd := stringmanip.Substring(content, blankLine, blankLine+maxLen-truncation) contentNoNL := strings.Replace(truncd, "\n", " ", -1) content = strings.TrimSpace(fmt.Sprintf(fmtStr, contentNoNL)) } } return content } func shortPostDescription(content string) string { maxLen := 140 fmtStr := "%s" truncation := 0 if utf8.RuneCountInString(content) > maxLen { // Post is longer than the max description, so let's show a better description fmtStr = "%s..." truncation = 3 } return strings.TrimSpace(fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1))) } diff --git a/posts.go b/posts.go index 72615c8..194481d 100644 --- a/posts.go +++ b/posts.go @@ -1,1334 +1,1336 @@ package writefreely import ( "database/sql" "encoding/json" "fmt" "github.com/gorilla/mux" "github.com/guregu/null" "github.com/guregu/null/zero" "github.com/kylemcc/twitter-text-go/extract" stripmd "github.com/writeas/go-strip-markdown" "github.com/writeas/impart" "github.com/writeas/monday" "github.com/writeas/slug" "github.com/writeas/web-core/activitystreams" "github.com/writeas/web-core/bots" "github.com/writeas/web-core/converter" "github.com/writeas/web-core/i18n" "github.com/writeas/web-core/log" "github.com/writeas/web-core/tags" "github.com/writeas/writefreely/page" "github.com/writeas/writefreely/parse" "html/template" "net/http" "regexp" "strings" "time" ) const ( // Post ID length bounds minIDLen = 10 maxIDLen = 10 userPostIDLen = 10 postIDLen = 10 postMetaDateFormat = "2006-01-02 15:04:05" ) type ( AnonymousPost struct { ID string Content string HTMLContent template.HTML Font string Language string Direction string Title string GenTitle string Description string Author string Views int64 IsPlainText bool IsCode bool IsLinkable bool } AuthenticatedPost struct { ID string `json:"id" schema:"id"` *SubmittedPost } // SubmittedPost represents a post supplied by a client for publishing or // updating. Since Title and Content can be updated to "", they are // pointers that can be easily tested to detect changes. SubmittedPost struct { Slug *string `json:"slug" schema:"slug"` Title *string `json:"title" schema:"title"` Content *string `json:"body" schema:"body"` Font string `json:"font" schema:"font"` IsRTL converter.NullJSONBool `json:"rtl" schema:"rtl"` Language converter.NullJSONString `json:"lang" schema:"lang"` Created *string `json:"created" schema:"created"` } // Post represents a post as found in the database. Post struct { ID string `db:"id" json:"id"` Slug null.String `db:"slug" json:"slug,omitempty"` Font string `db:"text_appearance" json:"appearance"` Language zero.String `db:"language" json:"language"` RTL zero.Bool `db:"rtl" json:"rtl"` Privacy int64 `db:"privacy" json:"-"` OwnerID null.Int `db:"owner_id" json:"-"` CollectionID null.Int `db:"collection_id" json:"-"` PinnedPosition null.Int `db:"pinned_position" json:"-"` Created time.Time `db:"created" json:"created"` Updated time.Time `db:"updated" json:"updated"` ViewCount int64 `db:"view_count" json:"-"` Title zero.String `db:"title" json:"title"` HTMLTitle template.HTML `db:"title" json:"-"` Content string `db:"content" json:"body"` HTMLContent template.HTML `db:"content" json:"-"` HTMLExcerpt template.HTML `db:"content" json:"-"` Tags []string `json:"tags"` Images []string `json:"images,omitempty"` OwnerName string `json:"owner,omitempty"` } // PublicPost holds properties for a publicly returned post, i.e. a post in // a context where the viewer may not be the owner. As such, sensitive // metadata for the post is hidden and properties supporting the display of // the post are added. PublicPost struct { *Post IsSubdomain bool `json:"-"` IsTopLevel bool `json:"-"` DisplayDate string `json:"-"` Views int64 `json:"views"` Owner *PublicUser `json:"-"` IsOwner bool `json:"-"` Collection *CollectionObj `json:"collection,omitempty"` } RawPost struct { Id, Slug string Title string Content string Views int64 Font string Created time.Time IsRTL sql.NullBool Language sql.NullString OwnerID int64 CollectionID sql.NullInt64 Found bool Gone bool } AnonymousAuthPost struct { ID string `json:"id"` Token string `json:"token"` } ClaimPostRequest struct { *AnonymousAuthPost CollectionAlias string `json:"collection"` CreateCollection bool `json:"create_collection"` // Generated properties Slug string `json:"-"` } ClaimPostResult struct { ID string `json:"id,omitempty"` Code int `json:"code,omitempty"` ErrorMessage string `json:"error_msg,omitempty"` Post *PublicPost `json:"post,omitempty"` } ) func (p *Post) Direction() string { if p.RTL.Valid { if p.RTL.Bool { return "rtl" } return "ltr" } return "auto" } // DisplayTitle dynamically generates a title from the Post's contents if it // doesn't already have an explicit title. func (p *Post) DisplayTitle() string { if p.Title.String != "" { return p.Title.String } t := friendlyPostTitle(p.Content, p.ID) return t } // PlainDisplayTitle dynamically generates a title from the Post's contents if it // doesn't already have an explicit title. func (p *Post) PlainDisplayTitle() string { if t := stripmd.Strip(p.DisplayTitle()); t != "" { return t } return p.ID } // FormattedDisplayTitle dynamically generates a title from the Post's contents if it // doesn't already have an explicit title. func (p *Post) FormattedDisplayTitle() template.HTML { if p.HTMLTitle != "" { return p.HTMLTitle } return template.HTML(p.DisplayTitle()) } // Summary gives a shortened summary of the post based on the post's title, // especially for display in a longer list of posts. It extracts a summary for // posts in the Title\n\nBody format, returning nothing if the entire was short // enough that the extracted title == extracted summary. func (p Post) Summary() string { if p.Content == "" { return "" } p.Content = stripmd.Strip(p.Content) title := p.Title.String var desc string if title == "" { // No title, so generate one title = friendlyPostTitle(p.Content, p.ID) desc = postDescription(p.Content, title, p.ID) if desc == title { return "" } return desc } return shortPostDescription(p.Content) } // Excerpt shows any text that comes before a (more) tag. // TODO: use HTMLExcerpt in templates instead of this method func (p *Post) Excerpt() template.HTML { return p.HTMLExcerpt } func (p *Post) CreatedDate() string { return p.Created.Format("2006-01-02") } func (p *Post) Created8601() string { return p.Created.Format("2006-01-02T15:04:05Z") } func (p *Post) IsScheduled() bool { return p.Created.After(time.Now()) } func (p *Post) HasTag(tag string) bool { // Regexp looks for tag and has a non-capturing group at the end looking // for the end of the word. // Assisted by: https://stackoverflow.com/a/35192941/1549194 hasTag, _ := regexp.MatchString("#"+tag+`(?:[[:punct:]]|\s|\z)`, p.Content) return hasTag } func (p *Post) HasTitleLink() bool { if p.Title.String == "" { return false } hasLink, _ := regexp.MatchString(`([^!]+|^)\[.+\]\(.+\)`, p.Title.String) return hasLink } func handleViewPost(app *app, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) friendlyID := vars["post"] isJSON := strings.HasSuffix(friendlyID, ".json") isXML := strings.HasSuffix(friendlyID, ".xml") isCSS := strings.HasSuffix(friendlyID, ".css") isMarkdown := strings.HasSuffix(friendlyID, ".md") isRaw := strings.HasSuffix(friendlyID, ".txt") || isJSON || isXML || isCSS || isMarkdown // Display reserved page if that is requested resource if t, ok := pages[r.URL.Path[1:]+".tmpl"]; ok { // Serve templated page err := t.ExecuteTemplate(w, "base", pageForReq(app, r)) if err != nil { log.Error("Unable to render page: %v", err) } return nil } else if (strings.Contains(r.URL.Path, ".") && !isRaw && !isMarkdown) || r.URL.Path == "/robots.txt" || r.URL.Path == "/manifest.json" { // Serve static file shttp.ServeHTTP(w, r) return nil } // Display collection if this is a collection c, _ := app.db.GetCollection(friendlyID) if c != nil { return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s/", friendlyID)} } // Normalize the URL, redirecting user to consistent post URL if friendlyID != strings.ToLower(friendlyID) { return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s", strings.ToLower(friendlyID))} } ext := "" if isRaw { parts := strings.Split(friendlyID, ".") friendlyID = parts[0] if len(parts) > 1 { ext = "." + parts[1] } } var ownerID sql.NullInt64 var title string var content string var font string var language []byte var rtl []byte var views int64 var post *AnonymousPost var found bool var gone bool fixedID := slug.Make(friendlyID) if fixedID != friendlyID { return impart.HTTPError{http.StatusFound, fmt.Sprintf("/%s%s", fixedID, ext)} } err := app.db.QueryRow(fmt.Sprintf("SELECT owner_id, title, content, text_appearance, view_count, language, rtl FROM posts WHERE id = ?"), friendlyID).Scan(&ownerID, &title, &content, &font, &views, &language, &rtl) switch { case err == sql.ErrNoRows: found = false // Output the error in the correct format if isJSON { content = "{\"error\": \"Post not found.\"}" } else if isRaw { content = "Post not found." } else { return ErrPostNotFound } case err != nil: found = false log.Error("Post loading err: %s\n", err) return ErrInternalGeneral default: found = true var d string if len(rtl) == 0 { d = "auto" } else if rtl[0] == 49 { // TODO: find a cleaner way to get this (possibly NULL) value d = "rtl" } else { d = "ltr" } generatedTitle := friendlyPostTitle(content, friendlyID) sanitizedContent := content if font != "code" { sanitizedContent = template.HTMLEscapeString(content) } var desc string if title == "" { desc = postDescription(content, title, friendlyID) } else { desc = shortPostDescription(content) } post = &AnonymousPost{ ID: friendlyID, Content: sanitizedContent, Title: title, GenTitle: generatedTitle, Description: desc, Author: "", Font: font, IsPlainText: isRaw, IsCode: font == "code", IsLinkable: font != "code", Views: views, Language: string(language), Direction: d, } if !isRaw { post.HTMLContent = template.HTML(applyMarkdown([]byte(content))) } } // Check if post has been unpublished if content == "" { gone = true if isJSON { content = "{\"error\": \"Post was unpublished.\"}" } else if isCSS { content = "" } else if isRaw { content = "Post was unpublished." } else { return ErrPostUnpublished } } var u = &User{} if isRaw { contentType := "text/plain" if isJSON { contentType = "application/json" } else if isCSS { contentType = "text/css" } else if isXML { contentType = "application/xml" } else if isMarkdown { contentType = "text/markdown" } w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType)) if isMarkdown && post.Title != "" { fmt.Fprintf(w, "%s\n", post.Title) for i := 1; i <= len(post.Title); i++ { fmt.Fprintf(w, "=") } fmt.Fprintf(w, "\n\n") } fmt.Fprint(w, content) if !found { return ErrPostNotFound } else if gone { return ErrPostUnpublished } } else { var err error page := struct { *AnonymousPost page.StaticPage Username string IsOwner bool SiteURL string }{ AnonymousPost: post, StaticPage: pageForReq(app, r), SiteURL: app.cfg.App.Host, } if u = getUserSession(app, r); u != nil { page.Username = u.Username page.IsOwner = ownerID.Valid && ownerID.Int64 == u.ID } err = templates["post"].ExecuteTemplate(w, "post", page) if err != nil { log.Error("Post template execute error: %v", err) } } go func() { if u != nil && ownerID.Valid && ownerID.Int64 == u.ID { // Post is owned by someone; skip view increment since that person is viewing this post. return } // Update stats for non-raw post views if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) { _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE id = ?", friendlyID) if err != nil { log.Error("Unable to update posts count: %v", err) } } }() return nil } // API v2 funcs // newPost creates a new post with or without an owning Collection. // // Endpoints: // /posts // /posts?collection={alias} // ? /collections/{alias}/posts func newPost(app *app, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r.Header.Get("Content-Type")) vars := mux.Vars(r) collAlias := vars["alias"] if collAlias == "" { collAlias = r.FormValue("collection") } accessToken := r.Header.Get("Authorization") if accessToken == "" { // TODO: remove this accessToken = r.FormValue("access_token") } // FIXME: determine web submission with Content-Type header var u *User var userID int64 = -1 var username string if accessToken == "" { u = getUserSession(app, r) if u != nil { userID = u.ID username = u.Username } } else { userID = app.db.GetUserID(accessToken) } if userID == -1 { return ErrNotLoggedIn } if accessToken == "" && u == nil && collAlias != "" { return impart.HTTPError{http.StatusBadRequest, "Parameter `access_token` required."} } // Get post data var p *SubmittedPost if reqJSON { decoder := json.NewDecoder(r.Body) err := decoder.Decode(&p) if err != nil { log.Error("Couldn't parse new post JSON request: %v\n", err) return ErrBadJSON } if p.Title == nil { t := "" p.Title = &t } if strings.TrimSpace(*(p.Content)) == "" { return ErrNoPublishableContent } } else { post := r.FormValue("body") appearance := r.FormValue("font") title := r.FormValue("title") rtlValue := r.FormValue("rtl") langValue := r.FormValue("lang") if strings.TrimSpace(post) == "" { return ErrNoPublishableContent } var isRTL, rtlValid bool if rtlValue == "auto" && langValue != "" { isRTL = i18n.LangIsRTL(langValue) rtlValid = true } else { isRTL = rtlValue == "true" rtlValid = rtlValue != "" && langValue != "" } // Create a new post p = &SubmittedPost{ Title: &title, Content: &post, Font: appearance, IsRTL: converter.NullJSONBool{sql.NullBool{Bool: isRTL, Valid: rtlValid}}, Language: converter.NullJSONString{sql.NullString{String: langValue, Valid: langValue != ""}}, } } if !p.isFontValid() { p.Font = "norm" } var newPost *PublicPost = &PublicPost{} var coll *Collection var collID int64 var err error if accessToken != "" { newPost, err = app.db.CreateOwnedPost(p, accessToken, collAlias) } else { //return ErrNotLoggedIn // TODO: verify user is logged in if collAlias != "" { coll, err = app.db.GetCollection(collAlias) if err != nil { return err } if coll.OwnerID != u.ID { return ErrForbiddenCollection } collID = coll.ID } // TODO: return PublicPost from createPost newPost.Post, err = app.db.CreatePost(userID, collID, p) } if err != nil { return err } if coll != nil { coll.ForPublic() newPost.Collection = &CollectionObj{Collection: *coll} } newPost.extractData() newPost.OwnerName = username // Write success now response := impart.WriteSuccess(w, newPost, http.StatusCreated) if coll != nil && app.cfg.App.Federation { go federatePost(app, newPost, collID, false) } return response } func existingPost(app *app, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r.Header.Get("Content-Type")) vars := mux.Vars(r) postID := vars["post"] p := AuthenticatedPost{ID: postID} var err error if reqJSON { // Decode JSON request decoder := json.NewDecoder(r.Body) err = decoder.Decode(&p) if err != nil { log.Error("Couldn't parse post update JSON request: %v\n", err) return ErrBadJSON } } else { err = r.ParseForm() if err != nil { log.Error("Couldn't parse post update form request: %v\n", err) return ErrBadFormData } // Can't decode to a nil SubmittedPost property, so create instance now p.SubmittedPost = &SubmittedPost{} err = app.formDecoder.Decode(&p, r.PostForm) if err != nil { log.Error("Couldn't decode post update form request: %v\n", err) return ErrBadFormData } } if p.SubmittedPost == nil { return ErrPostNoUpdatableVals } // Ensure an access token was given accessToken := r.Header.Get("Authorization") // Get user's cookie session if there's no token var u *User //var username string if accessToken == "" { u = getUserSession(app, r) if u != nil { //username = u.Username } } if u == nil && accessToken == "" { return ErrNoAccessToken } // Get user ID from current session or given access token, if one was given. var userID int64 if u != nil { userID = u.ID } else if accessToken != "" { userID, err = AuthenticateUser(app.db, accessToken) if err != nil { return err } } // Modify post struct p.ID = postID err = app.db.UpdateOwnedPost(&p, userID) if err != nil { if reqJSON { return err } if err, ok := err.(impart.HTTPError); ok { addSessionFlash(app, w, r, err.Message, nil) } else { addSessionFlash(app, w, r, err.Error(), nil) } } var pRes *PublicPost pRes, err = app.db.GetPost(p.ID, 0) if reqJSON { if err != nil { return err } pRes.extractData() } if pRes.CollectionID.Valid { coll, err := app.db.GetCollectionBy("id = ?", pRes.CollectionID.Int64) if err == nil && app.cfg.App.Federation { pRes.Collection = &CollectionObj{Collection: *coll} go federatePost(app, pRes, pRes.Collection.ID, true) } } // Write success now if reqJSON { return impart.WriteSuccess(w, pRes, http.StatusOK) } addSessionFlash(app, w, r, "Changes saved.", nil) collectionAlias := vars["alias"] redirect := "/" + postID + "/meta" if collectionAlias != "" { redirect = "/" + collectionAlias + "/" + pRes.Slug.String + "/edit/meta" } w.Header().Set("Location", redirect) w.WriteHeader(http.StatusFound) return nil } func deletePost(app *app, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) friendlyID := vars["post"] editToken := r.FormValue("token") var ownerID int64 var u *User accessToken := r.Header.Get("Authorization") if accessToken == "" && editToken == "" { u = getUserSession(app, r) if u == nil { return ErrNoAccessToken } } var res sql.Result var t *sql.Tx var err error var collID sql.NullInt64 var coll *Collection var pp *PublicPost if accessToken != "" || u != nil { // Caller provided some way to authenticate; assume caller expects the // post to be deleted based on a specific post owner, thus we should // return corresponding errors. if accessToken != "" { ownerID = app.db.GetUserID(accessToken) if ownerID == -1 { return ErrBadAccessToken } } else { ownerID = u.ID } // TODO: don't make two queries var realOwnerID sql.NullInt64 err = app.db.QueryRow("SELECT collection_id, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&collID, &realOwnerID) if err != nil { return err } if !collID.Valid { // There's no collection; simply delete the post res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID) } else { // Post belongs to a collection; do any additional clean up coll, err = app.db.GetCollectionBy("id = ?", collID.Int64) if err != nil { log.Error("Unable to get collection: %v", err) return err } if app.cfg.App.Federation { // First fetch full post for federation pp, err = app.db.GetOwnedPost(friendlyID, ownerID) if err != nil { log.Error("Unable to get owned post: %v", err) return err } collObj := &CollectionObj{Collection: *coll} pp.Collection = collObj } t, err = app.db.Begin() if err != nil { log.Error("No begin: %v", err) return err } res, err = t.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID) } } else { if editToken == "" { return impart.HTTPError{http.StatusBadRequest, "No authenticated user or post token given."} } // TODO: SELECT owner_id, as well, and return appropriate error if NULL instead of running two queries var dummy int64 err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ?", friendlyID).Scan(&dummy) switch { case err == sql.ErrNoRows: return impart.HTTPError{http.StatusNotFound, "Post not found."} } err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND owner_id IS NULL", friendlyID).Scan(&dummy) switch { case err == sql.ErrNoRows: // Post already has an owner. This could provide a bad experience // for the user, but it's more important to ensure data isn't lost // unexpectedly. So prevent deletion via token. return impart.HTTPError{http.StatusConflict, "This post belongs to some user (hopefully yours). Please log in and delete it from that user's account."} } res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND modify_token = ? AND owner_id IS NULL", friendlyID, editToken) } if err != nil { return err } affected, err := res.RowsAffected() if err != nil { if t != nil { t.Rollback() log.Error("Rows affected err! Rolling back") } return err } else if affected == 0 { if t != nil { t.Rollback() log.Error("No rows affected! Rolling back") } return impart.HTTPError{http.StatusForbidden, "Post not found, or you're not the owner."} } if t != nil { t.Commit() } if coll != nil && app.cfg.App.Federation { go deleteFederatedPost(app, pp, collID.Int64) } return impart.HTTPError{Status: http.StatusNoContent} } // addPost associates a post with the authenticated user. func addPost(app *app, w http.ResponseWriter, r *http.Request) error { var ownerID int64 // Authenticate user at := r.Header.Get("Authorization") if at != "" { ownerID = app.db.GetUserID(at) if ownerID == -1 { return ErrBadAccessToken } } else { u := getUserSession(app, r) if u == nil { return ErrNotLoggedIn } ownerID = u.ID } // Parse claimed posts in format: // [{"id": "...", "token": "..."}] var claims *[]ClaimPostRequest decoder := json.NewDecoder(r.Body) err := decoder.Decode(&claims) if err != nil { return ErrBadJSONArray } vars := mux.Vars(r) collAlias := vars["alias"] // Update all given posts res, err := app.db.ClaimPosts(ownerID, collAlias, claims) if err != nil { return err } return impart.WriteSuccess(w, res, http.StatusOK) } func dispersePost(app *app, w http.ResponseWriter, r *http.Request) error { var ownerID int64 // Authenticate user at := r.Header.Get("Authorization") if at != "" { ownerID = app.db.GetUserID(at) if ownerID == -1 { return ErrBadAccessToken } } else { u := getUserSession(app, r) if u == nil { return ErrNotLoggedIn } ownerID = u.ID } // Parse posts in format: // ["..."] var postIDs []string decoder := json.NewDecoder(r.Body) err := decoder.Decode(&postIDs) if err != nil { return ErrBadJSONArray } // Update all given posts res, err := app.db.DispersePosts(ownerID, postIDs) if err != nil { return err } return impart.WriteSuccess(w, res, http.StatusOK) } type ( PinPostResult struct { ID string `json:"id,omitempty"` Code int `json:"code,omitempty"` ErrorMessage string `json:"error_msg,omitempty"` } ) // pinPost pins a post to a blog func pinPost(app *app, w http.ResponseWriter, r *http.Request) error { var userID int64 // Authenticate user at := r.Header.Get("Authorization") if at != "" { userID = app.db.GetUserID(at) if userID == -1 { return ErrBadAccessToken } } else { u := getUserSession(app, r) if u == nil { return ErrNotLoggedIn } userID = u.ID } // Parse request var posts []struct { ID string `json:"id"` Position int64 `json:"position"` } decoder := json.NewDecoder(r.Body) err := decoder.Decode(&posts) if err != nil { return ErrBadJSONArray } // Validate data vars := mux.Vars(r) collAlias := vars["alias"] coll, err := app.db.GetCollection(collAlias) if err != nil { return err } if coll.OwnerID != userID { return ErrForbiddenCollection } // Do (un)pinning isPinning := r.URL.Path[strings.LastIndex(r.URL.Path, "/"):] == "/pin" res := []PinPostResult{} for _, p := range posts { err = app.db.UpdatePostPinState(isPinning, p.ID, coll.ID, userID, p.Position) ppr := PinPostResult{ID: p.ID} if err != nil { ppr.Code = http.StatusInternalServerError // TODO: set error messsage } else { ppr.Code = http.StatusOK } res = append(res, ppr) } return impart.WriteSuccess(w, res, http.StatusOK) } func fetchPost(app *app, w http.ResponseWriter, r *http.Request) error { var collID int64 vars := mux.Vars(r) if collAlias := vars["alias"]; collAlias != "" { // Fetch collection information, since an alias is provided coll, err := app.db.GetCollection(collAlias) if err != nil { return err } _, err = apiCheckCollectionPermissions(app, r, coll) if err != nil { return err } collID = coll.ID } p, err := app.db.GetPost(vars["post"], collID) if err != nil { return err } p.extractData() return impart.WriteSuccess(w, p, http.StatusOK) } func fetchPostProperty(app *app, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) p, err := app.db.GetPostProperty(vars["post"], 0, vars["property"]) if err != nil { return err } return impart.WriteSuccess(w, p, http.StatusOK) } func (p *Post) processPost() PublicPost { res := &PublicPost{Post: p, Views: 0} res.Views = p.ViewCount // TODO: move to own function loc := monday.FuzzyLocale(p.Language.String) res.DisplayDate = monday.Format(p.Created, monday.LongFormatsByLocale[loc], loc) return *res } func (p *PublicPost) CanonicalURL() string { if p.Collection == nil || p.Collection.Alias == "" { return hostName + "/" + p.ID } return p.Collection.CanonicalURL() + p.Slug.String } func (p *PublicPost) ActivityObject() *activitystreams.Object { o := activitystreams.NewArticleObject() o.ID = p.Collection.FederatedAPIBase() + "api/posts/" + p.ID o.Published = p.Created o.URL = p.CanonicalURL() o.AttributedTo = p.Collection.FederatedAccount() o.CC = []string{ p.Collection.FederatedAccount() + "/followers", } o.Name = p.DisplayTitle() if p.HTMLContent == template.HTML("") { p.formatContent(false) } o.Content = string(p.HTMLContent) if p.Language.Valid { o.ContentMap = map[string]string{ p.Language.String: string(p.HTMLContent), } } if len(p.Tags) == 0 { o.Tag = []activitystreams.Tag{} } else { var tagBaseURL string if isSingleUser { tagBaseURL = p.Collection.CanonicalURL() + "tag:" } else { tagBaseURL = fmt.Sprintf("%s/%s/tag:", hostName, p.Collection.Alias) } for _, t := range p.Tags { o.Tag = append(o.Tag, activitystreams.Tag{ Type: activitystreams.TagHashtag, HRef: tagBaseURL + t, Name: "#" + t, }) } } return o } // TODO: merge this into getSlugFromPost or phase it out func getSlug(title, lang string) string { return getSlugFromPost("", title, lang) } func getSlugFromPost(title, body, lang string) string { if title == "" { title = postTitle(body, body) } title = parse.PostLede(title, false) // Truncate lede if needed title, _ = parse.TruncToWord(title, 80) if lang != "" && len(lang) == 2 { return slug.MakeLang(title, lang) } return slug.Make(title) } // isFontValid returns whether or not the submitted post's appearance is valid. func (p *SubmittedPost) isFontValid() bool { validFonts := map[string]bool{ "norm": true, "sans": true, "mono": true, "wrap": true, "code": true, } _, valid := validFonts[p.Font] return valid } func getRawPost(app *app, friendlyID string) *RawPost { var content, font, title string var isRTL sql.NullBool var lang sql.NullString var ownerID sql.NullInt64 var created time.Time err := app.db.QueryRow("SELECT title, content, text_appearance, language, rtl, created, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&title, &content, &font, &lang, &isRTL, &created, &ownerID) switch { case err == sql.ErrNoRows: return &RawPost{Content: "", Found: false, Gone: false} case err != nil: return &RawPost{Content: "", Found: true, Gone: false} } return &RawPost{Title: title, Content: content, Font: font, Created: created, IsRTL: isRTL, Language: lang, OwnerID: ownerID.Int64, Found: true, Gone: content == ""} } // TODO; return a Post! func getRawCollectionPost(app *app, slug, collAlias string) *RawPost { var id, title, content, font string var isRTL sql.NullBool var lang sql.NullString var created time.Time var ownerID null.Int var views int64 err := app.db.QueryRow("SELECT id, title, content, text_appearance, language, rtl, view_count, created, owner_id FROM posts WHERE slug = ? AND collection_id = (SELECT id FROM collections WHERE alias = ?)", slug, collAlias).Scan(&id, &title, &content, &font, &lang, &isRTL, &views, &created, &ownerID) switch { case err == sql.ErrNoRows: return &RawPost{Content: "", Found: false, Gone: false} case err != nil: return &RawPost{Content: "", Found: true, Gone: false} } return &RawPost{ Id: id, Slug: slug, Title: title, Content: content, Font: font, Created: created, IsRTL: isRTL, Language: lang, OwnerID: ownerID.Int64, Found: true, Gone: content == "", Views: views, } } func viewCollectionPost(app *app, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) slug := vars["slug"] isJSON := strings.HasSuffix(slug, ".json") isXML := strings.HasSuffix(slug, ".xml") isMarkdown := strings.HasSuffix(slug, ".md") isRaw := strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown if strings.Contains(r.URL.Path, ".") && !isRaw { // Serve static file shttp.ServeHTTP(w, r) return nil } cr := &collectionReq{} err := processCollectionRequest(cr, vars, w, r) if err != nil { return err } // Check for hellbanned users u, err := checkUserForCollection(app, cr, r, true) if err != nil { return err } // Normalize the URL, redirecting user to consistent post URL if slug != strings.ToLower(slug) { loc := fmt.Sprintf("/%s", strings.ToLower(slug)) if !app.cfg.App.SingleUser { loc = "/" + cr.alias + loc } return impart.HTTPError{http.StatusMovedPermanently, loc} } // Display collection if this is a collection var c *Collection if app.cfg.App.SingleUser { c, err = app.db.GetCollectionByID(1) } else { c, err = app.db.GetCollection(cr.alias) } if err != nil { if err, ok := err.(impart.HTTPError); ok { if err.Status == http.StatusNotFound { // Redirect if necessary newAlias := app.db.GetCollectionRedirect(cr.alias) if newAlias != "" { return impart.HTTPError{http.StatusFound, "/" + newAlias + "/" + slug} } } } return err } // Check collection permissions if c.IsPrivate() && (u == nil || u.ID != c.OwnerID) { return ErrPostNotFound } if c.IsProtected() && ((u == nil || u.ID != c.OwnerID) && !isAuthorizedForCollection(app, c.Alias, r)) { return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/?g=" + slug} } cr.isCollOwner = u != nil && c.OwnerID == u.ID if isRaw { slug = strings.Split(slug, ".")[0] } // Fetch extra data about the Collection // TODO: refactor out this logic, shared in collection.go:fetchCollection() coll := &CollectionObj{Collection: *c} owner, err := app.db.GetUserByID(coll.OwnerID) if err != nil { // Log the error and just continue log.Error("Error getting user for collection: %v", err) } else { coll.Owner = owner } p, err := app.db.GetPost(slug, coll.ID) if err != nil { if err == ErrCollectionPageNotFound && slug == "feed" { // User tried to access blog feed without a trailing slash, and // there's no post with a slug "feed" return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/feed/"} } return err } p.IsOwner = owner != nil && p.OwnerID.Valid && owner.ID == p.OwnerID.Int64 p.Collection = coll p.IsTopLevel = app.cfg.App.SingleUser // Check if post has been unpublished if p.Content == "" { return impart.HTTPError{http.StatusGone, "Post was unpublished."} } // Serve collection post if isRaw { contentType := "text/plain" if isJSON { contentType = "application/json" } else if isXML { contentType = "application/xml" } else if isMarkdown { contentType = "text/markdown" } w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType)) if isMarkdown && p.Title.String != "" { fmt.Fprintf(w, "# %s\n\n", p.Title.String) } fmt.Fprint(w, p.Content) } else if strings.Contains(r.Header.Get("Accept"), "application/activity+json") { p.extractData() ap := p.ActivityObject() ap.Context = []interface{}{activitystreams.Namespace} return impart.RenderActivityJSON(w, ap, http.StatusOK) } else { p.extractData() p.Content = strings.Replace(p.Content, "", "", 1) // TODO: move this to function p.formatContent(cr.isCollOwner) tp := struct { *PublicPost + page.StaticPage IsOwner bool IsPinned bool IsCustomDomain bool PinnedPosts *[]PublicPost }{ PublicPost: p, + StaticPage: pageForReq(app, r), IsOwner: cr.isCollOwner, IsCustomDomain: cr.isCustomDomain, } tp.PinnedPosts, _ = app.db.GetPinnedPosts(coll) tp.IsPinned = len(*tp.PinnedPosts) > 0 && PostsContains(tp.PinnedPosts, p) if err := templates["collection-post"].ExecuteTemplate(w, "post", tp); err != nil { log.Error("Error in collection-post template: %v", err) } } go func() { if p.OwnerID.Valid { // Post is owned by someone. Don't update stats if owner is viewing the post. if u != nil && p.OwnerID.Int64 == u.ID { return } } // Update stats for non-raw post views if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) { _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE slug = ? AND collection_id = ?", slug, coll.ID) if err != nil { log.Error("Unable to update posts count: %v", err) } } }() return nil } // TODO: move this to utils after making it more generic func PostsContains(sl *[]PublicPost, s *PublicPost) bool { for _, e := range *sl { if e.ID == s.ID { return true } } return false } func (p *Post) extractData() { p.Tags = tags.Extract(p.Content) p.extractImages() } func (rp *RawPost) UserFacingCreated() string { return rp.Created.Format(postMetaDateFormat) } func (rp *RawPost) Created8601() string { return rp.Created.Format("2006-01-02T15:04:05Z") } var imageURLRegex = regexp.MustCompile(`(?i)^https?:\/\/[^ ]*\.(gif|png|jpg|jpeg)$`) func (p *Post) extractImages() { matches := extract.ExtractUrls(p.Content) urls := map[string]bool{} for i := range matches { u := matches[i].Text if !imageURLRegex.MatchString(u) { continue } urls[u] = true } resURLs := make([]string, 0) for k := range urls { resURLs = append(resURLs, k) } p.Images = resURLs } diff --git a/routes.go b/routes.go index 8900e80..21cbda4 100644 --- a/routes.go +++ b/routes.go @@ -1,154 +1,156 @@ package writefreely import ( "github.com/gorilla/mux" "github.com/writeas/go-nodeinfo" "github.com/writeas/go-webfinger" "github.com/writeas/web-core/log" "github.com/writeas/writefreely/config" "net/http" "strings" ) func initRoutes(handler *Handler, r *mux.Router, cfg *config.Config, db *datastore) { hostSubroute := cfg.App.Host[strings.Index(cfg.App.Host, "://")+3:] if cfg.App.SingleUser { hostSubroute = "{domain}" } else { if strings.HasPrefix(hostSubroute, "localhost") { hostSubroute = "localhost" } } if cfg.App.SingleUser { log.Info("Adding %s routes (single user)...", hostSubroute) } else { log.Info("Adding %s routes (multi-user)...", hostSubroute) } // Primary app routes write := r.PathPrefix("/").Subrouter() // Federation endpoint configurations wf := webfinger.Default(wfResolver{db, cfg}) wf.NoTLSHandler = nil // Federation endpoints // host-meta write.HandleFunc("/.well-known/host-meta", handler.Web(handleViewHostMeta, UserLevelOptional)) // webfinger write.HandleFunc(webfinger.WebFingerPath, handler.LogHandlerFunc(http.HandlerFunc(wf.Webfinger))) // nodeinfo - niCfg := nodeInfoConfig(cfg) + niCfg := nodeInfoConfig(db, cfg) ni := nodeinfo.NewService(*niCfg, nodeInfoResolver{cfg, db}) write.HandleFunc(nodeinfo.NodeInfoPath, handler.LogHandlerFunc(http.HandlerFunc(ni.NodeInfoDiscover))) write.HandleFunc(niCfg.InfoURL, handler.LogHandlerFunc(http.HandlerFunc(ni.NodeInfo))) // Set up dyamic page handlers // Handle auth auth := write.PathPrefix("/api/auth/").Subrouter() if cfg.App.OpenRegistration { auth.HandleFunc("/signup", handler.All(apiSignup)).Methods("POST") } auth.HandleFunc("/login", handler.All(login)).Methods("POST") auth.HandleFunc("/read", handler.WebErrors(handleWebCollectionUnlock, UserLevelNone)).Methods("POST") auth.HandleFunc("/me", handler.All(handleAPILogout)).Methods("DELETE") // Handle logged in user sections me := write.PathPrefix("/me").Subrouter() me.HandleFunc("/", handler.Redirect("/me", UserLevelUser)) me.HandleFunc("/c", handler.Redirect("/me/c/", UserLevelUser)).Methods("GET") me.HandleFunc("/c/", handler.User(viewCollections)).Methods("GET") me.HandleFunc("/c/{collection}", handler.User(viewEditCollection)).Methods("GET") me.HandleFunc("/c/{collection}/stats", handler.User(viewStats)).Methods("GET") me.HandleFunc("/posts", handler.Redirect("/me/posts/", UserLevelUser)).Methods("GET") me.HandleFunc("/posts/", handler.User(viewArticles)).Methods("GET") me.HandleFunc("/posts/export.csv", handler.Download(viewExportPosts, UserLevelUser)).Methods("GET") me.HandleFunc("/posts/export.zip", handler.Download(viewExportPosts, UserLevelUser)).Methods("GET") me.HandleFunc("/posts/export.json", handler.Download(viewExportPosts, UserLevelUser)).Methods("GET") me.HandleFunc("/export", handler.User(viewExportOptions)).Methods("GET") me.HandleFunc("/export.json", handler.Download(viewExportFull, UserLevelUser)).Methods("GET") me.HandleFunc("/settings", handler.User(viewSettings)).Methods("GET") me.HandleFunc("/logout", handler.Web(viewLogout, UserLevelNone)).Methods("GET") write.HandleFunc("/api/me", handler.All(viewMeAPI)).Methods("GET") apiMe := write.PathPrefix("/api/me/").Subrouter() apiMe.HandleFunc("/", handler.All(viewMeAPI)).Methods("GET") apiMe.HandleFunc("/posts", handler.UserAPI(viewMyPostsAPI)).Methods("GET") apiMe.HandleFunc("/collections", handler.UserAPI(viewMyCollectionsAPI)).Methods("GET") apiMe.HandleFunc("/password", handler.All(updatePassphrase)).Methods("POST") apiMe.HandleFunc("/self", handler.All(updateSettings)).Methods("POST") // Sign up validation write.HandleFunc("/api/alias", handler.All(handleUsernameCheck)).Methods("POST") // Handle collections write.HandleFunc("/api/collections", handler.All(newCollection)).Methods("POST") apiColls := write.PathPrefix("/api/collections/").Subrouter() apiColls.HandleFunc("/{alias:[0-9a-zA-Z\\-]+}", handler.All(fetchCollection)).Methods("GET") apiColls.HandleFunc("/{alias:[0-9a-zA-Z\\-]+}", handler.All(existingCollection)).Methods("POST", "DELETE") apiColls.HandleFunc("/{alias}/posts", handler.All(fetchCollectionPosts)).Methods("GET") apiColls.HandleFunc("/{alias}/posts", handler.All(newPost)).Methods("POST") apiColls.HandleFunc("/{alias}/posts/{post}", handler.All(fetchPost)).Methods("GET") apiColls.HandleFunc("/{alias}/posts/{post:[a-zA-Z0-9]{10}}", handler.All(existingPost)).Methods("POST") apiColls.HandleFunc("/{alias}/posts/{post}/{property}", handler.All(fetchPostProperty)).Methods("GET") apiColls.HandleFunc("/{alias}/collect", handler.All(addPost)).Methods("POST") apiColls.HandleFunc("/{alias}/pin", handler.All(pinPost)).Methods("POST") apiColls.HandleFunc("/{alias}/unpin", handler.All(pinPost)).Methods("POST") apiColls.HandleFunc("/{alias}/inbox", handler.All(handleFetchCollectionInbox)).Methods("POST") apiColls.HandleFunc("/{alias}/outbox", handler.All(handleFetchCollectionOutbox)).Methods("GET") apiColls.HandleFunc("/{alias}/following", handler.All(handleFetchCollectionFollowing)).Methods("GET") apiColls.HandleFunc("/{alias}/followers", handler.All(handleFetchCollectionFollowers)).Methods("GET") // Handle posts write.HandleFunc("/api/posts", handler.All(newPost)).Methods("POST") posts := write.PathPrefix("/api/posts/").Subrouter() posts.HandleFunc("/{post:[a-zA-Z0-9]{10}}", handler.All(fetchPost)).Methods("GET") posts.HandleFunc("/{post:[a-zA-Z0-9]{10}}", handler.All(existingPost)).Methods("POST", "PUT") posts.HandleFunc("/{post:[a-zA-Z0-9]{10}}", handler.All(deletePost)).Methods("DELETE") posts.HandleFunc("/{post:[a-zA-Z0-9]{10}}/{property}", handler.All(fetchPostProperty)).Methods("GET") posts.HandleFunc("/claim", handler.All(addPost)).Methods("POST") posts.HandleFunc("/disperse", handler.All(dispersePost)).Methods("POST") if cfg.App.OpenRegistration { write.HandleFunc("/auth/signup", handler.Web(handleWebSignup, UserLevelNoneRequired)).Methods("POST") } write.HandleFunc("/auth/login", handler.Web(webLogin, UserLevelNoneRequired)).Methods("POST") // Handle special pages first write.HandleFunc("/login", handler.Web(viewLogin, UserLevelNoneRequired)) + draftEditPrefix := "" if cfg.App.SingleUser { + draftEditPrefix = "/d" write.HandleFunc("/me/new", handler.Web(handleViewPad, UserLevelOptional)).Methods("GET") } else { write.HandleFunc("/new", handler.Web(handleViewPad, UserLevelOptional)).Methods("GET") } // All the existing stuff - write.HandleFunc("/{action}/edit", handler.Web(handleViewPad, UserLevelOptional)).Methods("GET") - write.HandleFunc("/{action}/meta", handler.Web(handleViewMeta, UserLevelOptional)).Methods("GET") + write.HandleFunc(draftEditPrefix+"/{action}/edit", handler.Web(handleViewPad, UserLevelOptional)).Methods("GET") + write.HandleFunc(draftEditPrefix+"/{action}/meta", handler.Web(handleViewMeta, UserLevelOptional)).Methods("GET") // Collections if cfg.App.SingleUser { RouteCollections(handler, write.PathPrefix("/").Subrouter()) } else { write.HandleFunc("/{prefix:[@~$!\\-+]}{collection}", handler.Web(handleViewCollection, UserLevelOptional)) write.HandleFunc("/{collection}/", handler.Web(handleViewCollection, UserLevelOptional)) RouteCollections(handler, write.PathPrefix("/{prefix:[@~$!\\-+]?}{collection}").Subrouter()) // Posts - write.HandleFunc("/{post}", handler.Web(handleViewPost, UserLevelOptional)) } + write.HandleFunc(draftEditPrefix+"/{post}", handler.Web(handleViewPost, UserLevelOptional)) write.HandleFunc("/", handler.Web(handleViewHome, UserLevelOptional)) } func RouteCollections(handler *Handler, r *mux.Router) { r.HandleFunc("/page/{page:[0-9]+}", handler.Web(handleViewCollection, UserLevelOptional)) r.HandleFunc("/tag:{tag}", handler.Web(handleViewCollectionTag, UserLevelOptional)) r.HandleFunc("/tag:{tag}/feed/", handler.Web(ViewFeed, UserLevelOptional)) r.HandleFunc("/tags/{tag}", handler.Web(handleViewCollectionTag, UserLevelOptional)) r.HandleFunc("/sitemap.xml", handler.All(handleViewSitemap)) r.HandleFunc("/feed/", handler.All(ViewFeed)) r.HandleFunc("/{slug}", handler.Web(viewCollectionPost, UserLevelOptional)) r.HandleFunc("/{slug}/edit", handler.Web(handleViewPad, UserLevelUser)) r.HandleFunc("/{slug}/edit/meta", handler.Web(handleViewMeta, UserLevelUser)) r.HandleFunc("/{slug}/", handler.Web(handleCollectionPostRedirect, UserLevelOptional)).Methods("GET") } diff --git a/static/js/postactions.js b/static/js/postactions.js index 93b8ef8..74e3223 100644 --- a/static/js/postactions.js +++ b/static/js/postactions.js @@ -1,105 +1,121 @@ var postActions = function() { var $container = He.get('moving'); - var MultiMove = function(el, id) { + var MultiMove = function(el, id, singleUser) { var lbl = el.options[el.selectedIndex].textContent; var collAlias = el.options[el.selectedIndex].value; var $lbl = He.$('label[for=move-'+id+']')[0]; $lbl.textContent = "moving to "+lbl+"..."; var params; if (collAlias == '|anonymous|') { params = [id]; } else { params = [{ id: id }]; } var callback = function(code, resp) { if (code == 200) { for (var i=0; i"; - var newPostURL = "/"+collAlias+"/"+resp.data[i].post.slug; + var pre = "/"+collAlias; + if (typeof singleUser !== 'undefined' && singleUser) { + pre = ""; + } + var newPostURL = pre+"/"+resp.data[i].post.slug; try { // Posts page He.$('#post-'+resp.data[i].post.id+' > h3 > a')[0].href = newPostURL; } catch (e) { // Blog index var $article = He.get('post-'+resp.data[i].post.id); $article.className = 'norm moved'; if (collAlias == '|anonymous|') { - $article.innerHTML = '

Unpublished post.

'; + var draftPre = ""; + if (typeof singleUser !== 'undefined' && singleUser) { + draftPre = "d/"; + } + $article.innerHTML = '

Unpublished post.

'; } else { $article.innerHTML = '

Moved to '+lbl+'.

'; } } } else { $lbl.innerHTML = "unable to move: "+resp.data[i].error_msg; } } } }; if (collAlias == '|anonymous|') { He.postJSON("/api/posts/disperse", params, callback); } else { He.postJSON("/api/collections/"+collAlias+"/collect", params, callback); } }; - var Move = function(el, id, collAlias) { + var Move = function(el, id, collAlias, singleUser) { var lbl = el.textContent; try { var m = lbl.match(/move to (.*)/); lbl = m[1]; } catch (e) { if (collAlias == '|anonymous|') { lbl = "draft"; } } el.textContent = "moving to "+lbl+"..."; if (collAlias == '|anonymous|') { params = [id]; } else { params = [{ id: id }]; } var callback = function(code, resp) { if (code == 200) { for (var i=0; i"; el.onclick = null; - var newPostURL = "/"+collAlias+"/"+resp.data[i].post.slug; + var pre = "/"+collAlias; + if (typeof singleUser !== 'undefined' && singleUser) { + pre = ""; + } + var newPostURL = pre+"/"+resp.data[i].post.slug; el.href = newPostURL; el.title = "View on "+lbl; try { // Posts page He.$('#post-'+resp.data[i].post.id+' > h3 > a')[0].href = newPostURL; } catch (e) { // Blog index var $article = He.get('post-'+resp.data[i].post.id); $article.className = 'norm moved'; if (collAlias == '|anonymous|') { - $article.innerHTML = '

Unpublished post.

'; + var draftPre = ""; + if (typeof singleUser !== 'undefined' && singleUser) { + draftPre = "d/"; + } + $article.innerHTML = '

Unpublished post.

'; } else { $article.innerHTML = '

Moved to '+lbl+'.

'; } } } else { el.innerHTML = "unable to move: "+resp.data[i].error_msg; } } } } if (collAlias == '|anonymous|') { He.postJSON("/api/posts/disperse", params, callback); } else { He.postJSON("/api/collections/"+collAlias+"/collect", params, callback); } }; return { move: Move, multiMove: MultiMove, }; }(); diff --git a/templates/base.tmpl b/templates/base.tmpl index 365770e..6c58ebf 100644 --- a/templates/base.tmpl +++ b/templates/base.tmpl @@ -1,55 +1,55 @@ {{define "base"}} {{ template "head" . }}

{{.SiteName}}

- {{if .HeaderNav}} + {{if not .SingleUser}} {{end}}
{{ template "content" . }}
{{ template "footer" . }} {{if not .JSDisabled}} {{else}} {{if .WebFonts}}{{end}} {{end}} {{end}} diff --git a/templates/collection-post.tmpl b/templates/collection-post.tmpl index e581ad9..6d2dfa0 100644 --- a/templates/collection-post.tmpl +++ b/templates/collection-post.tmpl @@ -1,134 +1,134 @@ {{define "post"}} {{.PlainDisplayTitle}} — {{.Collection.DisplayTitle}} {{if gt .Views 1}} {{end}} {{if gt (len .Images) 0}}{{else}}{{end}} {{range .Images}}{{else}}{{end}} {{if .Collection.StyleSheet}}{{end}} {{if .Collection.RenderMathJax}} {{end}}

{{if .IsScheduled}}

Scheduled

{{end}}{{if .Title.String}}

{{.FormattedDisplayTitle}}

{{end}}
{{.HTMLContent}}
{{ if .Collection.ShowFooterBranding }}

{{ end }} {{if .Collection.CanShowScript}} {{range .Collection.ExternalScripts}}{{end}} {{if .Collection.Script}}{{end}} {{end}} {{end}} diff --git a/templates/collection-tags.tmpl b/templates/collection-tags.tmpl index 5550b42..48cb475 100644 --- a/templates/collection-tags.tmpl +++ b/templates/collection-tags.tmpl @@ -1,198 +1,198 @@ {{define "collection-tags"}} {{.Tag}} — {{.Collection.DisplayTitle}} {{if not .Collection.IsPrivate}}{{end}} {{if gt .Views 1}} {{end}} {{if .Collection.StyleSheet}}{{end}} {{if .Collection.RenderMathJax}} {{end}}

{{.Collection.DisplayTitle}}

{{if .Posts}}
{{else}}
{{end}}

{{.Tag}}

{{template "posts" .}} {{if .Posts}}
{{else}}
{{end}} {{ if .Collection.ShowFooterBranding }} {{ end }} {{if .CanShowScript}} {{range .ExternalScripts}}{{end}} {{if .Collection.Script}}{{end}} {{end}} {{if .IsOwner}} {{end}} {{end}} diff --git a/templates/collection.tmpl b/templates/collection.tmpl index 33c6317..a46c64b 100644 --- a/templates/collection.tmpl +++ b/templates/collection.tmpl @@ -1,225 +1,229 @@ {{define "collection"}} {{.DisplayTitle}}{{if not .SingleUser}} — {{.SiteName}}{{end}} {{if gt .CurrentPage 1}}{{end}} {{if lt .CurrentPage .TotalPages}}{{end}} {{if not .IsPrivate}}{{end}} {{if .StyleSheet}}{{end}} {{if .RenderMathJax}} {{end}} {{if .IsOwner}}{{end}}

{{if .Posts}}{{else}}write.as {{end}}{{.DisplayTitle}}

{{if .Description}}

{{.Description}}

{{end}} {{/*if not .Public/*}} {{/*end*/}} {{if .PinnedPosts}} + {{range .PinnedPosts}}{{.PlainDisplayTitle}}{{end}} {{end}}
{{if .Posts}}
{{else}}
{{end}} {{if .IsWelcome}}

Welcome, {{.Username}}!

This is your new blog.

Start writing, or customize your blog.

Check out our writing guide to see what else you can do, and get in touch anytime with questions or feedback.

{{end}} {{template "posts" .}} {{if gt .TotalPages 1}}{{end}} {{if .Posts}}
{{else}}{{end}} {{if .ShowFooterBranding }} {{ end }} {{if .CanShowScript}} {{range .ExternalScripts}}{{end}} {{if .Script}}{{end}} {{end}} {{end}} diff --git a/templates/edit-meta.tmpl b/templates/edit-meta.tmpl index 57eada5..93c36ba 100644 --- a/templates/edit-meta.tmpl +++ b/templates/edit-meta.tmpl @@ -1,370 +1,370 @@ {{define "edit-meta"}} Edit metadata: {{if .Post.Title}}{{.Post.Title}}{{else}}{{.Post.Id}}{{end}} — {{.SiteName}}

{{if .User}}w{{else}}write.as{{end}}

-
+
-

Edit metadata: {{if .Post.Title}}{{.Post.Title}}{{else}}{{.Post.Id}}{{end}} view post

+

Edit metadata: {{if .Post.Title}}{{.Post.Title}}{{else}}{{.Post.Id}}{{end}} view post

{{if .Flashes}}{{end}}
{{if .EditCollection}}
{{end}}
UTC now

Date format should be: YYYY-MM-DD HH:MM:SS

 
{{end}} diff --git a/templates/include/footer.tmpl b/templates/include/footer.tmpl index 98a5c07..ef8eb9c 100644 --- a/templates/include/footer.tmpl +++ b/templates/include/footer.tmpl @@ -1,25 +1,35 @@ {{define "footer"}} - {{end}} diff --git a/templates/include/posts.tmpl b/templates/include/posts.tmpl index 165311b..514f69f 100644 --- a/templates/include/posts.tmpl +++ b/templates/include/posts.tmpl @@ -1,53 +1,53 @@ {{ define "posts" }} {{ range $el := .Posts }}
{{if .IsScheduled}}

Scheduled

{{end}} - {{if .Title.String}}

{{if .HasTitleLink}}{{.HTMLTitle}} {{else}}{{end}} + {{if .Title.String}}

{{if .HasTitleLink}}{{.HTMLTitle}} {{else}}{{end}} {{if $.IsOwner}} - + {{if $.CanPin}}{{end}} {{if gt (len $.Collections) 1}}{{else}} {{range $.Collections}} - + {{end}} {{end}} {{end}}

{{if $.Format.ShowDates}}{{end}} {{else}}

- {{if $.Format.ShowDates}}{{end}} + {{if $.Format.ShowDates}}{{end}} {{if $.IsOwner}} - {{if not $.Format.ShowDates}}{{end}} - - {{if $.CanPin}}{{end}} + {{if not $.Format.ShowDates}}{{end}} + + {{if $.CanPin}}{{end}} {{if gt (len $.Collections) 1}}{{else}} {{range $.Collections}} - + {{end}} {{end}} {{end}}

{{end}} {{if .Excerpt}}
{{if and (and (not $.IsOwner) (not $.Format.ShowDates)) (not .Title.String)}}{{end}}{{.Excerpt}}
{{localstr "Read more..." .Language.String}}{{else}}
{{if and (and (not $.IsOwner) (not $.Format.ShowDates)) (not .Title.String)}}{{end}}{{.HTMLContent}}
{{end}}
{{ end }} {{ end }} diff --git a/templates/pad.tmpl b/templates/pad.tmpl index cbce9bf..914d921 100644 --- a/templates/pad.tmpl +++ b/templates/pad.tmpl @@ -1,358 +1,363 @@ {{define "pad"}} {{if .Editing}}Editing {{if .Post.Title}}{{.Post.Title}}{{else}}{{.Post.Id}}{{end}}{{else}}New Post{{end}} — {{.SiteName}}
-

{{if .User}}{{else}}write.as{{end}} -

-
- {{if .Editing}}{{end}} + {{if .Editing}}{{end}}
{{end}} diff --git a/templates/post.tmpl b/templates/post.tmpl index 53e2bd8..22fa294 100644 --- a/templates/post.tmpl +++ b/templates/post.tmpl @@ -1,97 +1,97 @@ {{define "post"}} {{if .Title}}{{.Title}}{{else}}{{.GenTitle}}{{end}} — {{.SiteName}} {{if .IsCode}} {{end}} {{if gt .Views 1}} {{end}} {{if .Author}}{{end}}

{{.SiteName}}

{{if .Title}}

{{.Title}}

{{end}}{{ if .IsPlainText }}

{{.Content}}

{{ else }}
{{.HTMLContent}}
{{ end }}
{{if .IsCode}} {{else}} {{if .IsPlainText}}{{end}} {{end}} {{end}} diff --git a/templates/user/articles.tmpl b/templates/user/articles.tmpl index bfc48f2..4956301 100644 --- a/templates/user/articles.tmpl +++ b/templates/user/articles.tmpl @@ -1,145 +1,145 @@ {{define "articles"}} {{template "header" .}}
{{if .Flashes}}{{end}}

drafts

{{ if .AnonymousPosts }}
{{ range $el := .AnonymousPosts }}
-

+

- edit + edit delete {{ if $.Collections }} {{if gt (len $.Collections) 1}}
- {{range $.Collections}}{{end}}
{{else}} {{range $.Collections}} - move to {{.DisplayTitle}} + move to {{.DisplayTitle}} {{end}} {{end}} {{ end }}

{{if .Summary}}

{{.Summary}}

{{end}}
{{end}}
{{ else }}

You haven't saved any drafts yet.

They'll show up here once you do. Find your blog posts from the Blogs page.

Start writing

{{ end }}
{{template "footer" .}} {{end}} diff --git a/templates/user/collection.tmpl b/templates/user/collection.tmpl index d5789fb..e9cbd44 100644 --- a/templates/user/collection.tmpl +++ b/templates/user/collection.tmpl @@ -1,234 +1,234 @@ {{define "upgrade"}}

Upgrade for $40 / year to edit.

{{end}} {{define "collection"}} {{template "header" .}}

Customize {{.DisplayTitle}} view blog

{{if .Flashes}}{{end}}

URL

{{if eq .Alias .Username}}

This blog uses your username in its URL{{if .Federation}} and fediverse handle{{end}}. You can change it in your Account Settings.

{{end}}
  • {{.FriendlyHost}}/{{.Alias}}/
  • - @{{.Alias}}@{{.FriendlyHost}} + @{{.Alias}}@{{.FriendlyHost}}

Publicity

  • This blog is visible to anyone with its link.

  • Only you may read this blog (while you're logged in).

  • A password is required to read this blog.

Display Format

Customize how your posts display on your page.

  • Dates are shown. Latest posts listed first.

  • No dates shown. Oldest posts first.

  • No dates shown. Latest posts first.

Text Rendering

Customize how plain text renders on your blog.

Custom CSS

See our guide on customization.

View Blog

{{if ne .Alias .Username}}

Delete Blog...

{{end}}
{{template "footer" .}} {{end}} diff --git a/templates/user/include/header.tmpl b/templates/user/include/header.tmpl index fa31adb..797b3d7 100644 --- a/templates/user/include/header.tmpl +++ b/templates/user/include/header.tmpl @@ -1,37 +1,59 @@ {{define "header"}} {{.PageTitle}} {{if .Separator}}{{.Separator}}{{else}}—{{end}} {{.SiteName}} -
+ + {{if .SingleUser}} + + {{else}}

{{.SiteName}}

+ {{end}}
{{end}}