From 93e6b9a0d3a3abe539f504186a11601bb07a924b Mon Sep 17 00:00:00 2001
From: Yusur Princeps
Date: Fri, 5 Sep 2025 21:42:18 +0200
Subject: [PATCH] the big change
---
.gitignore | 47 +-
CHANGELOG.md | 13 +
LICENSE | 68 +-
LICENSE.0_9 | 20 +
README.md | 41 +-
app.py | 1389 -----------------
app_init.py | 5 -
app_sync.py | 175 ---
extensions/circles.py | 241 ---
extensions/contactnova.py | 214 ---
i18n/salvi.en.json | 110 +-
i18n/salvi.it.json | 11 +-
migrations/0_6to0_7.py | 20 -
migrations/0_7to0_8.py | 23 -
pyproject.toml | 31 +
requirements.txt | 16 +-
robots.txt | 2 +
salvi/__init__.py | 191 +++
salvi/colors.py | 77 +
salvi/constants.py | 15 +
salvi/exceptions.py | 9 +
salvi/i18n.py | 34 +
salvi/models.py | 657 ++++++++
salvi/renderer.py | 40 +
salvi/routes/__init__.py | 44 +
salvi/routes/accounts.py | 95 ++
salvi/routes/admin.py | 93 ++
salvi/routes/calendar.py | 47 +
salvi/routes/edit.py | 203 +++
salvi/routes/embed.py | 22 +
salvi/routes/home.py | 55 +
salvi/routes/legal.py | 16 +
salvi/routes/search.py | 22 +
salvi/routes/stats.py | 75 +
salvi/routes/view.py | 50 +
{static => salvi/static}/content.js | 0
{static => salvi/static}/edit.js | 0
{static => salvi/static}/style.css | 238 +--
salvi/templates/400.html | 15 +
salvi/templates/403.html | 14 +
salvi/templates/404.html | 14 +
.../templates/500.html | 7 +-
.../templates/administration.html | 5 +-
.../templates/backlinks.html | 12 +-
salvi/templates/base.html | 83 +
.../templates/calendar.html | 7 +-
.../templates/contributions.html | 22 +-
.../templates/easter.html | 5 +-
.../edit.jinja2 => salvi/templates/edit.html | 15 +-
.../templates/exportpages.html | 6 +-
.../templates/history.html | 23 +-
.../home.jinja2 => salvi/templates/home.html | 13 +-
.../templates/importpages.html | 5 +-
.../templates/kt_list.html | 2 +-
.../new.jinja2 => salvi/templates/kt_new.html | 2 +-
.../templates/kt_single.html | 2 +-
salvi/templates/listrecent.html | 15 +
.../templates/listtag.html | 9 +-
salvi/templates/login.html | 32 +
.../templates/macros/icon.html | 0
.../templates/macros/nl.html | 14 +-
salvi/templates/macros/title.html | 17 +
.../templates/manageaccounts.html | 17 +-
.../templates/month.html | 11 +-
.../templates/privacy.html | 7 +-
salvi/templates/register.html | 41 +
.../templates/rules.html | 7 +-
.../templates/search.html | 13 +-
salvi/templates/stats.html | 23 +
.../templates/terms.html | 8 +-
.../view.jinja2 => salvi/templates/view.html | 11 +-
.../templates/viewold.html | 8 +-
salvi/transfer.py | 104 ++
salvi/utils.py | 35 +
strings.csv | 29 -
templates/badrequest.jinja2 | 13 -
templates/base.jinja2 | 62 -
templates/circles/add.jinja2 | 58 -
templates/circles/csv.jinja2 | 21 -
templates/circles/list.jinja2 | 65 -
templates/circles/stats.jinja2 | 30 -
templates/forbidden.jinja2 | 13 -
templates/includes/nl_item.jinja2 | 25 -
templates/leaderboard.jinja2 | 40 -
templates/listrecent.jinja2 | 12 -
templates/login.jinja2 | 35 -
templates/notfound.jinja2 | 13 -
templates/register.jinja2 | 39 -
templates/stats.jinja2 | 18 -
templates/upload.jinja2 | 23 -
90 files changed, 2629 insertions(+), 2900 deletions(-)
create mode 100644 LICENSE.0_9
delete mode 100644 app.py
delete mode 100644 app_init.py
delete mode 100644 app_sync.py
delete mode 100644 extensions/circles.py
delete mode 100644 extensions/contactnova.py
delete mode 100644 migrations/0_6to0_7.py
delete mode 100644 migrations/0_7to0_8.py
create mode 100644 pyproject.toml
create mode 100644 salvi/__init__.py
create mode 100644 salvi/colors.py
create mode 100644 salvi/constants.py
create mode 100644 salvi/exceptions.py
create mode 100644 salvi/i18n.py
create mode 100644 salvi/models.py
create mode 100644 salvi/renderer.py
create mode 100644 salvi/routes/__init__.py
create mode 100644 salvi/routes/accounts.py
create mode 100644 salvi/routes/admin.py
create mode 100644 salvi/routes/calendar.py
create mode 100644 salvi/routes/edit.py
create mode 100644 salvi/routes/embed.py
create mode 100644 salvi/routes/home.py
create mode 100644 salvi/routes/legal.py
create mode 100644 salvi/routes/search.py
create mode 100644 salvi/routes/stats.py
create mode 100644 salvi/routes/view.py
rename {static => salvi/static}/content.js (100%)
rename {static => salvi/static}/edit.js (100%)
rename {static => salvi/static}/style.css (57%)
create mode 100644 salvi/templates/400.html
create mode 100644 salvi/templates/403.html
create mode 100644 salvi/templates/404.html
rename templates/internalservererror.jinja2 => salvi/templates/500.html (50%)
rename templates/administration.jinja2 => salvi/templates/administration.html (75%)
rename templates/backlinks.jinja2 => salvi/templates/backlinks.html (75%)
create mode 100644 salvi/templates/base.html
rename templates/calendar.jinja2 => salvi/templates/calendar.html (83%)
rename templates/contributions.jinja2 => salvi/templates/contributions.html (50%)
rename templates/easter.jinja2 => salvi/templates/easter.html (86%)
rename templates/edit.jinja2 => salvi/templates/edit.html (94%)
rename templates/exportpages.jinja2 => salvi/templates/exportpages.html (84%)
rename templates/history.jinja2 => salvi/templates/history.html (62%)
rename templates/home.jinja2 => salvi/templates/home.html (59%)
rename templates/importpages.jinja2 => salvi/templates/importpages.html (83%)
rename templates/contactnova/list.jinja2 => salvi/templates/kt_list.html (98%)
rename templates/contactnova/new.jinja2 => salvi/templates/kt_new.html (98%)
rename templates/contactnova/single.jinja2 => salvi/templates/kt_single.html (95%)
create mode 100644 salvi/templates/listrecent.html
rename templates/listtag.jinja2 => salvi/templates/listtag.html (68%)
create mode 100644 salvi/templates/login.html
rename extensions/__init__.py => salvi/templates/macros/icon.html (100%)
rename templates/macros/nl.jinja2 => salvi/templates/macros/nl.html (88%)
create mode 100644 salvi/templates/macros/title.html
rename templates/manageaccounts.jinja2 => salvi/templates/manageaccounts.html (68%)
rename templates/month.jinja2 => salvi/templates/month.html (82%)
rename templates/privacy.jinja2 => salvi/templates/privacy.html (91%)
create mode 100644 salvi/templates/register.html
rename templates/rules.jinja2 => salvi/templates/rules.html (91%)
rename templates/search.jinja2 => salvi/templates/search.html (67%)
create mode 100644 salvi/templates/stats.html
rename templates/terms.jinja2 => salvi/templates/terms.html (97%)
rename templates/view.jinja2 => salvi/templates/view.html (91%)
rename templates/viewold.jinja2 => salvi/templates/viewold.html (65%)
create mode 100644 salvi/transfer.py
create mode 100644 salvi/utils.py
delete mode 100644 strings.csv
delete mode 100644 templates/badrequest.jinja2
delete mode 100644 templates/base.jinja2
delete mode 100644 templates/circles/add.jinja2
delete mode 100644 templates/circles/csv.jinja2
delete mode 100644 templates/circles/list.jinja2
delete mode 100644 templates/circles/stats.jinja2
delete mode 100644 templates/forbidden.jinja2
delete mode 100644 templates/includes/nl_item.jinja2
delete mode 100644 templates/leaderboard.jinja2
delete mode 100644 templates/listrecent.jinja2
delete mode 100644 templates/login.jinja2
delete mode 100644 templates/notfound.jinja2
delete mode 100644 templates/register.jinja2
delete mode 100644 templates/stats.jinja2
delete mode 100644 templates/upload.jinja2
diff --git a/.gitignore b/.gitignore
index 9c35e69..62f74a0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,22 +1,29 @@
-# application content
-media/
-**.sqlite
-database/
-site.conf
-site-*.conf
-run_8180.py
-.env
-alembic.ini
-venv
-venv-*
-.venv
-env
-
-# automatically generated garbage
-**/__pycache__/
+node_modules/
+__pycache__/
**.pyc
**~
-**/.\#*
-**/\#*\#
-ig_api_settings/
-node_modules/
+.*.swp
+\#*\#
+.\#*
+alembic.ini
+.env
+.env.*
+.venv
+env
+venv
+venv-*/
+config/
+conf/
+config.json
+data/
+site-*.conf
+site.conf
+.err
+.vscode
+/run.sh
+/target
+dist/
+build/
+**.egg-info
+ROADMAP.md
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5ff070e..0b40585 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,18 @@
# What’s New
+## 1.0.0
+
++ **BREAKING CHANGES AHEAD**!
++ **SECURITY ADVISORY**: versions from `0.7` up to `0.9` are **VULNERABLE to XSS** due to `.jinja2` not getting autoescaped.
++ No more a monolith: `app.py` got split into several files into `salvi` package
++ Switched from peewee to **SQLAlchemy**; Schema as of 1.0 is the same as 0.9
++ Added dependency on [libsuou](https://github.com/yusurko/suou)
++ `site.conf` deprecated, but still supported for the time being
++ Switched to `pyproject.toml`. `requirements.txt` has been sunset.
++ Switched to the Apache License; the old license text is moved to `LICENSE.0_9`
++ Added color themes! This is a breaking (but trivial) aesthetic change. Default theme is 'Miku' (aquamarine green).
++ Extensions have been removed. They never had a clear, usable, public API in the first place.
+
## 0.9
+ Removed `markdown_katex` dependency, and therefore support for math.
diff --git a/LICENSE b/LICENSE
index a2d4b30..df8a219 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,19 +1,55 @@
-Copyright (C) 2020-2021 Sakuragasaki46
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
+Copyright (c) 2020-2025 Sakuragasaki46
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
diff --git a/LICENSE.0_9 b/LICENSE.0_9
new file mode 100644
index 0000000..a513535
--- /dev/null
+++ b/LICENSE.0_9
@@ -0,0 +1,20 @@
+
+Copyright (C) 2020-2021 Sakuragasaki46
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 941565a..56a8ff2 100644
--- a/README.md
+++ b/README.md
@@ -17,46 +17,47 @@ suitable as a community or team knowledge base.
+ Calendar
+ Works fine even with JavaScript disabled.
-## Requirements
+## Requirements & Dependencies
-+ **Python** 3.6+.
++ **Python** 3.10+.
+ **Flask** web framework (and Flask-Login / Flask-WTF / Flask-Arrest extensions).
-+ **Peewee** ORM.
++ **SQLAlchemy** ORM.
+ **Markdown** for page rendering.
-+ **Python-I18n**.
++ **[SUOU](https://github.com/yusurko/suou)**. (since 1.0)
* **Python-Dotenv**.
+ The database drivers needed for the type of database.
+To install the dependencies, run (virtualenv advised):
+> `pip install -e .`
+
## Usage
-+ Clone this repository: `git clone https://github.com/sakuragasaki46/salvi`
-+ Edit site.conf (old way) or .env (new way) with the needed parameters. An example site.conf with SQLite:
-
-```
-[site]
-name = Salvi
-
-[database]
-directory = /path/to/database/
-```
-
- An example .env with MySQL:
++ Clone this repository: `git clone https://github.com/yusurko/salvi`
++ Edit `.env` with the needed parameters. An example `.env` with MySQL:
```
APP_NAME=Salvi
DATABASE_URL=mysql://root:root@localhost/salvi
```
-+ Run `python3 -m app_init` to initialize the database and create the administrator user.
++ Run `python3 -m app_init` to initialize the database and create the administrator user. (The installer is unstable)
+ Run `flask run`.
+ You can now access Salvi in your browser at port 5000.
## Caveats
-+ The whole application is untested.
-+ If you forget the password, there is currently no way to reset it.
++ The whole application is free of unit tests. Ergo untested. No coverage.
++ If you forget the password, there is currently no way to reset it. E-mail is not supported as of 1.0.
+ This app comes with no content. It means, you have to write it yourself.
## License
-[MIT License](./LICENSE).
+Since 1.0, Salvi is licensed under the [Apache License, Version 2.0](LICENSE), a non-copyleft free and open source license.
+
+Salvi`<=0.9` is under **[MIT license](LICENSE.0_9)**, available at `LICENSE.0_9`.
+
+This is a hobby project, made available “AS IS”, with __no warranty__ express or implied.
+
+I (sakuragasaki46) may NOT be held accountable for Your use of my code.
+
+> It's pointless to file a lawsuit because you feel damaged, and it's only going to turn against you. What a waste of money you could have spent on a vacation or charity, or invested in stocks.
diff --git a/app.py b/app.py
deleted file mode 100644
index 2bdec0d..0000000
--- a/app.py
+++ /dev/null
@@ -1,1389 +0,0 @@
-# (C) 2020-2021 Sakuragasaki46.
-# See LICENSE for copying info.
-
-'''
-A simple wiki-like note webapp.
-
-Pages are stored in SQLite/MySQL databases.
-Markdown is used for text formatting.
-
-Application is kept compact, with all its core in a single file.
-'''
-
-#### IMPORTS ####
-
-from flask import (
- Flask, abort, flash, g, jsonify, make_response, redirect, request,
- render_template, send_from_directory)
-from markupsafe import Markup
-from flask_login import LoginManager, login_user, logout_user, current_user, login_required
-from flask_wtf import CSRFProtect
-#from flask_arrest import RestBlueprint, serialize_response
-from werkzeug.security import generate_password_hash, check_password_hash
-from werkzeug.routing import BaseConverter
-from peewee import *
-from playhouse.db_url import connect as dbconnect
-import datetime, hashlib, html, importlib, json, markdown, os, random, \
- re, sys, warnings
-from functools import lru_cache, partial
-from urllib.parse import quote
-from configparser import ConfigParser
-import i18n
-import gzip
-from getpass import getpass
-import dotenv
-
-__version__ = '0.9-dev'
-
-#### CONSTANTS ####
-
-APP_BASE_DIR = os.path.dirname(__file__)
-
-FK = ForeignKeyField
-
-SLUG_RE = r'[a-z0-9]+(?:-[a-z0-9]+)*'
-ILINK_RE = r'\]\(/(p/\d+|' + SLUG_RE + ')/?\)'
-USERNAME_RE = r'[a-z0-9_-]{3,30}'
-PING_RE = r'(?' + match.group(1) + ''
-
-# XXX ugly monkeypatch to make spoilers prevail over blockquotes
-from markdown.blockprocessors import BlockQuoteProcessor
-BlockQuoteProcessor.RE = re.compile(r'(^|\n)[ ]{0,3}>(?!!)[ ]?(.*)')
-
-### XXX it currently only detects spoilers that are not at the beginning of the line. To be fixed.
-class SpoilerExtension(markdown.extensions.Extension):
- def extendMarkdown(self, md, md_globals=None):
- md.inlinePatterns.register(markdown.inlinepatterns.SimpleTagInlineProcessor(r'()>!(.*?)!<', 'span class="spoiler"'), 'spoiler', 14)
-
-
-#class PingExtension(markdown.extensions.Extension):
-# def extendMarkdown(self, md):
-# pass
-
-#### DATABASE SCHEMA ####
-
-database_url = os.getenv("DATABASE_URL") or _getconf('database', 'url')
-if database_url:
- database = dbconnect(database_url)
-else:
- print("Database URL required.")
- exit(-1)
-
-class BaseModel(Model):
- class Meta:
- database = database
-
-class User(BaseModel):
- username = CharField(32, unique=True)
- email = CharField(256, null=True)
- password = CharField()
- join_date = DateTimeField(default=datetime.datetime.now)
- karma = IntegerField(default=1)
- privileges = BitField()
- is_admin = privileges.flag(1)
- restrictions = BitField()
- is_disabled = restrictions.flag(1)
-
- # helpers for flask_login
- @property
- def is_anonymous(self):
- return False
- @property
- def is_active(self):
- return not self.is_disabled
- @property
- def is_authenticated(self):
- return True
-
- @property
- def groups(self):
- return (
- UserGroup.select().join(UserGroupMembership, on=UserGroupMembership.group)
- .where(UserGroupMembership.user == self)
- )
-
- def get_perms(self):
- if self.is_admin:
- return PERM_ALL
-
- perm = 0
-
- for gr in self.groups:
- perm |= gr.permissions
-
- return perm
-
-
-# page perms (used as bitmasks)
-PERM_READ = 1
-PERM_EDIT = 2
-PERM_CREATE = 4
-PERM_SET_URL = 8
-PERM_SET_TAGS = 16
-PERM_ALL = 31
-PERM_LOCK = ~(PERM_EDIT | PERM_CREATE | PERM_SET_URL | PERM_SET_TAGS)
-
-class UserGroup(BaseModel):
- name = CharField(32, unique=True)
- permissions = BitField()
- # Can read pages.
- can_read = permissions.flag(1)
- # Can edit all non-locked pages.
- can_edit = permissions.flag(2)
- # Can create and edit their own pages.
- can_create = permissions.flag(4)
- # Can set page URL.
- can_set_url = permissions.flag(8)
- # Can change page tags.
- can_set_tags = permissions.flag(16)
-
- @classmethod
- def get_default_group(cls):
- try:
- return cls[1]
- except cls.DoesNotExist:
- return cls.get(cls.name == 'default')
-
-class UserGroupMembership(BaseModel):
- user = ForeignKeyField(User, backref='group_memberships')
- group = ForeignKeyField(UserGroup, backref='user_memberships')
- since = DateTimeField(default=datetime.datetime.now)
-
- class Meta:
- indexes = (
- (('user', 'group'), True),
- )
-
-
-class Page(BaseModel):
- url = CharField(64, unique=True, null=True)
- title = CharField(256, index=True)
- touched = DateTimeField(index=True)
- calendar = DateTimeField(index=True, null=True)
- owner = ForeignKeyField(User, null=True)
- flags = BitField()
- is_redirect = flags.flag(1)
- is_sync = flags.flag(2)
- is_math_enabled = flags.flag(4) # legacy, math is no more supported
- is_locked = flags.flag(8)
- is_cw = flags.flag(16)
- @property
- def latest(self):
- if self.revisions:
- return self.revisions.order_by(PageRevision.pub_date.desc())[0]
- def get_url(self):
- return '/' + self.url + '/' if self.url else '/p/{}/'.format(self.id)
- def short_desc(self):
- if self.is_cw:
- return '(Content Warning: we are not allowed to show a description.)'
- full_text = self.latest.text
- text = remove_tags(full_text, convert = not _getconf('appearance', 'simple_remove_tags', False))
- return text[:200] + ('\u2026' if len(text) > 200 else '')
- def change_tags(self, new_tags):
- old_tags = set(x.name for x in self.tags)
- new_tags = set(new_tags)
- PageTag.delete().where((PageTag.page == self) &
- (PageTag.name << (old_tags - new_tags))).execute()
- for tag in (new_tags - old_tags):
- PageTag.create(page=self, name=tag)
- def js_info(self):
- latest = self.latest
- return dict(
- id=self.id,
- url=self.url,
- title=self.title,
- is_redirect=self.is_redirect,
- touched=self.touched.timestamp(),
- is_editable=self.is_editable(),
- latest=dict(
- id=latest.id if latest else None,
- length=latest.length,
- pub_date=latest.pub_date.timestamp() if latest and latest.pub_date else None
- ),
- tags=[x.name for x in self.tags]
- )
- @property
- def prop(self):
- return PagePropertyDict(self)
- def is_editable(self):
- return self.can_edit(current_user)
-
- def can_edit(self, user):
- perm = self.get_perms(user)
- return perm & PERM_EDIT or (self.owner == user and perm & PERM_CREATE)
- def is_owned_by(self, user):
- return user.id == self.owner.id
-
- def get_perms(self, user=None):
- if user is None:
- user = current_user
-
- if user.is_anonymous:
- return UserGroup.get_default_group().permissions & PERM_LOCK
-
- if user.is_admin:
- return PERM_ALL
-
- perm = 0
- # default groups
- for gr in user.groups:
- perm |= gr.permissions
-
- # page overrides
- for ov in self.permission_overrides:
- if ov.group in user.groups:
- perm |= ov.permissions
-
- if self.is_locked and self.owner.id != user.id:
- perm &= PERM_LOCK
- return perm
-
- def seo_keywords(self):
- kw = []
- for tag in self.tags:
- kw.append(tag.name.replace("-", " "))
- for bkl in self.back_links:
- try:
- kw.append(bkl.from_page.title.replace(",", ""))
- except Exception:
- pass
- return ", ".join(kw)
-
- #def ldjson(self):
- # return {
- # "@context": "https://www.w3.org/ns/activitystreams",
- #
- # }
-
-
-class PageText(BaseModel):
- content = BlobField()
- flags = BitField()
- is_utf8 = flags.flag(1)
- is_gzipped = flags.flag(2)
- def get_content(self):
- c = self.content
- if self.is_gzipped:
- c = gzip.decompress(c)
- if self.is_utf8:
- return c.decode('utf-8')
- else:
- return c.decode('latin-1')
- @classmethod
- def create_content(cls, text, *, treshold=600, search_dup=True):
- c = text.encode('utf-8')
- use_gzip = len(c) > treshold
- if use_gzip and gzip:
- c = gzip.compress(c)
- if search_dup:
- item = cls.get_or_none((cls.content == c) & (cls.is_gzipped == use_gzip))
- if item:
- return item
- return cls.create(
- content=c,
- is_utf8=True,
- is_gzipped=use_gzip
- )
-
-class PageRevision(BaseModel):
- page = FK(Page, backref='revisions', index=True)
- user = ForeignKeyField(User, backref='contributions', null=True)
- comment = CharField(1024, default='')
- textref = FK(PageText)
- pub_date = DateTimeField(index=True)
- length = IntegerField()
- @property
- def text(self):
- return self.textref.get_content()
- def html(self):
- return md(self.text)
- def html_and_toc(self):
- return md_and_toc(self.text)
- def human_pub_date(self):
- delta = datetime.datetime.now() - self.pub_date
- T = partial(get_string, g.lang)
- if delta < datetime.timedelta(seconds=60):
- return T('just-now')
- elif delta < datetime.timedelta(seconds=3600):
- return T('n-minutes-ago').format(delta.seconds // 60)
-
- elif delta < datetime.timedelta(days=1):
- return T('n-hours-ago').format(delta.seconds // 3600)
- elif delta < datetime.timedelta(days=15):
- return T('n-days-ago').format(delta.days)
- else:
- return self.pub_date.strftime('%B %-d, %Y')
-
-class PageTag(BaseModel):
- page = FK(Page, backref='tags', index=True)
- name = CharField(64, index=True)
- class Meta:
- indexes = (
- (('page', 'name'), True),
- )
- def popularity(self):
- return PageTag.select().where(PageTag.name == self.name).count()
-
-class PageProperty(BaseModel):
- page = ForeignKeyField(Page, backref='page_meta', index=True)
- key = CharField(64)
- value = CharField(8000)
- class Meta:
- indexes = (
- (('page', 'key'), True),
- )
-
-# currently experimental
-class PagePropertyDict(object):
- def __init__(self, page):
- self._page = page
- def items(self):
- for kv in self._page.page_meta:
- yield kv.key, kv.value
- def __len__(self):
- return self._page.page_meta.count()
- def keys(self):
- for kv in self._page.page_meta:
- yield kv.key
- __iter__ = keys
- def __getitem__(self, key):
- try:
- return self._page.page_meta.get(PageProperty.key == key).value
- except PageProperty.DoesNotExist:
- raise KeyError(key)
- def get(self, key, default=None):
- try:
- return self._page.page_meta.get(PageProperty.key == key).value
- except PageProperty.DoesNotExist:
- return default
- def setdefault(self, key, default):
- try:
- return self._page.page_meta.get(PageProperty.key == key).value
- except PageProperty.DoesNotExist:
- self[key] = default
- return default
- def __setitem__(self, key, value):
- if key in self:
- pp = self._page.page_meta.get(PageProperty.key == key)
- pp.value = value
- pp.save()
- else:
- PageProperty.create(page=self._page, key=key, value=value)
- def __delitem__(self, key):
- PageProperty.delete().where((PageProperty.page == self._page) &
- (PageProperty.key == key)).execute()
- def __contains__(self, key):
- return PageProperty.select().where((PageProperty.page == self._page) &
- (PageProperty.key == key)).exists()
-
-
-# Link table for caching purposes.
-class PageLink(BaseModel):
- from_page = FK(Page, backref='forward_links')
- to_page = FK(Page, backref='back_links')
-
- class Meta:
- indexes = (
- (('from_page', 'to_page'), True),
- )
-
- @classmethod
- def parse_links(cls, from_page, text, erase=True):
- with database.atomic():
- old_links = list(cls.select().where(cls.from_page == from_page))
- for mo in re.finditer(ILINK_RE, text):
- try:
- pageurl = mo.group(1)
- if pageurl.startswith('p/'):
- to_page = Page[int(pageurl[2:])]
- else:
- to_page = Page.get(Page.url == pageurl)
-
- linkobj, created = PageLink.get_or_create(
- from_page = from_page,
- to_page = to_page)
- if linkobj in old_links:
- old_links.remove(linkobj)
- except Exception:
- continue
- if erase:
- for linkobj in old_links:
- linkobj.delete_instance()
-
- # The actual ULTIMATE method to refresh all links
- # To be called from a maintenance script only!
- @classmethod
- def refresh_all_links(cls):
- for p in Page.select():
- cls.parse_links(p, p.latest.text)
-
-class PagePermission(BaseModel):
- page = ForeignKeyField(Page, backref='permission_overrides')
- group = ForeignKeyField(UserGroup, backref='page_permissions')
- permissions = BitField()
- # Can read pages.
- can_read = permissions.flag(1)
- # Can edit all non-locked pages.
- can_edit = permissions.flag(2)
- # Can create and edit their own pages.
- can_create = permissions.flag(4)
- # Can set page URL.
- can_set_url = permissions.flag(8)
- # Can change page tags.
- can_set_tags = permissions.flag(16)
-
- class Meta:
- indexes = (
- (('page', 'group'), True),
- )
-
-def init_db():
- database.create_tables([
- User, UserGroup, UserGroupMembership,
- Page, PageText, PageRevision, PageTag, PageProperty, PageLink,
- PagePermission
- ])
-
-def init_db_and_create_first_user():
- try:
- User[1]
- UserGroup[1]
- except Exception:
- pass
- else:
- print('Looks like this site is already set up!')
- return
- username = input('Username: ')
- password = getpass('Password: ')
- confirm_password = getpass('Confirm password: ')
- email = input('Email: (optional)') or None
- if not is_username(username):
- print('Invalid username: usernames can contain only letters, numbers, underscores and hyphens.')
- return
- if password != confirm_password:
- print('Passwords do not match.')
- return
- default_permissions = PERM_ALL # all permissions
- if not input('Agree to the Terms of Use?')[0].lower() == 'y':
- print('You must accept Terms in order to register.')
- return
- with database.atomic():
- init_db()
- ua = User.create(
- username = username,
- email = email,
- password = generate_password_hash(password),
- join_date = datetime.datetime.now(),
- is_admin = True
- )
- ug = UserGroup.create(
- name = 'default',
- permissions = int(default_permissions)
- )
- UserGroupMembership.create(
- user = ua,
- group = ug
- )
- print('Installed successfully!')
-
-#### PERMS HELPERS ####
-
-def has_perms(user, flags, page=None):
- if page:
- perm = page.get_perms(user)
- else:
- perm = user.get_perms()
-
- if perm & flags:
- return True
- return False
-
-#### WIKI SYNTAX ####
-
-def md_and_toc(text, toc=True):
- extensions = ['tables', 'footnotes', 'fenced_code', 'sane_lists']
- extension_configs = {}
- if not _getconf('markdown', 'disable_custom_extensions'):
- extensions.append(StrikethroughExtension())
- extensions.append(SpoilerExtension())
- if toc:
- extensions.append('toc')
- try:
- converter = markdown.Markdown(extensions=extensions, extension_configs=extension_configs)
- if toc:
- return converter.convert(text), converter.toc
- else:
- return converter.convert(text), ''
- except Exception as e:
- return '
There was an error during rendering: {e.__class__.__name__}: {e}
'.format(e=e), ''
-
-def md(text, toc=True):
- return md_and_toc(text, toc=toc)[0]
-
-def remove_tags(text, convert=True, headings=True):
- if headings:
- text = re.sub(r'\#[^\n]*', '', text)
- if convert:
- text = md(text, toc=False)
- return re.sub(r'<.*?>', '', text)
-
-def is_username(s):
- return re.match('^' + USERNAME_RE + '$', s)
-
-#### I18N ####
-
-i18n.load_path.append(os.path.join(APP_BASE_DIR, 'i18n'))
-i18n.set('file_format', 'json')
-
-def get_string(loc, s):
- i18n.set('locale', loc)
- return i18n.t('salvi.' + s)
-
-#### APPLICATION CONFIG ####
-
-class SlugConverter(BaseConverter):
- regex = SLUG_RE
-
-def is_valid_url(url):
- return re.fullmatch(SLUG_RE, url)
-
-def is_url_available(url):
- return url not in forbidden_urls and not Page.select().where(Page.url == url).exists()
-
-forbidden_urls = [
- 'about', 'accounts', 'ajax', 'backlinks', 'calendar', 'circles', 'create',
- 'easter', 'edit', 'embed', 'group', 'help', 'history', 'init-config', 'kt',
- 'manage', 'media', 'p', 'privacy', 'protect', 'rules', 'search', 'static',
- 'stats', 'tags', 'terms', 'u', 'upload', 'upload-info'
-]
-
-app = Flask(__name__)
-app.secret_key = b'\xf3\xa9?\xbee$L\xabA\xd3\r\xa2\x08\xf6\x00%0b\xa9\xfe\x11\x04\xa6\xd8=\xd3\xa2\x00\xb3\xd5;9'
-app.url_map.converters['slug'] = SlugConverter
-
-csrf = CSRFProtect(app)
-login_manager = LoginManager(app)
-
-login_manager.login_view = 'accounts_login'
-
-#### ROUTES ####
-
-def _get_lang():
- if request.args.get('uselang') is not None:
- lang = request.args['uselang']
- else:
- for l in request.headers.get('accept-language', 'it,en').split(','):
- if ';' in l:
- l, _ = l.split(';')
- lang = l
- break
- else:
- lang = 'en'
- return lang
-
-@app.before_request
-def _before_request():
- g.lang = _get_lang()
-
-@app.context_processor
-def _inject_variables():
- return {
- 'T': partial(get_string, _get_lang()),
- 'app_name': os.getenv("APP_NAME") or _getconf('site', 'title'),
- 'strong': lambda x:Markup('{0}').format(x),
- 'app_version': __version__,
- 'material_icons_url': _getconf('site', 'material_icons_url'),
- 'min': min
- }
-
-@login_manager.user_loader
-def _inject_user(userid):
- u = User[userid]
- if not u.is_disabled:
- return u
-
-@app.template_filter()
-def linebreaks(text):
- text = html.escape(text)
- text = text.replace("\n\n", '
').replace('\n', ' ')
- return Markup(text)
-
-app.template_filter(name='markdown')(md)
-
-@app.route('/')
-def homepage():
- page_limit = _getconf("appearance", "items_per_page", 20, cast=int)
- return render_template('home.jinja2', new_notes=Page.select()
- .order_by(Page.touched.desc()).limit(page_limit))
-
-@app.route('/robots.txt')
-def robots():
- return send_from_directory(APP_BASE_DIR, 'robots.txt')
-
-@app.route('/favicon.ico')
-def favicon():
- return send_from_directory(APP_BASE_DIR, 'favicon.ico')
-
-## error handlers ##
-
-@app.errorhandler(404)
-def error_404(body):
- return render_template('notfound.jinja2'), 404
-
-@app.errorhandler(403)
-def error_403(body):
- return render_template('forbidden.jinja2'), 403
-
-@app.errorhandler(400)
-def error_400(body):
- return render_template('badrequest.jinja2'), 400
-
-@app.errorhandler(500)
-def error_500(body):
- try:
- User[1]
- except OperationalError:
- g.need_install = True
- return render_template('internalservererror.jinja2'), 500
-
-# Middle point during page editing.
-def savepoint(form, is_preview=False, pageobj=None):
- if is_preview:
- preview = md(form['text'])
- else:
- preview = None
- pl_js_info = dict()
- pl_js_info['editing'] = dict(
- original_text = None, # TODO
- preview_text = form['text'],
- page_id = pageobj.id if pageobj else None
- )
- return render_template(
- 'edit.jinja2',
- pl_url=form['url'],
- pl_title=form['title'],
- pl_text=form['text'],
- pl_tags=form['tags'],
- pl_comment=form['comment'],
- pl_is_locked='lockpage' in form,
- pl_owner_is_current_user=pageobj.is_owned_by(current_user) if pageobj else True,
- preview=preview,
- pl_js_info=pl_js_info,
- pl_calendar=('usecalendar' in form) and form['calendar'],
- pl_readonly=not pageobj.can_edit(current_user) if pageobj else False,
- pl_cw=('cw' in form) and form['cw']
- )
-
-@app.route('/create/', methods=['GET', 'POST'])
-@login_required
-def create():
- if not has_perms(current_user, PERM_CREATE):
- flash("You are not allowed to create pages.")
- abort(403)
- if request.method == 'POST':
- if request.form.get('preview'):
- return savepoint(request.form, is_preview=True)
- p_url = request.form['url'] or None
- if p_url:
- if not is_valid_url(p_url):
- flash('Invalid URL. Valid URLs contain only letters, numbers and hyphens.')
- return savepoint(request.form)
- elif not is_url_available(p_url):
- flash('This URL is not available.')
- return savepoint(request.form)
- p_tags = [x.strip().lower().replace(' ', '-').replace('_', '-').lstrip('#')
- for x in request.form.get('tags', '').split(',') if x]
- if any(not re.fullmatch(SLUG_RE, x) for x in p_tags):
- flash('Invalid tags text. Tags contain only letters, numbers and hyphens, and are separated by comma.')
- return savepoint(request.form)
- try:
- p = Page.create(
- url=p_url,
- title=request.form['title'],
- is_redirect=False,
- touched=datetime.datetime.now(),
- owner_id=current_user.id,
- calendar=datetime.date.fromisoformat(request.form["calendar"]) if 'usecalendar' in request.form else None,
- is_locked = 'lockpage' in request.form,
- is_cw = 'cw' in request.form
- )
- p.change_tags(p_tags)
- except IntegrityError as e:
- flash('An error occurred while saving this revision: {e}'.format(e=e))
- return savepoint(request.form)
- pr = PageRevision.create(
- page=p,
- user_id=p.owner.id,
- comment='',
- textref=PageText.create_content(request.form['text']),
- pub_date=datetime.datetime.now(),
- length=len(request.form['text'])
- )
- PageLink.parse_links(p, request.form['text'])
- return redirect(p.get_url())
- return savepoint({
- "url": request.args.get("url"),
- "title": "",
- "text": "",
- "tags": "",
- "comment": get_string(g.lang, "page-created")
- })
-
-@app.route('/edit//', methods=['GET', 'POST'])
-@login_required
-def edit(id):
- p = Page[id]
- if request.method == 'POST':
- # check if page is locked first!
- if not p.can_edit(current_user):
- flash('You are trying to edit a locked page!')
- abort(403)
-
- if request.form.get('preview'):
- return savepoint(request.form, is_preview=True, pageobj=p)
- p_url = request.form['url'] or None
- if p_url:
- if not is_valid_url(p_url):
- flash('Invalid URL. Valid URLs contain only letters, numbers and hyphens.')
- return savepoint(request.form, pageobj=p)
- elif not is_url_available(p_url) and p_url != p.url:
- flash('This URL is not available.')
- return savepoint(request.form, pageobj=p)
- p_tags = [x.strip().lower().replace(' ', '-').replace('_', '-').lstrip('#')
- for x in request.form.get('tags', '').split(',')]
- p_tags = [x for x in p_tags if x]
- if any(not re.fullmatch(SLUG_RE, x) for x in p_tags):
- flash('Invalid tags text. Tags contain only letters, numbers and hyphens, and are separated by comma.')
- return savepoint(request.form, pageobj=p)
- p.url = p_url
- p.title = request.form['title']
- p.touched = datetime.datetime.now()
- p.is_locked = 'lockpage' in request.form
- p.is_cw = 'cw' in request.form
- p.calendar = datetime.date.fromisoformat(request.form["calendar"]) if 'usecalendar' in request.form else None
- p.save()
- p.change_tags(p_tags)
- if request.form['text'] != p.latest.text:
- pr = PageRevision.create(
- page=p,
- user_id=current_user.id,
- comment=request.form["comment"],
- textref=PageText.create_content(request.form['text']),
- pub_date=datetime.datetime.now(),
- length=len(request.form['text'])
- )
- PageLink.parse_links(p, request.form['text'])
- return redirect(p.get_url())
-
- form = {
- "url": p.url,
- "title": p.title,
- "text": p.latest.text,
- "tags": ','.join(x.name for x in p.tags),
- "comment": ""
- }
- if p.is_locked:
- form["lockpage"] = "1"
- if p.calendar:
- form["usecalendar"] = "1"
- try:
- form["calendar"] = p.calendar.isoformat().split("T")[0]
- except Exception:
- form["calendar"] = p.calendar
-
- return savepoint(form, pageobj=p)
-
-@app.route("/__sync_start")
-def __sync_start():
- flash("Sync is unavailable. Please import and export pages manually.")
- return redirect("/")
-
-@app.route('/_jsoninfo/', methods=['GET', 'POST'])
-def page_jsoninfo(id):
- try:
- p = Page[id]
- except Page.DoesNotExist:
- return jsonify({'status':'fail'}), 404
- j = p.js_info()
- j["status"] = "ok"
- if request.method == "POST":
- j["text"] = p.latest.text
- return jsonify(j)
-
-@app.route("/_jsoninfo/changed/")
-def jsoninfo_changed(ts):
- tse = str(datetime.datetime.fromtimestamp(ts).isoformat(" "))
- ps = Page.select().where(Page.touched >= tse)
- return jsonify({
- "ids": [i.id for i in ps],
- "status": "ok"
- })
-
-
-@app.route('/p//')
-def view_unnamed(id):
- try:
- p = Page[id]
- except Page.DoesNotExist:
- abort(404)
- if p.url:
- if p.url not in forbidden_urls:
- return redirect(p.get_url())
- else:
- flash('The URL of this page is a reserved URL. Please change it.')
- return render_template('view.jinja2', p=p, rev=p.latest)
-
-@app.route('/embed//')
-def embed_view(id):
- try:
- p = Page[id]
- except Page.DoesNotExist:
- return "", 404
- rev = p.latest
- return "
+
+{% endblock %}
\ No newline at end of file
diff --git a/extensions/__init__.py b/salvi/templates/macros/icon.html
similarity index 100%
rename from extensions/__init__.py
rename to salvi/templates/macros/icon.html
diff --git a/templates/macros/nl.jinja2 b/salvi/templates/macros/nl.html
similarity index 88%
rename from templates/macros/nl.jinja2
rename to salvi/templates/macros/nl.html
index 5956fc8..e448d66 100644
--- a/templates/macros/nl.jinja2
+++ b/salvi/templates/macros/nl.html
@@ -1,11 +1,19 @@
+
+
{#
Recommendations: Always import this macro with context,
otherwise it fails. It depends on a couple context-defined functions.
#}
-{% macro nl_list(l, page_n=None, total_count=None, hl_tags=(), hl_calendar=None, other_url='p/most_recent') %}
-{% if page_n and total_count %}
+{# TODO rewrite to fit! #}
+{# TODO rewrite to fit! #}
+
+{% macro nl_list(l, hl_tags=(), hl_calendar=None, other_url='p/most_recent', is_main = False) %}
+{% set page_n = l.page %}
+{% set total_count = l.total %}
+
+{% if not is_main %}