This commit is contained in:
lwark
2025-09-17 07:52:16 -05:00
commit a2ff72dda8
584 changed files with 52247 additions and 0 deletions

119
.circleci/config.yml Normal file
View File

@@ -0,0 +1,119 @@
version: 2.1
orbs:
python: circleci/python@0.2.1
codecov: codecov/codecov@3.2.5
jobs:
hatch:
parameters:
hatch_env:
description: "Name of Hatch environment to run"
default: "py3.11-dj4.2"
type: string
python_version:
description: "Python version string"
default: "3.11"
type: string
description: "Reusable job for invoking hatch"
docker:
- image: cimg/python:<<parameters.python_version>>
steps:
- checkout
- run: pip install coverage[toml] hatch libsass
- run: python -m hatch --env test.<<parameters.hatch_env>> run all
- codecov/upload
lint:
description: "Simple job for linting the pushed code"
docker:
- image: cimg/python:3.11
steps:
- checkout
- run: pip install hatch libsass && python -m hatch --env test.py3.11-dj4.2 run lint
workflows:
test:
jobs:
- hatch:
name: "Python 3.9, Django 4.0"
hatch_env: "py3.9-dj4.0"
python_version: "3.9"
- hatch:
name: "Python 3.9, Django 4.1"
hatch_env: "py3.9-dj4.1"
python_version: "3.9"
- hatch:
name: "Python 3.9, Django 4.2"
hatch_env: "py3.9-dj4.2"
python_version: "3.9"
- hatch:
name: "Python 3.10, Django 4.0"
hatch_env: "py3.10-dj4.0"
python_version: "3.10"
- hatch:
name: "Python 3.10, Django 4.1"
hatch_env: "py3.10-dj4.1"
python_version: "3.10"
- hatch:
name: "Python 3.10, Django 4.2"
hatch_env: "py3.10-dj4.2"
python_version: "3.10"
- hatch:
name: "Python 3.10, Django 5.0"
hatch_env: "py3.10-dj5.0"
python_version: "3.10"
- hatch:
name: "Python 3.10, Django 5.1"
hatch_env: "py3.10-dj5.1"
python_version: "3.10"
- hatch:
name: "Python 3.10, Django 5.2"
hatch_env: "py3.10-dj5.2"
python_version: "3.10"
- hatch:
name: "Python 3.11, Django 4.1"
hatch_env: "py3.11-dj4.1"
python_version: "3.11"
- hatch:
name: "Python 3.11, Django 4.2"
hatch_env: "py3.11-dj4.2"
python_version: "3.11"
- hatch:
name: "Python 3.11, Django 5.0"
hatch_env: "py3.11-dj5.0"
python_version: "3.11"
- hatch:
name: "Python 3.11, Django 5.1"
hatch_env: "py3.11-dj5.1"
python_version: "3.11"
- hatch:
name: "Python 3.11, Django 5.2"
hatch_env: "py3.11-dj5.2"
python_version: "3.11"
- hatch:
name: "Python 3.12, Django 5.0"
hatch_env: "py3.12-dj5.0"
python_version: "3.12"
- hatch:
name: "Python 3.12, Django 5.1"
hatch_env: "py3.12-dj5.1"
python_version: "3.12"
- hatch:
name: "Python 3.12, Django 5.2"
hatch_env: "py3.12-dj5.2"
python_version: "3.12"
- hatch:
name: "Python 3.13, Django 5.0"
hatch_env: "py3.13-dj5.0"
python_version: "3.13"
- hatch:
name: "Python 3.13, Django 5.1"
hatch_env: "py3.13-dj5.1"
python_version: "3.13"
- hatch:
name: "Python 3.13, Django 5.2"
hatch_env: "py3.13-dj5.2"
python_version: "3.13"
- lint

34
.editorconfig Normal file
View File

@@ -0,0 +1,34 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 160
max_line_wrap = false
[*.py]
max_line_length = 160
quote_type = double
[*.{scss,js,html}]
indent_style = space
indent_size = 2
quote_type = double
[*.js]
indent_size = 2
quote_type = double
curly_bracket_next_line = false
[**.min.{js,css}]
indent_style = ignore
insert_final_newline = ignore
[Makefile]
indent_style = tab

2
.git-blame-ignore-revs Normal file
View File

@@ -0,0 +1,2 @@
# black code style on all files
254c4a2658894c8c993a3921bec2580a6138b49b

39
.github/DISCUSSION_TEMPLATE/bug.yml vendored Normal file
View File

@@ -0,0 +1,39 @@
title: "[Bug]: "
labels: ["Bug"]
body:
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: Steps to reproduce.
value: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
'...'
validations:
required: true
- type: textarea
attributes:
label: Expected behavior
description: A clear and concise description of what you expected to happen.
- type: input
attributes:
label: Python Version
placeholder: 3.7, 3.8, 3.9, 3.10, 3.11
validations:
required: true
- type: input
attributes:
label: Django Version
placeholder: 2.2, 3.0, 3.1, 3.2, 4.0, 4.1, 4.2
validations:
required: true
- type: textarea
attributes:
label: Extra context
description: Add any other context about the problem here.

35
.github/DISCUSSION_TEMPLATE/ideas.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
title: "[Feature]: "
labels: ["ideas"]
body:
- type: dropdown
attributes:
label: "I've already checked other feature proposals"
options:
- 'Yes'
- 'No'
validations:
required: true
- type: dropdown
attributes:
label: Is your feature request related to a problem?
options:
- 'Yes'
- 'No'
validations:
required: true
- type: textarea
attributes:
label: Describe your problem.
description: A clear and concise description of what the problem is.
- type: textarea
attributes:
label: Describe your feature request.
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
attributes:
label: Anything else we should know.
description: |
A clear and concise description of any alternative solutions or features you've considered.
Add any other context or screenshots about the feature request here.

11
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
blank_issues_enabled: true
contact_links:
- name: Bug Report
url: https://github.com/django-wiki/django-wiki/discussions/new?category=bug&title=[Bug]:&labels=bug
about: Submit a GitHub issue
- name: Feature Request
url: https://github.com/django-wiki/django-wiki/discussions/new?category=ideas&title=[Feature]:&labels=enhancement
about: Request or share ideas for new features to be added to Django Wiki
- name: Ask a Question
url: https://github.com/django-wiki/django-wiki/discussions/new?category=q-a&title=[Question]
about: Ask questions and discuss with other community members

8
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
open-pull-requests-limit: 5
schedule:
interval: "weekly"

20
.github/issue_template.md vendored Normal file
View File

@@ -0,0 +1,20 @@
**NOTE** Please use this option only if the discussions doesn't suit your needs.
## Expected Behavior
Tell us what should happen...
## Current Behavior
Tell us what happens instead of the expected behavior...
## Context (Environment)
* django-wiki version: ...
* Django version: ...
* Python version: ...
* Other details...
## Details
Please add logs or exception traces if relevant.

74
.gitignore vendored Normal file
View File

@@ -0,0 +1,74 @@
*.pyc
build
dist
*.egg-info
.eggs
testproject/testproject/whoosh_index/
testproject/testproject/xapian_index/
tests/media
# Ignore compiled version of source language
src/wiki/locale/en/LC_MESSAGES/django.mo
# Ignore Transifex managed msgids
src/wiki/locale/*/LC_MESSAGES/django.po
!src/wiki/locale/en/LC_MESSAGES/django.po
# Ignore this folder which is created by tests
wiki/attachments
#PyCharm
.idea
# Test artifacts
cache
wiki/images
#Docs
docs/_build
docs/_build/*
docs/wiki.*
docs/modules.rst
# Test project
testproject/testproject/settings/local.py
testproject/testproject/media/*
# Installer logs
pip-log.txt
# Unit test / coverage reports
htmlcov/
.coverage
.coverage.*
.tox
.cache
coverage.xml
*.cover
#Eclipse
.project
.pydevproject
.settings
#Visual Studio Code
.vscode
#Virtualenv
virtualenv
.venv
env/
#Mr Developer
.mr.developer.cfg
# text editors
*~
*.swp
*.db
*.sqlite3
__pycache__
/src/wiki/images/
/src.7z

31
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,31 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.3
hooks:
- id: ruff
language_version: python3
- id: ruff-format
language_version: python3
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
- id: trailing-whitespace
exclude: |
(?x)^(
.tx/|
src/wiki/static/wiki/bootstrap/js/.*
)$
- id: check-added-large-files
- id: debug-statements
- id: end-of-file-fixer
exclude: |
(?x)^(
.tx/|
src/wiki/static/wiki/bootstrap/js/.*|
.*\.map
)$
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: ["--py39-plus"]

13
.readthedocs.yml Normal file
View File

@@ -0,0 +1,13 @@
version: 2
build:
os: ubuntu-20.04
tools:
python: "3.11"
sphinx:
configuration: docs/conf.py
python:
install:
- method: pip
path: .
extra_requirements:
- docs

8
.tx/config Normal file
View File

@@ -0,0 +1,8 @@
[main]
host = https://www.transifex.com
[o:django-wiki:p:django-wiki:r:core]
file_filter = src/wiki/locale/<lang>/LC_MESSAGES/django.po
source_file = src/wiki/locale/en/LC_MESSAGES/django.po
source_lang = en
type = PO

46
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at info@django-wiki.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

45
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,45 @@
# Contributing
If you are a developer, please refer to the
[Developer Guide](http://django-wiki.readthedocs.io/en/latest/development/index.html)
## Support
**DO NOT USE GITHUB FOR SUPPORT INQUIRIES! USE IRC OR MAILING LIST!**
Django-wiki is community based, please try to be active. If you want help, plan
to give help, too. For instance, if you join IRC, then stay around and help
others.
## Issues
Contributions are appreciated! The following guide is a rough draft, but
please feel free to contribute to this contribution doc as well :D
When submitting an Issue, please provide the following:
* If it's a **feature request**, then write why *you* want it, but also which other
cases you find it useful for. Best way to get a new feature made by others
is to motivate.
* Think about challenges.
* Have you read the Manifesto (below) ? New features should maintain the focus
of the project.
* If you encounter a **bug**, keep in mind that it's probably easiest to fix if
a developer sat in front of your computer... but in lack of that option:
* `django-admin.py --version`
* `python --version`
* `uname -a`
* An example of how to reproduce the bug.
* The expected result.
* Does the bug happen with a checkout of django-wiki's `main` branch? To upgrade:
`pip install --upgrade git+https://github.com/django-wiki/django-wiki.git`
## Manifesto
Django needs a mature wiki system appealing to all kinds of needs, both big and small:
* **Be pluggable and light-weight.** Don't integrate optional features in the core.
* **Be open.** Make an extension API that allows the ecology of the wiki to grow. After all, Wikipedia consists of some [680 extensions](http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/) written for MediaWiki.
* **Be smart.** [This is](https://upload.wikimedia.org/wikipedia/commons/8/88/MediaWiki_database_schema_1-19_%28r102798%29.png) the map of tables in MediaWiki - we'll understand the choices of other wiki projects and make our own. After-all, this is a Django project.
* **Be simple.** The source code should *almost* explain itself.
* **Be structured.** Markdown is a simple syntax for readability. Features should be implemented either through easy coding patterns in the content field, but rather stored in a structured way (in the database) and managed through a friendly interface. This gives control back to the website developer, and makes knowledge more usable. Just ask: Why has Wikipedia never changed? Answer: Because it's knowledge is stored in a complicated way, thus it becomes very static.

674
COPYING Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
django-wiki Copyright (C) 2012 Benjamin Bach
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

252
README.rst Normal file
View File

@@ -0,0 +1,252 @@
django-wiki
===========
|Docs| |Build Status| |Coverage Status| |PyPi| |Downloads| |IRC|
.. |Docs| image:: https://readthedocs.org/projects/django-wiki/badge/?version=latest
:target: https://django-wiki.readthedocs.io/
.. |Build status| image:: https://circleci.com/gh/django-wiki/django-wiki.svg?style=shield
:target: https://circleci.com/gh/django-wiki/django-wiki
.. |Coverage Status| image:: https://codecov.io/github/django-wiki/django-wiki/coverage.svg?branch=main
:target: https://codecov.io/github/django-wiki/django-wiki?branch=main
.. |PyPi| image:: https://badge.fury.io/py/wiki.svg
:target: https://pypi.org/project/wiki/
.. |Downloads| image:: https://img.shields.io/pypi/dm/wiki.svg
:target: https://pypi.org/project/wiki/
.. |IRC| image:: https://img.shields.io/badge/irc-%23django--wiki%20on%20libera.chat-blue.svg
:target: https://web.libera.chat/?channel=#django-wiki
Django support
--------------
The table below explains which Django versions are supported.
+------------------+----------------+--------------+
| Release | Django | Upgrade from |
+==================+================+==============+
| 0.12.x | 4.0, 4.1, 4.2 | 0.10 or 0.11 |
| | 5.0, 5.1, 5.2 | |
+------------------+----------------+--------------+
| 0.11.x | 3.2, 4.0, 4.1, | 0.10 |
| | 4.2, 5.0, 5.1 | |
+------------------+----------------+--------------+
| 0.10.x | 2.2, 3.0, 3.1, | 0.7 |
| | 3.2, 4.0, 4.1, | |
| | 4.2 | |
+------------------+----------------+--------------+
| 0.9.x | 2.2, 3.0, 3.1, | 0.7 |
| | 3.2, 4.0 | |
+------------------+----------------+--------------+
| 0.8.x | 2.2, 3.0, 3.1, | 0.7 |
| | 3.2, 4.0 | |
+------------------+----------------+--------------+
| 0.7.x | 2.2, 3.0, 3.1, | 0.5 or 0.6 |
| | 3.2 | |
+------------------+----------------+--------------+
| 0.6.x | 2.1, 2.2, 3.0 | 0.5 |
+------------------+----------------+--------------+
| 0.5.x | 2.1, 2.2 | 0.4 |
+------------------+----------------+--------------+
| 0.4.x | 1.11, 2.0, 2.1 | 0.3 |
+------------------+----------------+--------------+
| 0.3.x | 1.8, 1.9, | 0.2 |
| | 1.10, 1.11 | |
+------------------+----------------+--------------+
| 0.2.x | 1.8, 1.9, 1.10 | 0.1 |
+------------------+----------------+--------------+
| 0.1.x | 1.5, 1.6, 1.7 | 0.0.24 |
+------------------+----------------+--------------+
| 0.0.24 | 1.4, 1.5, 1.6 | 0.0.? |
| | 1.7 (unstable) | |
+------------------+----------------+--------------+
For upgrade instructions, please refer to the `Release
Notes <https://django-wiki.readthedocs.io/en/latest/release_notes.html>`__
Translations (Transifex)
------------------------
Django-wiki is fully translated into 13 languages, apart from the
default (English) and some additional languages are underway.
But please help out by adding more languages!
It's very easy, and you don't need to be a programmer.
Some languages...
* ...just need a little push, as they are almost fully complete
* ...got initiated and need a new instigator to carry on the ambitions
* ...do not exist yet - but you can request them and become the coordinator
`Visit the django-wiki project on Transifex <https://www.transifex.com/django-wiki/django-wiki/>`__
Demo
----
A demo running the latest ``main`` branch is available here:
https://demo.django-wiki.org
Sign up for an account to see the notification system,
or you can log in with the existing account:
- user: ``admin``
- password:``admin``
Community
---------
Please use our IRC or mailing list (google group) to get in touch
on development and support. Please do not email developers asking for
personal support.
- Discussions on GitHub: `<https://github.com/django-wiki/django-wiki/discussions>`__
- `#django-wiki on libera.chat <https://web.libera.chat/?channel=#django-wiki>`__
- `django-wiki@googlegroups.com <https://groups.google.com/forum/#!forum/django-wiki>`__
- `Fediverse: @djangowiki@fosstodon.org <https://fosstodon.org/@djangowiki>`__
- `Twitter: @djangowiki <https://twitter.com/djangowiki>`__
*Always a work in progr...*
-----------------------------
On a number of factors,
this project has proven itself useful and stable.
- There won't be changes that are expected to cause loss of data without a proper upgrade path.
- The model API has been very stable and is only subject to smaller changes.
- The plugin API seems pretty stable.
- You can maintain the latest version of django-wiki through PyPi (package name: ``wiki``), using `SemVer <https://semver.org/>`__ versioning schema.
What should I customize? What can break?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You will need to learn a bit about Django to customize the django-wiki.
The simplest is to override templates and create your own template tags.
Do not make your own hard copy of this repository in order to fiddle with internal parts of the wiki,
this strategy will lead you to lose out on future updates with highly improved features, plugins, and security fixes.
You can also override the whole Bootstrap theming.
At present,
you're best off maintaining your own Bootstrap SCSS and hard-copying, then overriding django-wiki's rules.
All Python views are class-based.
However, for most cases, overriding views and URLs shouldn't be the best place to start
since most customization can be achieved through plugins, templates, and SCSS.
Contributing
------------
Contributions are welcome! ❤️
Please read our
`Developer Guide <https://django-wiki.readthedocs.io/en/latest/development/index.html>`__
Manifesto
---------
Django needs a mature wiki system appealing to all kinds of needs, both
big and small:
- **Be pluggable and lightweight.** Don't integrate optional features
in the core.
- **Be open.** Make an extension API that allows the ecology of the
wiki to grow in a structured way. Wikipedia consists of over `1100
extension projects <https://phabricator.wikimedia.org/diffusion/query/all/?after=1100>`__
written for MediaWiki. We should learn from this.
- **Be smart.** `This
is <https://upload.wikimedia.org/wikipedia/commons/f/f7/MediaWiki_1.24.1_database_schema.svg>`__
the map of tables in MediaWiki - we'll understand the choices of
other wiki projects and make our own. After all, this is a Django
project.
- **Be simple.** The source code should *almost* explain itself.
- **Be structured.** Markdown is a simple syntax for readability.
Features should be implemented either through easy coding patterns in
the content field, but rather stored in a structured way (in the
database) and managed through a friendly interface. This gives
control back to the website developer, and makes knowledge more
usable. Just ask: Why has Wikipedia never changed? Answer: Because
its knowledge is stored in a complicated way, thus it becomes very
static.
Docs
----
See the docs/ folder, or read them at:
https://django-wiki.readthedocs.io/en/latest/
If you wish to add something, please ask in the Google group or raise an
issue if you're in doubt about whether something might change.
Background
----------
Django-wiki is a rewrite of
`django-simplewiki <https://code.google.com/p/django-simple-wiki/>`__, a
project from 2009 that aimed to be a base system for a wiki. It proposed
that the user should customize the wiki by overwriting templates, but
soon learned that the only customization that really took place was that
people forked the entire project. We don't want that for django-wiki, we
want it to be modular and extendable.
As of now, Django has existed for too long without a proper wiki
application. The dream of django-wiki is to become a contestant
alongside Mediawiki, so that Django developers can stick to the Django
platform even when facing tough challenges such as implementing a wiki.
Q&A
---
- **Why is the module named just** ``wiki`` **?** Because when we tried
``pip install wiki``, it returned "No distributions at all found
for wiki", so we had to make up for that! ...oh, and django-wiki was occupied.
- **What markup language will you use?**
`Markdown <https://pypi.python.org/pypi/Markdown>`__. The markup
renderer is not a pluggable part but has been internalized into core
parts. Discussion should go here:
https://github.com/django-wiki/django-wiki/issues/76
- **Why not use django-reversion?** It's a great project, but if the
wiki has to grow ambitious, someone will have to optimize its
behavior, and using a third-party application for something as
crucial as the revision system is a no-go in this regard.
- **Any support for multiple wikis?** Yes, in a sense you can just
imagine that you always have multiple wikis, because you always have
hierarchies and full control of their permissions. See this
discussion: https://github.com/django-wiki/django-wiki/issues/63
Docker tl;dr
------------
There is a docker container available here: https://github.com/riotkit-org/docker-django-wiki
Acknowledgements
----------------
- The people at `edX <https://www.edx.org/>`__ & MIT for finding
and supporting the project both financially and with ideas.
- `django-mptt <https://github.com/django-mptt/django-mptt>`__, a
wonderful utility for inexpensively using tree structures in Django
with a relational database backend.
- `oscarmcm <https://github.com/oscarmcm>`__,
`atombrella <https://github.com/atombrella>`__,
`floemker <https://github.com/floemker>`__,
`rsalmaso <https://github.com/rsalmaso>`__,
`spookylukey <https://github.com/spookylukey>`__,
`jluttine <https://github.com/jluttine>`__,
`duvholt <https://github.com/duvholt>`__,
`valberg <https://github.com/valberg>`__,
`jdcaballerov <https://github.com/jdcaballerov>`__,
`yekibud <https://github.com/yekibud>`__,
`bridger <https://github.com/bridger>`__,
`TomLottermann <https://github.com/TomLottermann>`__,
`crazyzubr <https://github.com/crazyzubr>`__, and `everyone
else <https://github.com/django-wiki/django-wiki/graphs/contributors>`__
involved!
Original source of inspiration back in 2009 was django-cms,
Since then, Wagtail has also done a tremendous amount of work to promote Django models as a fundamental structure and enabler for application design.

17
SUPPORT.rst Normal file
View File

@@ -0,0 +1,17 @@
Getting support
===============
Please refer to our documentation before asking questions:
http://django-wiki.readthedocs.io/
* **DO NOT USE GITHUB FOR SUPPORT INQUIRIES!**
* **DO NOT EMAIL DEVELOPERS ASKING FOR SUPPORT!**
Django-wiki is community based. If you want support, then consider offering support to others. For instance, if you join IRC, then stay around and help others.
Please use your preferred support channels for getting answers to your questions.
* `StackOverflow tag:django-wiki <https://stackoverflow.com/tags/django-wiki>`__
* ``#django-wiki`` on irc.freenode.net
* `django-wiki@googlegroups.com <https://groups.google.com/forum/#!forum/django-wiki>`__

0
docs/__init__.py Normal file
View File

350
docs/conf.py Normal file
View File

@@ -0,0 +1,350 @@
import inspect
import os
import sys
from datetime import datetime
import bleach
import django
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_str as force_text
#
# django-wiki documentation build configuration file, created by
# sphinx-quickstart on Mon Jul 23 16:13:51 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath("../src"))
sys.path.insert(0, os.path.abspath("../testproject"))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings.dev")
django.setup()
# Auto list fields from django models - from https://djangosnippets.org/snippets/2533/#c5977
def process_docstring(app, what, name, obj, options, lines):
# This causes import errors if left outside the function
from django.db import models
# Only look at objects that inherit from Django's base model class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list from the meta class
fields = obj._meta.get_fields()
for field in fields:
# Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text'
if not hasattr(field, "verbose_name"):
continue
# Decode and strip any html out of the field's help text
help_text = bleach.clean(force_text(field.help_text), strip=True)
# Decode and capitalize the verbose name, for use if there isn't
# any help text
verbose_name = force_text(field.verbose_name).capitalize()
if help_text:
# Add the model field to the end of the docstring as a param
# using the help text as the description
lines.append(f":param {field.attname}: {help_text}")
else:
# Add the model field to the end of the docstring as a param
# using the verbose name as the description
lines.append(f":param {field.attname}: {verbose_name}")
# Add the field's type to the docstring
if isinstance(field, models.ForeignKey):
for to in field.to_fields:
lines.append(
":type %s: %s to :class:`~%s`"
% (field.attname, type(field).__name__, to)
)
else:
lines.append(f":type {field.attname}: {type(field).__name__}")
return lines
extlinks = {
"url-issue": (
"https://github.com/django-wiki/django-wiki/issues/%s",
"#%s",
),
}
def setup(app):
# Register the docstring processor with sphinx
app.connect("autodoc-process-docstring", process_docstring)
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.extlinks",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
# Fix: https://github.com/readthedocs/sphinx_rtd_theme/issues/1452
"sphinxcontrib.jquery",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "django-wiki"
copyright = f"{datetime.now().year}, Benjamin Bach" # noqa
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
sys.path = [path] + sys.path
sys.path = [os.path.join(path, "wiki")] + sys.path
import wiki # noqa
from wiki import __about__ # noqa
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ".".join(__about__.__version__.split(".")[0:100])
# The full version, including alpha/beta/rc tags.
release = __about__.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
linkcheck_ignore = [
r"wiki.+",
]
# -- Options for HTML output ---------------------------------------------------
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "django-wikidoc"
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
(
"index",
"django-wiki.tex",
"django-wiki Documentation",
"Benjamin Bach",
"manual",
),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
("index", "django-wiki", "django-wiki Documentation", ["Benjamin Bach"], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
"index",
"django-wiki",
"django-wiki Documentation",
"Benjamin Bach",
"django-wiki",
"Wiki engine for Django - with real data models!",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

78
docs/customization.rst Normal file
View File

@@ -0,0 +1,78 @@
Customization
=============
See :doc:`settings` for the settings that can be used to configure
django-wiki. Other ways to customize django-wiki for your use are listed below.
Templates
---------
django-wiki can be customized by providing your own templates.
All templates used by django-wiki inherit from ``wiki/base.html``, which in
turn simply inherits from ``wiki/base_site.html`` (adding
nothing). ``wiki/base_site.html`` provides a complete HTML page, but provides a
number of blocks that you might want to override. The most useful are:
* ``wiki_site_title``
* ``wiki_header_branding``
* ``wiki_header_navlinks``
These can be overridden to provide your own branding and links in the top bar of
the page, as well as in browser window title. The ``wiki/base_site.html``
template uses Bootstrap 3, so the following example shows how to use this in
practice, assuming you want a single link to your home page, and one to the
wiki. Add the following as ``wiki/base.html`` somewhere in your
``TEMPLATE_DIRS``:
.. code-block:: html+django
{% extends "wiki/base_site.html" %}
{% block wiki_site_title %} - Wiki{% endblock %}
{% block wiki_header_branding %}
<a class="navbar-brand" href="/">Your brand</a>
{% endblock %}
{% block wiki_header_navlinks %}
<ul class="nav navbar-nav">
<li class="active"><a href="{% url 'wiki:root' %}">Wiki</a></li>
</ul>
{% endblock %}
Site
----
You can override default django-wiki ``wiki.sites.site`` urls/views site implementation
with your own: override by setting the :attr:`~.WikiConfig.default_site` attribute
of a custom ``AppConfig`` to the dotted import path of either a ``WikiSite`` subclass
or a callable that returns a site instance.
.. code-block:: python
# myproject/sites.py
from wiki.sites import WikiSite
class MyWikiSite(admin.WikiSite):
...
.. code-block:: python
# myproject/apps.py
from wiki.apps import WikiConfig
class MyWikiConfig(WikiConfig):
default_site = 'myproject.sites.MyWikiSite'
.. code-block:: python
# myproject/settings.py
INSTALLED_APPS = [
...
'myproject.apps.MyWikiConfig', # replaces 'wiki.apps.WikiConfig'
...
]

View File

@@ -0,0 +1,14 @@
Setting up a development environment
====================================
* Fork and clone the ``django-wiki`` repo from Github, ``cd`` into it.
* Install `hatch <https://hatch.pypa.io/latest/install/>`_ with your favorite package manager.
* Inside ``django-wiki`` directory, initialize the environment::
$ hatch env create
* Launch a new shell session in order to activate the environment::
$ hatch shell
* And done, you can start developing in ``django-wiki``.

255
docs/development/hatch.rst Normal file
View File

@@ -0,0 +1,255 @@
pyproject.toml and hatch
========================
Initially, django-wiki core devs opted to use the
new ``pyproject.toml`` and drop the old ``setup.py`` (see
:url-issue:`1199`). The Python packaging ecosystem has
standardized on the interface for build backends
(`PEP 517 <https://peps.python.org/pep-0517/>`_/`PEP 660 <https://peps.python.org/pep-0660/>`_)
and the format for metadata declaration (`PEP 621 <https://peps.python.org/pep-0621/>`_/`PEP 631 <https://peps.python.org/pep-0631/>`_).
As a result, the execution of ``setup.py`` files is now `deprecated <https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html>`_.
The discussion for this feature and the steps to mark this as completed are
happening `in this discussion <https://github.com/django-wiki/django-wiki/discussions/1226>`_,
and as well the development process is `here <https://github.com/django-wiki/django-wiki/pull/1227>`_.
As a result of this work, the maintainers opted to use ``hatch`` to manage the
development process of django-wiki, you can read more about it in their
`official docs <https://hatch.pypa.io/latest/>`_.
Assuming you have installed ``hatch`` in your environment, the first thing that
you have to do in a fresh copy of ``django-wiki`` is to initilize the
environments, for that you have to execute ``hatch env create`` in the root of
``django-wiki`` codebase.
This will add a set of available commands, and different environment that are
used in the development process, here's a list generated with ``hatch env show``::
Standalone
+-----------+---------+---------------------------+-------------+
| Name | Type | Dependencies | Scripts |
+===========+=========+===========================+=============+
| default | virtual | black<22.11,>=22.3.0 | assets |
| | | codecov | clean-build |
| | | coverage[toml] | clean-pyc |
| | | ddt | cov |
| | | django-functest<1.6,>=1.2 | lint |
| | | flake8<5.1,>=3.7 | no-cov |
| | | pre-commit | test |
| | | pytest-cov | |
| | | pytest-django | |
| | | pytest-pythonpath | |
| | | pytest<7.3,>=6.2.5 | |
+-----------+---------+---------------------------+-------------+
| transifex | virtual | transifex-client | assets |
| | | | clean-build |
| | | | clean-pyc |
| | | | cov |
| | | | lint |
| | | | no-cov |
| | | | pull |
| | | | push |
| | | | test |
+-----------+---------+---------------------------+-------------+
| docs | virtual | bleach<5.1,>=3.3.0 | assets |
| | | django>=3.1.13 | build |
| | | sphinx-rtd-theme==1.1.1 | changes |
| | | sphinx>=3 | clean |
| | | | clean-build |
| | | | clean-pyc |
| | | | cov |
| | | | devhelp |
| | | | dirhtml |
| | | | doctest |
| | | | epub |
| | | | gettext |
| | | | html |
| | | | htmlhelp |
| | | | info |
| | | | json |
| | | | latex |
| | | | latexpdf |
| | | | link-check |
| | | | link-check2 |
| | | | lint |
| | | | man |
| | | | no-cov |
| | | | pickle |
| | | | qthelp |
| | | | singlehtml |
| | | | test |
| | | | texinfo |
| | | | text |
+-----------+---------+---------------------------+-------------+
Matrices
+------+---------+-------------------+---------------------------+-------------+
| Name | Type | Envs | Dependencies | Scripts |
+======+=========+===================+===========================+=============+
| test | virtual | test.py3.7-dj2.2 | black<22.11,>=22.3.0 | all |
| | | test.py3.7-dj3.0 | codecov | assets |
| | | test.py3.7-dj3.1 | coverage[toml] | clean |
| | | test.py3.7-dj3.2 | ddt | clean-build |
| | | test.py3.8-dj2.2 | django-functest<1.6,>=1.2 | clean-pyc |
| | | test.py3.8-dj3.0 | flake8<5.1,>=3.7 | cov |
| | | test.py3.8-dj3.1 | pre-commit | lint |
| | | test.py3.8-dj3.2 | pytest-cov | no-cov |
| | | test.py3.9-dj2.2 | pytest-django | test |
| | | test.py3.9-dj3.0 | pytest-pythonpath | |
| | | test.py3.9-dj3.1 | pytest<7.3,>=6.2.5 | |
| | | test.py3.9-dj3.2 | | |
| | | test.py3.10-dj3.2 | | |
| | | test.py3.8-dj4.0 | | |
| | | test.py3.9-dj4.0 | | |
| | | test.py3.10-dj4.0 | | |
+------+---------+-------------------+---------------------------+-------------+
We have 4 different environments declared in the configuration file, each one
has his own purpose:
* ``default``: The development environment for django-wiki.
* ``test``: where we ensure that the code works on different Django and Python versions.
* ``docs``: Used for generate the page you're reading at this moment.
* ``transifex``: Used only for the translation side of the project.
We center around the entrypoints provided by ``hatch`` (`read more <https://hatch.pypa.io/latest/environment/#scripts>`_)
that's why we have documented commands that make development easier.
Some commands are only available in certain environments,
so for example at the ``transifex`` environment you see ``pull`` and ``push``
commands that are not present in any other environment declared above. For
executing the command you have to follow this simple formula::
$ hatch run <environment name>:<command name>
Then applied to the ``push`` command on the ``transifex`` environment will be::
$ hatch run transifex:pull
You can use the same logic to execute the available commands in the app, but
heres a detailed list of the commands ordered by environments, so you can
understand the purpose of each one:
* ``cov``: Check coverage status.
* ``no-cov``: Check places pending to add coverage.
* ``lint``: Make sure the code changes follow our guidelines and conventions.
* ``clean-build``: Remove the files generated after the project is built.
* ``clean-pyc``: Remove pyc generated files.
* ``assets``: Generate the static files used by django-wiki frontend.
* ``test``: Test the changes in the current environment.
* ``test:all``: Test the changes across our supported Python and Django versions.
* ``test:lint``: Make sure the code changes follows our guidelines and conventions.
* ``test:clean``: Remove the files generated via the testing process.
* ``transifex:push``: Push the translation files to Transifex.
* ``transifex:pull``: Pull the translation files from Transifex.
* ``docs:clean``: Remove the generated documentation files.
* List of docs commands used to generate the documentation in different formats:
* Please refer to the `Builder documentation of SPHINX <https://www.sphinx-doc.org/en/master/usage/builders/index.html>`_
to understand more about the purpose of each builder and the expected output.
* ``docs:html``
* ``docs:dirhtml``
* ``docs:singlehtml``
* ``docs:pickle``
* ``docs:json``
* ``docs:htmlhelp``
* ``docs:qthelp``
* ``docs:devhelp``
* ``docs:epub``
* ``docs:latex``
* ``docs:latexpdf``
* ``docs:text``
* ``docs:man``
* ``docs:texinfo``
* ``docs:info``
* ``docs:gettext``
* ``docs:changes``
* ``docs:link-check2``
* ``docs:doctest``
* ``docs:build``: Generate the documentation in HTML format.
* ``docs:link-check``: Checks for external links across the documentation.
We hope that this document helps you to understand more about the development
process, if something is not clear please open an issue.
FAQ
---
1. **Whats the difference between test and test:all?**
When you execute ``hatch run test`` this will check your changes in the
active environment, this means it will run over an specific Python version
and an specific Django Version; in the other hand ``test:all`` will run the
test suite in the whole matrix of the supported versions of Python and Django.
2. **hatch is unable to create a test environment with an specific Python Version?**
If after you execute ``hatch env create`` you receive a message like this in
your terminal ``py3.8-4.0 -> cannot locate Python: 3.8`` this means that
``hatch`` was unable to locate that Python version, in the end it depends on
what program do you use for manage your Python version, the most
important part is that the versions must be available in your ``PATH``.
3. **How to manage different Python Versions?**
There's a lot of options outside, the most important piece is that as stated
above, the versions need to able to be located in your system ``PATH``. for
example, if you're a user of `pyenv <https://github.com/pyenv/pyenv>`_ you
can set multiple Python version using ``pyenv local <version> <version>``.
``pyenv local 3.7.12 3.8.12 3.9.13 3.10.2``
4. **There's an error when init an environment?**
If you see and error message like ``Environment default defines a matrix, choose one of the following instead:``
and then a list of all of the available environments, you need to set the
environment name on the shell command like this ``hatch -e <env_name> shell``
``hatch -e test.py3.10-dj3.2 shell``
This way you can switch environments by an specific Python and Django version.
5. **How do I switch default shell versions?**
By default django-wiki runs on the latest supported Python and Django
version, if you want to swich to another environment, say for example
Python 3.9.13 with Django 3.0 then execute the following command:
``hatch -e py3.9-dj3.0 shell``

146
docs/development/index.rst Normal file
View File

@@ -0,0 +1,146 @@
Developer guide
===============
.. toctree::
:maxdepth: 1
hatch
environment
testproject
testing
.. highlight:: shell
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/django-wiki/django-wiki/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug"
and "help wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
Django-wiki could always use more documentation, whether as part of the
official django-wiki docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/django-wiki/django-wiki/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `django-wiki` for local development.
#. Fork the `django-wiki` repo on GitHub.
#. Clone your fork locally::
$ git clone git@github.com:your_name_here/django-wiki.git
#. Go to your fork and install ``hatch`` which is the tool we use manage django-wiki
#. Install your local copy into a new environment. Assuming you have ``hatch`` installed, this is how you set up your fork for local development::
$ cd django-wiki/
$ hatch env create
#. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
#. As you are making changes you may want to verify that changes are
passing all the relevant functional/unit tests::
$ hatch run test:all
#. If you made changes related to the style sheets (SCSS), you need to install `sassc <https://sass-lang.com/libsass>`__ (``sudo apt install sassc``) and run this to compile css::
$ hatch run assets
#. When you're done making changes, perform one final round of
testing, and also ensure relevant tests pass with all supported
Python versions with our matrix::
$ hatch run test
$ hatch run test:all # Runs all tests that pytest would run, just with various Python/Django combinations
#. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
#. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 3.6, 3.7, 3.8 and for PyPy. Check
the status messages that are automatically generated for your pull request.
Tips
----
To run a subset of tests::
$ hatch run test:all tests/core/test_basic.py # All tests from a single file.
$ hatch run test:all tests/core/test_basic.py::URLPathTests # All tests from a single class.
$ hatch run test:all tests/core/test_basic.py::URLPathTests::test_manager # Just one test.
Roadmap
-------
The best way to contribute is to use our Github issue list to look
at current wishes. The list is found here:
https://github.com/django-wiki/django-wiki/issues/
If you want to add a feature, consider writing a plugin. Please create an
issue to discuss whether your plugin idea is a core plugin
(``wiki.plugins.*``) or external plugin. If there are additions needed
to the plugin API, we can discuss that as well! A discussion is always welcome
in a Github issue.
Generally speaking, we need more **unit tests** to improve coverage, and new
features will not be accepted without tests. To add more stuff to the project
without tests wouldn't be fair to the project or your hard work. We use coverage
metrics to see that each new contribution does not significantly impact test
coverage.

View File

@@ -0,0 +1,62 @@
Tests
=====
Running tests
-------------
To run django-wiki's tests, you need to have installed ``hatch`` (read
more about it `here <https://hatch.pypa.io/latest/install/>`_) once installed
you can execute ``hatch run test:all`` to test your changes across our matrix.
To run **specific tests**, see ``hatch run test:all --help``.
To include Selenium tests, you need to have ``Xvfb`` installed
(usually via system-provided package manager), `chromedriver
<https://sites.google.com/a/chromium.org/chromedriver/>`_ and set the
environment variable ``INCLUDE_SELENIUM_TESTS=1``. For example, run
tests with (depending on whether you want to test directly or via
the test matrix)::
INCLUDE_SELENIUM_TESTS=1 hatch run test
INCLUDE_SELENIUM_TESTS=1 hatch run test:all
If you wish to also show the browser window while running the
functional tests, set the environment variable
``SELENIUM_SHOW_BROWSER=1`` in *addition* to
``INCLUDE_SELENIUM_TESTS=1``, for example::
INCLUDE_SELENIUM_TESTS=1 SELENIUM_SHOW_BROWSER=1 hatch run test:all
Writing tests
-------------
Tests generally fall into a few categories:
* Testing at the model level. These test cases should inherit from
``tests.base.TestBase``.
* Tests for views that return HTML. We normally use `django-functest
<http://django-functest.readthedocs.io/en/latest/>`_ for these, especially if
the page involves forms and handling of POST data. Test cases should inherit
from ``tests.base.WebTestBase`` and ``tests.base.SeleniumBase`` - see
``tests.core.test_views.RootArticleViewTestsBase``,
``RootArticleViewTestsWebTest`` and ``RootArticleViewTestsSelenium`` for an
example.
(In the past the Django test Client was used for these, and currently there
are still a lot of tests written in this style. These should be gradually
phased out where possible, because the test Client does a poor job of
replicating what browsers and people actually do.
* Tests for views that return JSON or other non-HTML. These test cases
should inherit from ``tests.base.DjangoClientTestBase``.
There are also other mixins in ``tests.base`` that provide commonly used
fixtures for tests e.g. a root article.
.. warning::
Views should be written so that as far as possible they work without
Javascript, and can be tested using the fast WebTest method, rather than
relying on the slow and fragile Selenium method. Selenium tests are not run by
default.

View File

@@ -0,0 +1,10 @@
Running the test project
========================
In order to quickly get setup, there is a project in the git repository.
The folder **testproject/** contains a pre-configured django project and
an sqlite database. Login for django admin is ``admin:admin``. This
project should always be maintained, but please do not commit changes to
the SQLite database as we only care about its contents in case data
models are changed.

28
docs/index.rst Normal file
View File

@@ -0,0 +1,28 @@
.. django-wiki documentation master file, created by
sphinx-quickstart on Mon Jul 23 16:13:51 2012.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
django-wiki documentation
=========================
.. toctree::
:name: mastertoc
:maxdepth: 1
installation
release_notes
plugins
customization
settings
development/index
tips/index
.. include:: ../README.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

196
docs/installation.rst Normal file
View File

@@ -0,0 +1,196 @@
Installation
============
django-wiki is an application for Django.
This means that you need to setup a basic Django project in order to use django-wiki.
.. seealso::
Read more about setting up your first Django project in the
`official Django tutorial <https://docs.djangoproject.com/en/stable/intro/tutorial01/>`__.
Pre-requisite: Pillow
---------------------
For image processing, django-wiki uses the `Pillow
library <https://github.com/python-pillow/Pillow>`_ (a fork of PIL).
The preferred method should be to get a system-wide, pre-compiled
version of Pillow, for instance by getting the binaries from your Linux
distribution repos.
Debian/Ubuntu
~~~~~~~~~~~~~
You need to get development libraries which Pip needs for compiling::
sudo apt-get install libjpeg8 libjpeg-dev libpng12-0 libpng12-dev
After that, install with ``sudo pip install Pillow``. You might as well
install Pillow system-wide, because there are little version-specific
dependencies in Django applications when it comes to Pillow, and having
multiple installations of the very same package is a bad practice in
this case.
Mac OS X 10.5+
~~~~~~~~~~~~~~
`Ethan
Tira-Thompson <http://ethan.tira-thompson.com/Mac_OS_X_Ports.html>`_ has
created ports for OS X and made them available as a .dmg installer.
Download and install the universal combo package
`here <http://ethan.tira-thompson.com/Mac_OS_X_Ports_files/libjpeg-libpng%20%28universal%29.dmg>`_.
Once you have the packages installed, you can proceed to the pip
installation. PIL will automatically pick up these libraries and compile
them for django use.
Installing
----------
To install the latest stable release::
pip install wiki
Install the latest pre-release (alpha, beta or rc)::
pip install --pre wiki
Upgrading
---------
Always read the :doc:`release_notes` for instructions on upgrading.
Configuration
-------------
Configure ``settings.INSTALLED_APPS``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following applications should be listed - NB! it's important to
maintain the order due to database relational constraints:
.. code-block:: python
'django.contrib.sites.apps.SitesConfig',
'django.contrib.humanize.apps.HumanizeConfig',
'django_nyt.apps.DjangoNytConfig',
'mptt',
'sekizai',
'sorl.thumbnail',
'wiki.apps.WikiConfig',
'wiki.plugins.attachments.apps.AttachmentsConfig',
'wiki.plugins.notifications.apps.NotificationsConfig',
'wiki.plugins.images.apps.ImagesConfig',
'wiki.plugins.macros.apps.MacrosConfig',
Configure ``context_processors``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``django-wiki`` uses the `Django Templates` backend.
Add ``'sekizai.context_processors.sekizai'`` and ``'django.template.context_processors.debug'`` to
``context_processors`` section of your template backend settings.
Please refer to the `Django templates docs <https://docs.djangoproject.com/en/stable/topics/templates/#django.template.backends.django.DjangoTemplates/>`_
to see the current default setting for this variable.
.. code-block:: python
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
# ...
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.request',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
"sekizai.context_processors.sekizai",
],
},
},
]
Database
~~~~~~~~
To sync and create tables, do:
::
python manage.py migrate
Set ``SITE_ID``
~~~~~~~~~~~~~~~
If you're working with fresh Django installation, you need to set the SITE_ID
.. code-block:: python
SITE_ID = 1
User account handling
~~~~~~~~~~~~~~~~~~~~~
There is a limited account handling included to allow users to sign up. Its
settings are shown below with their default values. To switch off account
handling entirely, set ``WIKI_ACCOUNT_HANDLING = False``.
.. code-block:: python
WIKI_ACCOUNT_HANDLING = True
WIKI_ACCOUNT_SIGNUP_ALLOWED = True
After a user is logged in, they will be redirected to the value of
``LOGIN_REDIRECT_URL``, which you can configure in your project's settings.py to
point to the root article:
.. code-block:: python
from django.urls import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('wiki:get', kwargs={'path': ''})
Include urlpatterns
~~~~~~~~~~~~~~~~~~~
To integrate the wiki in your existing application, you should ensure the
following lines are included in your project's ``urls.py``.
.. code-block:: python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('notifications/', include('django_nyt.urls')),
path('', include('wiki.urls'))
]
The above line puts the wiki in */* so it's important to put it at the
end of your urlconf. You can also put it in */wiki* by putting
``'^wiki/'`` as the pattern.
.. note::
If you are running ``manage.py runserver``, you need to have static files
and media files from ``STATIC_ROOT`` and ``MEDIA_ROOT`` served by the
development server. ``STATIC_ROOT`` is automatically served, but you have
to add ``MEDIA_ROOT`` manually::
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Please refer to
`the Django docs <https://docs.djangoproject.com/en/stable/howto/static-files/#serving-files-uploaded-by-a-user-during-development>`__.

18
docs/plugins.rst Normal file
View File

@@ -0,0 +1,18 @@
Plugins
=======
Add/remove the following to your ``settings.INSTALLED_APPS`` to
enable/disable the core plugins:
- ``'wiki.plugins.attachments.apps.AttachmentsConfig'``
- ``'wiki.plugins.editsection.apps.EditSectionConfig'``
- ``'wiki.plugins.globalhistory.apps.GlobalHistoryConfig'``
- ``'wiki.plugins.help.apps.HelpConfig'``
- ``'wiki.plugins.images.apps.ImagesConfig'``
- ``'wiki.plugins.links.apps.LinksConfig'``
- ``'wiki.plugins.macros.apps.MacrosConfig'``
- ``'wiki.plugins.notifications.apps.NotificationsConfig'``
The notifications plugin is mandatory for an out-of-the-box installation. You
can safely remove it from ``INSTALLED_APPS`` if you also override the
**wiki/base.html** template.

1084
docs/release_notes.rst Normal file

File diff suppressed because it is too large Load Diff

41
docs/settings.rst Normal file
View File

@@ -0,0 +1,41 @@
Settings
========
The following settings are available for configuration through your project.
All settings are customized by prefixing ``WIKI_``, so for instance
``URL_CASE_SENSITIVE`` should be configured as ``WIKI_URL_CASE_SENSITIVE``.
For plugins the prefix is ``WIKI_PLUGINNAME_``, e.g. ``WIKI_IMAGES`` for the
images plugin.
.. automodule:: wiki.conf.settings
:members:
Plugin attachments
------------------
.. automodule:: wiki.plugins.attachments.settings
:members:
Plugin editsection
------------------
.. automodule:: wiki.plugins.editsection.settings
:members:
Plugin images
-------------
.. automodule:: wiki.plugins.images.settings
:members:
Plugin links
------------
.. automodule:: wiki.plugins.links.settings
:members:
Plugin macros
-------------
.. automodule:: wiki.plugins.macros.settings
:members:

39
docs/tips/disqus.rst Normal file
View File

@@ -0,0 +1,39 @@
Disqus comment embed
====================
This page describes how to embed the Disqus_ comment system on each wiki page.
Put the following as ``wiki/base.html`` somewhere in your
``TEMPLATE_DIRS``:
.. code-block:: html+django
{% extends "wiki/base_site.html" %}
{% load sekizai_tags %}
{% block wiki_body %}
{{ block.super }}
{% block wiki_footer_logo %}
{% endblock wiki_footer_logo %}
{% if selected_tab == 'view' %}
{% addtoblock "js" %}
<script type="text/javascript">
(function(){
$("#wiki-footer p").eq(0).after('<div id="disqus_thread"></div>')
})();
var disqus_shortname = 'your_disqus_shortname';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
{% endaddtoblock %}
{% endif %}
{% endblock wiki_body %}
Replace ``your_disqus_sortname`` with your disqus sortname.
See also in :doc:`/customization`.
.. _Disqus: https://disqus.com/

32
docs/tips/faq.rst Normal file
View File

@@ -0,0 +1,32 @@
FAQ
===
Q: Why can't I move articles?
-----------------------------
A: Moving articles is not trivial. Here are a couple of reasons:
* Other articles may link to them.
* Permissions may change if you move the articles into a different hierarchy
* We keep revisions of stuff, so the action of moving an article will create a new revision.
* ...but what if the revision is reverted and we had automatically renamed stuff?
Because it isn't trivial to move articles, the work has delayed somewhat.
Resources:
* `Pull Request #461 <https://github.com/django-wiki/django-wiki/pull/461>`__
* `Issue #154 <https://github.com/django-wiki/django-wiki/issues/154>`__
Q: Why do I keep getting *"This slug conflicts with an existing URL."*
----------------------------------------------------------------------
A: When validating a slug, django-wiki will verify through
:doc:`../settings`.``WIKI_CHECK_SLUG_URL_AVAILABLE`` (default: ``True``) that the URL is not
already occupied.
So if you keep getting an error that the "slug" isn't available, it's
probably because you left another URL pattern interfearing with django-wiki's
by letting your pattern (regexp) be too open. Forgetting a closing
``$`` is a common mistake.

38
docs/tips/index.rst Normal file
View File

@@ -0,0 +1,38 @@
Tips & FAQ
==========
.. toctree::
:caption: Tips index
faq
disqus
mediawiki
Quick tips
----------
1. **Account handling:** There are simple views that handle login,
logout and signup. They are on by default. Make sure to set
``settings.LOGIN_URL`` to point to your login page as many wiki views
may redirect to a login page.
2. **Syntax highlighting:** Python-Markdown has a pre-shipped codehilite
extension which works perfectly, so add something like::
WIKI_MARKDOWN_KWARGS = {
'extensions': [
'footnotes',
'attr_list',
'headerid',
'extra',
'codehilite',
]
}
to your settings. Currently, django-wiki ships with a stylesheet
that already has the syntax highlighting CSS rules built-in. Oh, and
you need to ensure ``pip install pygments`` because Pygments is what
the codehilite extension is using!
3. **Project Templates:** Create new django-wiki projects quickly and easily using django-wiki project templates
https://github.com/django-wiki/django-wiki-project-template

150
docs/tips/mediawiki.rst Normal file
View File

@@ -0,0 +1,150 @@
Mediawiki
=========
If you want to import articles from Mediawiki, you can create an XML dump of the pages and then use
a Django management command to import it.
The management command is not provided as part of django-wiki, but we'll show you how to build one for your own Django app.
In the management command, we are going to use the lxml library to parse the MediaWiki XML
and the unidecode to convert non-latin characters to ascii (so as to create their slug). Finally it
uses pandoc to do conversion from MediaWiki markup to GitHub Flavored Markdown (which in this case renders fine in django-wiki).
For the lxml and unidecode you can install them with ``pip install lxml unidecode`` and for pandoc you can
download it from https://pandoc.org/installing.html (make sure the pandoc binary is in your PATH).
The following snippet of code should be placed in ``<your-app>/management/commands/import_mediawiki_dump.py``:
.. code-block:: python
from django.core.management.base import BaseCommand
from wiki.models.article import ArticleRevision, Article
from wiki.models.urlpath import URLPath
from django.contrib.sites.models import Site
from django.template.defaultfilters import slugify
import unidecode
from django.contrib.auth import get_user_model
import datetime
import pytz
from django.db import transaction
import subprocess
from lxml import etree
def slugify2(s):
return slugify(unidecode.unidecode(s))
def convert_to_markdown(text):
proc = subprocess.Popen(
["pandoc", "-f", "mediawiki", "-t", "gfm"],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
proc.stdin.write(text.encode("utf-8"))
proc.stdin.close()
return proc.stdout.read().decode("utf-8")
def create_article(title, text, timestamp, user):
text_ok = (
text.replace("__NOEDITSECTION__", "")
.replace("__NOTOC__", "")
.replace("__TOC__", "")
)
text_ok = convert_to_markdown(text_ok)
article = Article()
article_revision = ArticleRevision()
article_revision.content = text_ok
article_revision.title = title
article_revision.user = user
article_revision.owner = user
article_revision.created = timestamp
article.add_revision(article_revision, save=True)
article_revision.save()
article.save()
return article
def create_article_url(article, slug, current_site, url_root):
upath = URLPath.objects.create(
site=current_site, parent=url_root, slug=slug, article=article
)
article.add_object_relation(upath)
def import_page(current_site, url_root, text, title, timestamp, replace_existing, user):
slug = slugify2(title)
try:
urlp = URLPath.objects.get(slug=slug)
if not replace_existing:
print("\tAlready existing, skipping...")
return
print("\tDestorying old version of the article")
urlp.article.delete()
except URLPath.DoesNotExist:
pass
article = create_article(title, text, timestamp, user)
create_article_url(article, slug, current_site, url_root)
class Command(BaseCommand):
help = "Import everything from a MediaWiki XML dump file. Only the latest version of each page is imported."
args = ""
def add_arguments(self, parser):
parser.add_argument("file", type=str)
@transaction.atomic()
def handle(self, *args, **options):
user = get_user_model().objects.get(username="root")
current_site = Site.objects.get_current()
url_root = URLPath.root()
tree = etree.parse(options["file"])
pages = tree.xpath('// *[local-name()="page"]')
for p in pages:
title = p.xpath('*[local-name()="title"]')[0].text
print(title)
revision = p.xpath('*[local-name()="revision"]')[0]
text = revision.xpath('*[local-name()="text"]')[-1].text
timestamp = revision.xpath('*[local-name()="timestamp"]')[0].text
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
timestamp_with_timezone = pytz.utc.localize(timestamp)
import_page(
current_site,
url_root,
text,
title,
timestamp_with_timezone,
True,
user,
)
Usage
-----
Once the management command is provided by your Django application, you can invoke it from the command-line:
.. code-block:: console
python manage.py import_mediawiki_dump <mediawiki-xml-dump-file>``
Further work and customizing
----------------------------
Please note the following:
- The script defines a ``root`` user to assign the owner of the imported pages (you can leave that as None or add your own user).
- Multiple revisions of each page have not been implemented. Instead, the script tries to pick the text of the latest one (``text = revision.xpath('*[local-name()="text"]')[-1].text``). Because of this, it's recommended to only include the latest revision of each article on your MediaWiki dump.
- You can pass ``True`` or ``False`` to ``import_page()`` in order to replace or skip existing pages.

337
pyproject.toml Normal file
View File

@@ -0,0 +1,337 @@
[build-system]
requires = ["hatchling", "hatch-build-scripts"]
build-backend = "hatchling.build"
[project]
name = "wiki"
description = "A wiki system written for the Django framework."
readme = "README.rst"
requires-python = ">=3.9"
license = "GPL-3.0"
keywords = ["django", "wiki", "markdown"]
authors = [
{ name = "Benjamin Bach", email = "benjamin@overtag.dk" },
]
maintainers = [
{ name = "Oscar Cortez", email = "om.cortez.2010@gmail.com" },
]
classifiers = [
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Wiki",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries :: Application Frameworks",
]
dependencies = [
# Django version support is added one minor release at a time
"Django>=4.0,<5.3",
# bleach has been pretty stable, hence the loose pin
"bleach[css]>=6,<7",
# Pillow is used very little and has never broken
"Pillow",
# django-nyt is maintained by django-wiki maintainers, so we can
# control breakage and pinning ourselves
"django-nyt>=1.4.2,<1.5",
# django-mptt has had several breaking changes
"django-mptt>=0.13,<0.17",
# django-sekizai is basically only releasing every time
# it needs to restore support for a new Django/Python version
"django-sekizai>=0.10",
# sorl-thumbnail is maintained by jazzband so it might be
# very stable but it might also suddenly invite breaking changes
"sorl-thumbnail>=12.8,<13",
# django-wiki's integration with Markdown is really detailed,
# several extensions have imported internal APIs, so be very
# careful here.
"Markdown>=3.4,<3.10",
# Set of extensions for Python Markdown.
"pymdown-extensions>=10.5,<10.6",
]
dynamic = ["version"]
[project.optional-dependencies]
docs = [
"sphinx>=6,<8",
"sphinx_rtd_theme==2.0.0",
]
[project.urls]
Homepage = "http://www.django-wiki.org"
Documentation = "https://django-wiki.readthedocs.io/en/latest/"
Tracker = "https://github.com/django-wiki/django-wiki/issues"
Source = "https://github.com/django-wiki/django-wiki"
[[tool.hatch.build.hooks.build-scripts.scripts]]
out_dir = "."
commands = [
"""
python -c "import os, subprocess, shutil;
readthedocs_env = os.environ.get('READTHEDOCS_VIRTUALENV_PATH');
print('Building SCSS files.');
if readthedocs_env:
print('READTHEDOCS_VIRTUALENV_PATH is set, skipping SASS compilation');
elif shutil.which('pysassc') is None:
print('pysassc not found, please install it to proceed.');
else:
result = subprocess.run(
[
'pysassc',
'--style',
'compressed',
'src/wiki/static/wiki/bootstrap/scss/wiki/wiki-bootstrap.scss',
'src/wiki/static/wiki/bootstrap/css/wiki-bootstrap.min.css'
],
check=False,
capture_output=True,
text=True,
);
if result.returncode != 0:
print('Error during SASS compilation:', result.stderr);
exit(result.returncode);
"
"""
]
artifacts = [
# "wiki-bootstrap.min.css",
]
clean_artifacts = false
# clean_out_dir = true
[tool.hatch.publish.index]
disable = true
[tool.hatch.version]
path = "src/wiki/__about__.py"
[tool.hatch.build.targets.sdist]
include = [
"COPYING",
"README.rst",
"/src",
]
exclude = [
"src/wiki/locale/en/LC_MESSAGES/django.mo",
]
[tool.hatch.envs.default]
dependencies = [
"ruff==0.1.3",
"ddt==1.6.0",
"django-functest>=1.2,<1.6",
"pre-commit==3.5.0",
"pytest-cov",
"pytest-django",
"pytest-pythonpath",
"pytest>=6.2.5,<7.3",
"hatch-build-scripts==0.0.4",
]
[tool.hatch.envs.default.scripts]
lint = [
"ruff check src/wiki tests/ {args}",
"pre-commit install -f --install-hooks",
"pre-commit run --all-files --show-diff-on-failure",
]
format = "ruff format src/wiki tests/ {args}"
clean = [
"hatch run clean-build",
"hatch run clean-pyc",
"rm -fr htmlcov/",
]
clean-build = [
"rm -fr build",
"rm -fr dist",
"rm -fr .eggs",
"find . -name '*.egg-info' -exec rm -fr {{}} +",
"find . -name '*.egg' -exec rm -f {{}} +",
]
clean-pyc = [
"find . -name '*.pyc' -exec rm -f {{}} +",
"find . -name '*.pyo' -exec rm -f {{}} +",
"find . -name '*~' -exec rm -f {{}} +",
"find . -name '__pycache__' -exec rm -fr {{}} +",
]
test = "pytest {args}"
[tool.hatch.envs.test.overrides]
matrix.django.dependencies = [
{ value = "django~={matrix:django}" },
]
[tool.hatch.envs.test]
matrix-name-format = "dj{value}"
[tool.hatch.envs.test.scripts]
all = [
"sh -c 'testproject/manage.py makemigrations --check'",
"pytest tests/ --cov=wiki {args}",
]
[[tool.hatch.envs.test.matrix]]
python = ["3.9", "3.10"]
django = ["4.0"]
[[tool.hatch.envs.test.matrix]]
python = ["3.9", "3.10", "3.11"]
django = ["4.1", "4.2"]
[[tool.hatch.envs.test.matrix]]
python = ["3.10", "3.11", "3.12", "3.13"]
django = ["5.0", "5.1", "5.2"]
[tool.hatch.envs.transifex]
dependencies = []
[tool.hatch.envs.transifex.scripts]
push = [
"touch ~/.transifexrc",
# Recipe: https://github.com/transifex/cli#running-from-docker-beta
"docker run --rm -i -t -v `pwd`:/app -v ~/.transifexrc:/.transifexrc -v /etc/ssl/certs/ca-certificates.crt:/etc/ssl/certs/ca-certificates.crt transifex/txcli --root-config /.transifexrc push -s",
]
pull = [
"touch ~/.transifexrc",
# Recipe: https://github.com/transifex/cli#running-from-docker-beta
"docker run --rm -i -t -v `pwd`:/app -v ~/.transifexrc:/.transifexrc -v /etc/ssl/certs/ca-certificates.crt:/etc/ssl/certs/ca-certificates.crt transifex/txcli --root-config /.transifexrc pull -a",
# This can have permission errors because of Docker
# In this case, run chown -R USERNAME:USERGROUP src/wiki/locale
"cd src/wiki && django-admin compilemessages",
]
[tool.hatch.envs.docs]
dependencies = [
"sphinx>=6,<8",
"sphinx_rtd_theme==2.0.0",
]
[tool.hatch.envs.docs.scripts]
clean = "rm -rf docs/_build/*"
html = "sphinx-build -c docs -b html -d docs/_build/doctrees docs/ docs/_build/html"
dirhtml = "sphinx-build -c docs -b dirhtml -d docs/_build/doctrees docs/ docs/_build/dirhtml"
singlehtml = "sphinx-build -c docs -b singlehtml -d docs/_build/doctrees docs/ docs/_build/singlehtml"
pickle = "sphinx-build -c docs -b pickle -d docs/_build/doctrees docs/ docs/_build/pickle"
json = "sphinx-build -c docs -b json -d docs/_build/doctrees docs/ docs/_build/json"
htmlhelp = [
"sphinx-build -c docs -b htmlhelp -d docs/_build/doctrees docs/ docs/_build/htmlhelp",
"echo 'Build finished; now you can run HTML Help Workshop with the .hhp project file in docs/_build/htmlhelp.'",
]
qthelp = [
"sphinx-build -c docs -b qthelp -d docs/_build/doctrees docs/ docs/_build/qthelp",
"echo 'Build finished; now you can run qcollectiongenerator with the .qhcp project file in docs/_build/qthelp, like this:'",
"echo '# qcollectiongenerator docs/_build/qthelp/django-wiki.qhcp'",
"echo 'To view the help file:'",
"echo '# assistant -collectionFile docs/_build/qthelp/django-wiki.qhc'",
]
devhelp = [
"sphinx-build -c docs -b devhelp -d docs/_build/doctrees docs/ docs/_build/devhelp",
"echo 'Build finished.'",
"echo 'To view the help file:'",
"echo '# mkdir -p $$HOME/.local/share/devhelp/django-wiki'",
"echo '# ln -s docs/_build/devhelp $$HOME/.local/share/devhelp/django-wiki'",
"echo '# devhelp'",
]
epub = "sphinx-build -c docs -b epub -d docs/_build/doctrees docs/ docs/_build/epub"
latex = [
"sphinx-build -c docs -b latex -d docs/_build/doctrees -D latex_paper_size={args} docs/ docs/_build/latext",
"echo 'Build finished; the LaTeX files are in docs/_build/latex.'",
"echo 'Run `make` in that directory to run these through (pdf)latex'",
"echo '(use `make latexpdf` here to do that automatically).'",
]
latexpdf = [
"sphinx-build -c docs -b latex -d docs/_build/doctrees -D latex_paper_size={args} docs/ docs/_build/latext",
"echo 'Running LaTeX files through pdflatex...'",
"make -C docs/_build/latex all-pdf",
"echo 'pdflatex finished; the PDF files are in docs/_build/latex.'",
]
text = "sphinx-build -c docs -b text -d docs/_build/doctrees docs/ docs/_build/text"
man = "sphinx-build -c docs -b man -d docs/_build/doctrees docs/ docs/_build/man"
texinfo = [
"sphinx-build -c docs -b text -d docs/_build/doctrees docs/ docs/_build/text",
"echo 'Build finished. The Texinfo files are in docs/_build/texinfo.'",
"echo 'Run `make` in that directory to run these through makeinfo'",
"echo '(use `make info` here to do that automatically).'",
]
info = [
"sphinx-build -c docs -b texinfo -d docs/_build/doctrees docs/ docs/_build/texinfo",
"echo 'Running Texinfo files through makeinfo...'",
"make -C docs/_build/texinfo info",
"echo 'makeinfo finished; the Info files are in docs/_build/texinfo.'",
]
gettext = "sphinx-build -c docs -b gettext docs/_build/locale"
changes = "sphinx-build -c docs -b changes -d docs/_build/doctrees docs/ docs/_build/changes"
link-check2 = "sphinx-build -c docs -b linkcheck -d docs/_build/doctrees docs/ docs/_build/linkcheck"
doctest = "sphinx-build -c docs -b doctest -d docs/_build/doctrees docs/ docs/_build/doctest"
build = [
"hatch run docs:clean",
"rm -f docs/wiki*.rst",
"rm -f docs/modules.rst",
"sphinx-apidoc -o docs/ src/wiki",
"hatch run docs:html {args}",
"""
python -c '
import os, webbrowser, sys
try:
from urllib import pathname2url
except:
from urllib.request import pathname2url
webbrowser.open(\"file://\" + pathname2url(os.path.abspath(\"docs/_build/html/index.html\")))
'"""
]
link-check = "sphinx-build -b linkcheck ./docs ./docs/_build"
[tool.coverage.run]
disable_warnings = ['no-data-collected']
branch = true
parallel = true
source = [
"src/",
]
omit = [
".DS_Store",
"*/tests/*",
"src/wiki/__about__.py",
]
[tool.coverage.report]
exclude_lines = [
"no cov",
"if __name__ == .__main__.:",
"if TYPE_CHECKING:",
]
[tool.ruff]
exclude = ["env", "_build", "CVS", "__pycache__", ".eggs", "*.egg", "*/*migrations", "testproject"]
extend-ignore = ["E203"]
line-length = 79
[tool.ruff.mccabe]
max-complexity = 10
[tool.pytest.ini_options]
django_find_project = false
testpaths = [
"tests",
]
norecursedirs = [
"testproject",
".svn",
"_build",
"tmp*",
"dist",
"*.egg-info",
]
DJANGO_SETTINGS_MODULE = "tests.settings"

22
src/manage.py Normal file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wiki_main.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

1
src/wiki/__about__.py Normal file
View File

@@ -0,0 +1 @@
__version__ = "0.12.1"

17
src/wiki/__init__.py Normal file
View File

@@ -0,0 +1,17 @@
# This package and all its sub-packages are part of django-wiki,
# except where otherwise stated.
#
# django-wiki is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django-wiki is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django-wiki. If not, see <http://www.gnu.org/licenses/>.
default_app_config = "wiki.apps.WikiConfig"

107
src/wiki/admin.py Normal file
View File

@@ -0,0 +1,107 @@
from django import forms
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from django.utils.translation import gettext_lazy as _
from mptt.admin import MPTTModelAdmin
from . import editors
from . import models
class ArticleObjectAdmin(GenericTabularInline):
model = models.ArticleForObject
extra = 1
max_num = 1
raw_id_fields = ("article",)
class ArticleRevisionForm(forms.ModelForm):
class Meta:
model = models.ArticleRevision
exclude = ()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO: This pattern is too weird
editor = editors.getEditor()
self.fields["content"].widget = editor.get_admin_widget(self.instance)
class ArticleRevisionAdmin(admin.ModelAdmin):
form = ArticleRevisionForm
list_display = ("title", "created", "modified", "user", "ip_address")
class Media:
js = editors.getEditorClass().AdminMedia.js
css = editors.getEditorClass().AdminMedia.css
class ArticleRevisionInline(admin.TabularInline):
model = models.ArticleRevision
form = ArticleRevisionForm
fk_name = "article"
extra = 1
fields = (
"content",
"title",
"deleted",
"locked",
)
class Media:
js = editors.getEditorClass().AdminMedia.js
css = editors.getEditorClass().AdminMedia.css
class ArticleForm(forms.ModelForm):
class Meta:
model = models.Article
exclude = ()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
revisions = models.ArticleRevision.objects.select_related(
"article"
).filter(article=self.instance)
self.fields["current_revision"].queryset = revisions
else:
self.fields[
"current_revision"
].queryset = models.ArticleRevision.objects.none()
self.fields["current_revision"].widget = forms.HiddenInput()
class ArticleAdmin(admin.ModelAdmin):
inlines = [ArticleRevisionInline]
form = ArticleForm
search_fields = ("current_revision__title", "current_revision__content")
class URLPathAdmin(MPTTModelAdmin):
inlines = [ArticleObjectAdmin]
list_filter = (
"site",
"articles__article__current_revision__deleted",
"articles__article__created",
"articles__article__modified",
)
list_display = ("__str__", "article", "get_created")
raw_id_fields = ("article",)
def get_created(self, instance):
return instance.article.created
get_created.short_description = _("created")
def save_model(self, request, obj, form, change):
"""
Ensure that there is a generic relation from the article to the URLPath
"""
obj.save()
obj.article.add_object_relation(obj)
admin.site.register(models.URLPath, URLPathAdmin)
admin.site.register(models.Article, ArticleAdmin)
admin.site.register(models.ArticleRevision, ArticleRevisionAdmin)

30
src/wiki/apps.py Normal file
View File

@@ -0,0 +1,30 @@
from django.apps import AppConfig
from django.core.checks import register
from django.utils.translation import gettext_lazy as _
from wiki.core.plugins.loader import load_wiki_plugins
from . import checks
class WikiConfig(AppConfig):
default_site = "wiki.sites.WikiSite"
name = "wiki"
verbose_name = _("Wiki")
def ready(self):
register(
checks.check_for_required_installed_apps,
checks.Tags.required_installed_apps,
)
register(
checks.check_for_obsolete_installed_apps,
checks.Tags.obsolete_installed_apps,
)
register(
checks.check_for_context_processors, checks.Tags.context_processors
)
register(
checks.check_for_fields_in_custom_user_model,
checks.Tags.fields_in_custom_user_model,
)
load_wiki_plugins()

128
src/wiki/checks.py Normal file
View File

@@ -0,0 +1,128 @@
from django.apps import apps
from django.core.checks import Error
from django.template import Engine
class Tags:
required_installed_apps = "required_installed_apps"
obsolete_installed_apps = "obsolete_installed_apps"
context_processors = "context_processors"
fields_in_custom_user_model = "fields_in_custom_user_model"
REQUIRED_INSTALLED_APPS = (
# module name, package name, error code
("mptt", "django-mptt", "E001"),
("sekizai", "django-sekizai", "E002"),
("django.contrib.humanize", "django.contrib.humanize", "E003"),
("django.contrib.contenttypes", "django.contrib.contenttypes", "E004"),
("django.contrib.sites", "django.contrib.sites", "E005"),
)
OBSOLETE_INSTALLED_APPS = (
# obsolete module name, new module name, error code
("django_notify", "django_nyt", "E006"),
)
REQUIRED_CONTEXT_PROCESSORS = (
# context processor name, error code
("django.contrib.auth.context_processors.auth", "E007"),
("django.template.context_processors.request", "E008"),
("sekizai.context_processors.sekizai", "E009"),
)
FIELDS_IN_CUSTOM_USER_MODEL = (
# check function, field fetcher, required field type, error code
("check_user_field", "USERNAME_FIELD", "CharField", "E010"),
("check_email_field", "get_email_field_name()", "EmailField", "E011"),
)
def check_for_required_installed_apps(app_configs, **kwargs):
errors = []
for app in REQUIRED_INSTALLED_APPS:
if not apps.is_installed(app[0]):
errors.append(
Error(
"needs %s in INSTALLED_APPS" % app[1],
id="wiki.%s" % app[2],
)
)
return errors
def check_for_obsolete_installed_apps(app_configs, **kwargs):
errors = []
for app in OBSOLETE_INSTALLED_APPS:
if apps.is_installed(app[0]):
errors.append(
Error(
"You need to change from %s to %s in INSTALLED_APPS and your urlconfig."
% (app[0], app[1]),
id="wiki.%s" % app[2],
)
)
return errors
def check_for_context_processors(app_configs, **kwargs):
errors = []
# Pattern from django.contrib.admin.checks
try:
default_template_engine = Engine.get_default()
except Exception:
# Skip this non-critical check:
# 1. if the user has a non-trivial TEMPLATES setting and Django
# can't find a default template engine
# 2. if anything goes wrong while loading template engines, in
# order to avoid raising an exception from a confusing location
# Catching ImproperlyConfigured suffices for 1. but 2. requires
# catching all exceptions.
pass
else:
context_processors = default_template_engine.context_processors
for context_processor in REQUIRED_CONTEXT_PROCESSORS:
if context_processor[0] not in context_processors:
errors.append(
Error(
"needs %s in TEMPLATES[*]['OPTIONS']['context_processors']"
% context_processor[0],
id="wiki.%s" % context_processor[1],
)
)
return errors
def check_for_fields_in_custom_user_model(app_configs, **kwargs):
errors = []
from wiki.conf import settings
if not settings.ACCOUNT_HANDLING:
return errors
import wiki.forms_account_handling
from django.contrib.auth import get_user_model
User = get_user_model()
for (
check_function_name,
field_fetcher,
required_field_type,
error_code,
) in FIELDS_IN_CUSTOM_USER_MODEL:
function = getattr(wiki.forms_account_handling, check_function_name)
if not function(User):
errors.append(
Error(
"%s.%s.%s refers to a field that is not of type %s"
% (
User.__module__,
User.__name__,
field_fetcher,
required_field_type,
),
hint="If you have your own login/logout views, turn off settings.WIKI_ACCOUNT_HANDLING",
obj=User,
id="wiki.%s" % error_code,
)
)
return errors

View File

315
src/wiki/conf/settings.py Normal file
View File

@@ -0,0 +1,315 @@
import bleach
from django.conf import settings as django_settings
from django.contrib.messages import constants as messages
from django.core.files.storage import default_storage
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
#: Should urls be case sensitive?
URL_CASE_SENSITIVE = getattr(django_settings, "WIKI_URL_CASE_SENSITIVE", False)
# Non-configurable (at the moment)
WIKI_LANGUAGE = "markdown"
#: The editor class to use -- maybe a 3rd party or your own...? You can always
#: extend the built-in editor and customize it!
EDITOR = getattr(
django_settings, "WIKI_EDITOR", "wiki.editors.markitup.MarkItUp"
)
#: Whether to use Bleach or not. It's not recommended to turn this off unless
#: you know what you're doing and you don't want to use the other options.
MARKDOWN_SANITIZE_HTML = getattr(
django_settings, "WIKI_MARKDOWN_SANITIZE_HTML", True
)
#: Arguments for the Markdown instance, as a dictionary. The "extensions" key
#: should be a list of extra extensions to use besides the built-in django-wiki
#: extensions, and the "extension_configs" should be a dictionary, specifying
#: the keyword-arguments to pass to each extension.
#:
#: For a list of extensions officially supported by Python-Markdown, see:
#: https://python-markdown.github.io/extensions/
#:
#: To set a custom title for table of contents, specify the following in your
#: Django project settings::
#:
#: WIKI_MARKDOWN_KWARGS = {
#: 'extension_configs': {
#: 'wiki.plugins.macros.mdx.toc': {'title': 'Contents of this article'},
#: },
#: }
#:
#: Besides the extensions enabled by the "extensions" key, the following
#: built-in django-wiki extensions can be configured with "extension_configs":
#: "wiki.core.markdown.mdx.codehilite", "wiki.core.markdown.mdx.previewlinks",
#: "wiki.core.markdown.mdx.responsivetable", "wiki.plugins.macros.mdx.macro",
#: "wiki.plugins.macros.mdx.toc", "wiki.plugins.macros.mdx.wikilinks".
MARKDOWN_KWARGS = {
"extensions": [
"markdown.extensions.footnotes",
"markdown.extensions.attr_list",
"markdown.extensions.footnotes",
"markdown.extensions.attr_list",
"markdown.extensions.def_list",
"markdown.extensions.tables",
"markdown.extensions.abbr",
"markdown.extensions.sane_lists",
],
"extension_configs": {
"wiki.plugins.macros.mdx.toc": {"title": _("Contents")}
},
}
MARKDOWN_KWARGS.update(getattr(django_settings, "WIKI_MARKDOWN_KWARGS", {}))
_default_tag_whitelists = bleach.ALLOWED_TAGS.union(
{
"figure",
"figcaption",
"br",
"hr",
"p",
"div",
"img",
"pre",
"span",
"sup",
"table",
"thead",
"tbody",
"th",
"tr",
"td",
"dl",
"dt",
"dd",
}
).union({f"h{n}" for n in range(1, 7)})
#: List of allowed tags in Markdown article contents.
MARKDOWN_HTML_WHITELIST = _default_tag_whitelists
MARKDOWN_HTML_WHITELIST = MARKDOWN_HTML_WHITELIST.union(
getattr(django_settings, "WIKI_MARKDOWN_HTML_WHITELIST", frozenset())
)
_default_attribute_whitelist = bleach.ALLOWED_ATTRIBUTES
for tag in MARKDOWN_HTML_WHITELIST:
if tag not in _default_attribute_whitelist:
_default_attribute_whitelist[tag] = []
_default_attribute_whitelist[tag].append("class")
_default_attribute_whitelist[tag].append("id")
_default_attribute_whitelist[tag].append("target")
_default_attribute_whitelist[tag].append("rel")
_default_attribute_whitelist["img"].append("src")
_default_attribute_whitelist["img"].append("alt")
_default_attribute_whitelist["td"].append("align")
#: Dictionary of allowed attributes in Markdown article contents.
MARKDOWN_HTML_ATTRIBUTES = _default_attribute_whitelist
MARKDOWN_HTML_ATTRIBUTES.update(
getattr(django_settings, "WIKI_MARKDOWN_HTML_ATTRIBUTES", {})
)
#: Allowed inline styles in Markdown article contents, default is no styles
#: (empty list).
MARKDOWN_HTML_STYLES = getattr(
django_settings, "WIKI_MARKDOWN_HTML_STYLES", []
)
_project_defined_attrs = getattr(
django_settings, "WIKI_MARKDOWN_HTML_ATTRIBUTE_WHITELIST", False
)
# If styles are allowed but no custom attributes are defined, we allow styles
# for all kinds of tags.
if MARKDOWN_HTML_STYLES and not _project_defined_attrs:
MARKDOWN_HTML_ATTRIBUTES["*"] = "style"
#: This slug is used in URLPath if an article has been deleted. The children of the
#: URLPath of that article are moved to lost and found. They keep their permissions
#: and all their content.
LOST_AND_FOUND_SLUG = getattr(
django_settings, "WIKI_LOST_AND_FOUND_SLUG", "lost-and-found"
)
#: When True, this blocks new slugs that resolve to non-wiki views, stopping
#: users creating articles that conflict with overlapping URLs from other apps.
CHECK_SLUG_URL_AVAILABLE = getattr(
django_settings, "WIKI_CHECK_SLUG_URL_AVAILABLE", True
)
#: Do we want to log IPs of anonymous users?
LOG_IPS_ANONYMOUS = getattr(django_settings, "WIKI_LOG_IPS_ANONYMOUS", True)
#: Do we want to log IPs of logged in users?
LOG_IPS_USERS = getattr(django_settings, "WIKI_LOG_IPS_USERS", False)
#: Mapping from message.level to bootstrap class names.
MESSAGE_TAG_CSS_CLASS = getattr(
django_settings,
"WIKI_MESSAGE_TAG_CSS_CLASS",
{
messages.DEBUG: "alert alert-info",
messages.ERROR: "alert alert-danger",
messages.INFO: "alert alert-info",
messages.SUCCESS: "alert alert-success",
messages.WARNING: "alert alert-warning",
},
)
#: Weather to append a trailing slash to rendered Wikilinks. Defaults to True
WIKILINKS_TRAILING_SLASH = getattr(
django_settings, "WIKI_WIKILINKS_TRAILING_SLASH", True
)
####################################
# PERMISSIONS AND ACCOUNT HANDLING #
####################################
# NB! None of these callables need to handle anonymous users as they are treated
# in separate settings...
#: A function returning True/False if a user has permission to
#: read contents of an article and plugins.
#: Relevance: Viewing articles and plugins.
CAN_READ = getattr(django_settings, "WIKI_CAN_READ", None)
#: A function returning True/False if a user has permission to
#: change contents, i.e. add new revisions to an article.
#: Often, plugins also use this.
#: Relevance: Editing articles, changing revisions, editing plugins.
CAN_WRITE = getattr(django_settings, "WIKI_CAN_WRITE", None)
#: A function returning True/False if a user has permission to assign
#: permissions on an article.
#: Relevance: Changing owner and group membership.
CAN_ASSIGN = getattr(django_settings, "WIKI_CAN_ASSIGN", None)
#: A function returning True/False if the owner of an article has permission
#: to change the group to a user's own groups.
#: Relevance: Changing group membership.
CAN_ASSIGN_OWNER = getattr(django_settings, "WIKI_ASSIGN_OWNER", None)
#: A function returning True/False if a user has permission to change
#: read/write access for groups and others.
CAN_CHANGE_PERMISSIONS = getattr(
django_settings, "WIKI_CAN_CHANGE_PERMISSIONS", None
)
#: Specifies if a user has access to soft deletion of articles.
CAN_DELETE = getattr(django_settings, "WIKI_CAN_DELETE", None)
#: A function returning True/False if a user has permission to change
#: moderate, ie. lock articles and permanently delete content.
CAN_MODERATE = getattr(django_settings, "WIKI_CAN_MODERATE", None)
#: A function returning True/False if a user has permission to create
#: new groups and users for the wiki.
CAN_ADMIN = getattr(django_settings, "WIKI_CAN_ADMIN", None)
#: Treat anonymous (i.e. non logged in) users as the "other" user group.
ANONYMOUS = getattr(django_settings, "WIKI_ANONYMOUS", True)
#: Globally enable write access for anonymous users, if true anonymous users
#: will be treated as the others_write boolean field on models.Article.
ANONYMOUS_WRITE = getattr(django_settings, "WIKI_ANONYMOUS_WRITE", False)
#: Globally enable create access for anonymous users.
#: Defaults to ``ANONYMOUS_WRITE``.
ANONYMOUS_CREATE = getattr(
django_settings, "WIKI_ANONYMOUS_CREATE", ANONYMOUS_WRITE
)
#: Default setting to allow anonymous users upload access. Used in
#: plugins.attachments and plugins.images, and can be overwritten in
#: these plugins.
ANONYMOUS_UPLOAD = getattr(django_settings, "WIKI_ANONYMOUS_UPLOAD", False)
#: Sign up, login and logout views should be accessible.
ACCOUNT_HANDLING = getattr(django_settings, "WIKI_ACCOUNT_HANDLING", True)
#: Signup allowed? If it's not allowed, logged in superusers can still access
#: the signup page to create new users.
ACCOUNT_SIGNUP_ALLOWED = ACCOUNT_HANDLING and getattr(
django_settings, "WIKI_ACCOUNT_SIGNUP_ALLOWED", True
)
if ACCOUNT_HANDLING:
LOGIN_URL = reverse_lazy("wiki:login")
LOGOUT_URL = reverse_lazy("wiki:logout")
SIGNUP_URL = reverse_lazy("wiki:signup")
else:
LOGIN_URL = getattr(django_settings, "LOGIN_URL", "/")
LOGOUT_URL = getattr(django_settings, "LOGOUT_URL", "/")
SIGNUP_URL = getattr(django_settings, "WIKI_SIGNUP_URL", "/")
##################
# OTHER SETTINGS #
##################
#: Maximum amount of children to display in a menu before showing "+more".
#: NEVER set this to 0 as it will wrongly inform the user that there are no
#: children and for instance that an article can be safely deleted.
SHOW_MAX_CHILDREN = getattr(django_settings, "WIKI_SHOW_MAX_CHILDREN", 20)
#: User Bootstrap's select widget. Switch off if you're not using Bootstrap!
USE_BOOTSTRAP_SELECT_WIDGET = getattr(
django_settings, "WIKI_USE_BOOTSTRAP_SELECT_WIDGET", True
)
#: Dotted name of the class used to construct urlpatterns for the wiki.
#: Default is wiki.urls.WikiURLPatterns. To customize urls or view handlers,
#: you can derive from this.
URL_CONFIG_CLASS = getattr(django_settings, "WIKI_URL_CONFIG_CLASS", None)
#: Seconds of timeout before renewing the article cache. Articles are automatically
#: renewed whenever an edit occurs but article content may be generated from
#: other objects that are changed.
CACHE_TIMEOUT = getattr(django_settings, "WIKI_CACHE_TIMEOUT", 600)
#: Choose the Group model to use for permission handling. Defaults to django's auth.Group.
GROUP_MODEL = getattr(django_settings, "WIKI_GROUP_MODEL", "auth.Group")
###################
# SPAM PROTECTION #
###################
#: Maximum allowed revisions per hour for any given user or IP.
REVISIONS_PER_HOUR = getattr(django_settings, "WIKI_REVISIONS_PER_HOUR", 60)
#: Maximum allowed revisions per minute for any given user or IP.
REVISIONS_PER_MINUTES = getattr(
django_settings, "WIKI_REVISIONS_PER_MINUTES", 5
)
#: Maximum allowed revisions per hour for any anonymous user and any IP.
REVISIONS_PER_HOUR_ANONYMOUS = getattr(
django_settings, "WIKI_REVISIONS_PER_HOUR_ANONYMOUS", 10
)
#: Maximum allowed revisions per minute for any anonymous user and any IP.
REVISIONS_PER_MINUTES_ANONYMOUS = getattr(
django_settings, "WIKI_REVISIONS_PER_MINUTES_ANONYMOUS", 2
)
#: Number of minutes to look back for looking up ``REVISIONS_PER_MINUTES``
#: and ``REVISIONS_PER_MINUTES_ANONYMOUS``.
REVISIONS_MINUTES_LOOKBACK = getattr(
django_settings, "WIKI_REVISIONS_MINUTES_LOOKBACK", 2
)
###########
# STORAGE #
###########
#: Default Django storage backend to use for images, attachments etc.
STORAGE_BACKEND = getattr(
django_settings, "WIKI_STORAGE_BACKEND", default_storage
)
#: Use django-sendfile for sending out files? Otherwise the whole file is
#: first read into memory and than send with a mime type based on the file.
USE_SENDFILE = getattr(django_settings, "WIKI_ATTACHMENTS_USE_SENDFILE", False)

View File

11
src/wiki/core/diff.py Normal file
View File

@@ -0,0 +1,11 @@
import difflib
def simple_merge(txt1, txt2):
"""Merges two texts"""
differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1))
content = "".join([_l[2:] for _l in diff])
return content

View File

@@ -0,0 +1,12 @@
# If no root URL is found, we raise this...
class NoRootURL(Exception):
pass
# If there is more than one...
class MultipleRootURLs(Exception):
pass

59
src/wiki/core/http.py Normal file
View File

@@ -0,0 +1,59 @@
import mimetypes
import os
from datetime import datetime
from django.http import HttpResponse
from django.utils import dateformat
from django.utils.encoding import filepath_to_uri
from django.utils.http import http_date
from wiki.conf import settings
def django_sendfile_response(request, filepath):
from sendfile import sendfile
return sendfile(request, filepath)
def send_file(request, filepath, last_modified=None, filename=None):
fullpath = filepath
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
if filename:
mimetype, encoding = mimetypes.guess_type(filename)
else:
mimetype, encoding = mimetypes.guess_type(fullpath)
mimetype = mimetype or "application/octet-stream"
if settings.USE_SENDFILE:
response = django_sendfile_response(request, filepath)
else:
response = HttpResponse(
open(fullpath, "rb").read(), content_type=mimetype
)
if not last_modified:
response["Last-Modified"] = http_date(statobj.st_mtime)
else:
if isinstance(last_modified, datetime):
last_modified = float(dateformat.format(last_modified, "U"))
response["Last-Modified"] = http_date(epoch_seconds=last_modified)
response["Content-Length"] = statobj.st_size
if encoding:
response["Content-Encoding"] = encoding
if filename:
filename_escaped = filepath_to_uri(filename)
if "pdf" in mimetype.lower():
response["Content-Disposition"] = (
"inline; filename=%s" % filename_escaped
)
else:
response["Content-Disposition"] = (
"attachment; filename=%s" % filename_escaped
)
return response

View File

@@ -0,0 +1,117 @@
import bleach
import markdown
from bleach.css_sanitizer import CSSSanitizer
from wiki.conf import settings
from wiki.core.plugins import registry as plugin_registry
class ArticleMarkdown(markdown.Markdown):
def __init__(self, article, preview=False, user=None, *args, **kwargs):
kwargs.update(settings.MARKDOWN_KWARGS)
kwargs["extensions"] = self.get_markdown_extensions()
super().__init__(*args, **kwargs)
self.article = article
self.preview = preview
self.user = user
self.source = None
def core_extensions(self):
"""List of core extensions found in the mdx folder"""
return [
"wiki.core.markdown.mdx.codehilite",
"wiki.core.markdown.mdx.previewlinks",
"wiki.core.markdown.mdx.responsivetable",
]
def get_markdown_extensions(self):
extensions = list(settings.MARKDOWN_KWARGS.get("extensions", []))
extensions += self.core_extensions()
extensions += plugin_registry.get_markdown_extensions()
return extensions
def convert(self, text, *args, **kwargs):
# store source in instance, for extensions which might need it
self.source = text
html = super().convert(text, *args, **kwargs)
if settings.MARKDOWN_SANITIZE_HTML:
tags = settings.MARKDOWN_HTML_WHITELIST.union(
plugin_registry.get_html_whitelist()
)
css_sanitizer = CSSSanitizer(
allowed_css_properties=settings.MARKDOWN_HTML_STYLES
)
attrs = {}
attrs.update(settings.MARKDOWN_HTML_ATTRIBUTES)
attrs.update(plugin_registry.get_html_attributes().items())
html = bleach.clean(
html,
tags=tags,
attributes=attrs,
css_sanitizer=css_sanitizer,
strip=True,
)
return html
def article_markdown(text, article, *args, **kwargs):
md = ArticleMarkdown(article, *args, **kwargs)
return md.convert(text)
def add_to_registry(processor, key, value, location):
"""Utility function to register a key by location to Markdown's registry.
Parameters:
* `processor`: Markdown Registry instance
* `key`: A string used to reference the item.
* `value`: The item being registered.
* `location`: Where to register the new key
location can be one of the strings below:
* _begin (registers the key as the highest priority)
* _end (registers the key as the lowest priority)
* a string that starts with `<` or `>` (sets priority halfway between existing priorities)
Returns: None
Raises: ValueError if location is an invalid string.
"""
if len(processor) == 0:
# This is the first item. Set priority to 50.
priority = 50
elif location == "_begin":
processor._sort()
# Set priority 5 greater than highest existing priority
priority = processor._priority[0].priority + 5
elif location == "_end":
processor._sort()
# Set priority 5 less than lowest existing priority
priority = processor._priority[-1].priority - 5
elif location.startswith("<") or location.startswith(">"):
# Set priority halfway between existing priorities.
i = processor.get_index_for_name(location[1:])
if location.startswith("<"):
after = processor._priority[i].priority
if i > 0:
before = processor._priority[i - 1].priority
else:
# Location is first item`
before = after + 10
else:
# location.startswith('>')
before = processor._priority[i].priority
if i < len(processor) - 1:
after = processor._priority[i + 1].priority
else:
# location is last item
after = before - 10
priority = before - ((before - after) / 2)
else:
raise ValueError(
'Not a valid location: "%s". Location key '
'must start with a ">" or "<".' % location
)
processor.register(value, key, priority)

View File

View File

@@ -0,0 +1,159 @@
from textwrap import dedent
import logging
import re
from markdown.extensions.codehilite import CodeHilite
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
logger = logging.getLogger(__name__)
def highlight(code, config, tab_length, lang=None):
code = CodeHilite(
code,
linenums=config["linenums"],
guess_lang=config["guess_lang"],
css_class=config["css_class"],
style=config["pygments_style"],
noclasses=config["noclasses"],
tab_length=tab_length,
use_pygments=config["use_pygments"],
lang=lang,
)
html = code.hilite()
html = f"""<div class="codehilite-wrap">{html}</div>"""
return html
class WikiFencedBlockPreprocessor(Preprocessor):
"""
This is a replacement of markdown.extensions.fenced_code which will
directly and without configuration options invoke the vanilla CodeHilite
extension.
"""
FENCED_BLOCK_RE = re.compile(
dedent(
r"""
(?P<fence>^(?:~{3,}|`{3,}))[ ]* # opening fence
((\{(?P<attrs>[^\}\n]*)\})| # (optional {attrs} or
(\.?(?P<lang>[\w#.+-]*)[ ]*)? # optional (.)lang
(hl_lines=(?P<quot>"|')(?P<hl_lines>.*?)(?P=quot)[ ]*)?) # optional hl_lines)
\n # newline (end of opening fence)
(?P<code>.*?)(?<=\n) # the code block
(?P=fence)[ ]*$ # closing fence
"""
),
re.MULTILINE | re.DOTALL | re.VERBOSE,
)
CODE_WRAP = "<pre>%s</pre>"
def __init__(self, md):
super().__init__(md)
self.checked_for_codehilite = False
self.codehilite_conf = {}
def run(self, lines):
"""Match and store Fenced Code Blocks in the HtmlStash."""
text = "\n".join(lines)
while 1:
m = self.FENCED_BLOCK_RE.search(text)
if m:
lang = ""
if m.group("lang"):
lang = m.group("lang")
html = highlight(
m.group("code"), self.config, self.md.tab_length, lang=lang
)
placeholder = self.md.htmlStash.store(html)
text = "{}\n{}\n{}".format(
text[: m.start()],
placeholder,
text[m.end() :],
)
else:
break
return text.split("\n")
class HiliteTreeprocessor(Treeprocessor):
"""Hilight source code in code blocks."""
def code_unescape(self, text):
"""Unescape &, <, > and " characters."""
text = text.replace("&amp;", "&")
text = text.replace("&lt;", "<")
text = text.replace("&gt;", ">")
text = text.replace("&quot;", '"')
return text
def run(self, root):
"""Find code blocks and store in htmlStash."""
blocks = root.iter("pre")
for block in blocks:
if len(block) == 1 and block[0].tag == "code":
html = highlight(
self.code_unescape(block[0].text),
self.config,
self.md.tab_length,
)
placeholder = self.md.htmlStash.store(html)
# Clear codeblock in etree instance
block.clear()
# Change to p element which will later
# be removed when inserting raw html
block.tag = "p"
block.text = placeholder
class WikiCodeHiliteExtension(CodeHiliteExtension):
"""
markdown.extensions.codehilite cannot configure container tags but forces
code to be in <table></table>, so we had to overwrite some of the code
because it's hard to extend...
"""
def extendMarkdown(self, md):
"""Add HilitePostprocessor to Markdown instance."""
hiliter = HiliteTreeprocessor(md)
hiliter.config = self.getConfigs()
if "hilite" in md.treeprocessors:
logger.warning(
"Replacing existing 'hilite' extension - please remove "
"'codehilite' from WIKI_MARKDOWN_KWARGS"
)
# del md.treeprocessors["hilite"]
md.treeprocessors.deregister("hilite")
add_to_registry(md.treeprocessors, "hilite", hiliter, "<inline")
if "fenced_code_block" in md.preprocessors:
logger.warning(
"Replacing existing 'fenced_code_block' extension - please remove "
"'fenced_code_block' or 'extras' from WIKI_MARKDOWN_KWARGS"
)
# del md.preprocessors["fenced_code_block"]
md.preprocessors.deregister("fenced_code_block")
hiliter = WikiFencedBlockPreprocessor(md)
hiliter.config = self.getConfigs()
add_to_registry(
md.preprocessors,
"fenced_code_block",
hiliter,
">normalize_whitespace",
)
md.registerExtension(self)
def makeExtension(*args, **kwargs):
"""Return an instance of the extension."""
return WikiCodeHiliteExtension(*args, **kwargs)

View File

@@ -0,0 +1,28 @@
import markdown
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
class PreviewLinksExtension(markdown.Extension):
"""Markdown Extension that sets all anchor targets to _blank when in preview mode"""
def extendMarkdown(self, md):
add_to_registry(
md.treeprocessors, "previewlinks", PreviewLinksTree(md), "_end"
)
class PreviewLinksTree(Treeprocessor):
def run(self, root):
if self.md.preview:
for a in root.findall(".//a"):
# Do not set target for links like href='#markdown'
if not a.get("href").startswith("#"):
a.set("target", "_blank")
return root
def makeExtension(*args, **kwargs):
"""Return an instance of the extension."""
return PreviewLinksExtension(*args, **kwargs)

View File

@@ -0,0 +1,57 @@
from xml.etree import ElementTree as etree
import markdown
from markdown.treeprocessors import Treeprocessor
from wiki.core.markdown import add_to_registry
class ResponsiveTableExtension(markdown.Extension):
"""Wraps all tables with Bootstrap's table-responsive class"""
def extendMarkdown(self, md):
add_to_registry(
md.treeprocessors,
"responsivetable",
ResponsiveTableTree(md),
"_end",
)
class ResponsiveTableTree(Treeprocessor):
"""
NOTE: If you allow inputting of raw <table> tags rather than Markdown code
for tables, this tree processor will not affect the table, as it gets
stashed and not managed by a Treeprocessor type extension.
"""
def run(self, root):
for table_wrapper in list(root.iter("table")):
table_new = self.create_table_element()
self.convert_to_wrapper(table_wrapper)
self.move_children(table_wrapper, table_new)
table_wrapper.append(table_new)
return root
def create_table_element(self):
"""Create table element with text and tail"""
element = etree.Element("table")
element.text = "\n"
element.tail = "\n"
return element
def move_children(self, element1, element2):
"""Moves children from element1 to element2"""
for child in list(element1):
element2.append(child)
# reversed is needed to safely remove items while iterating
for child in reversed(list(element1)):
element1.remove(child)
def convert_to_wrapper(self, element):
element.tag = "div"
element.set("class", "table-responsive")
def makeExtension(*args, **kwargs):
"""Return an instance of the extension."""
return ResponsiveTableExtension(*args, **kwargs)

View File

@@ -0,0 +1,34 @@
from django.core.paginator import Paginator
class WikiPaginator(Paginator):
def __init__(self, *args, **kwargs):
"""
:param side_pages: How many pages should be shown before and after the current page
"""
self.side_pages = kwargs.pop("side_pages", 4)
super().__init__(*args, **kwargs)
def page(self, number):
# Save last accessed page number for context-based lookup in page_range
self.last_accessed_page_number = number
return super().page(number)
@property
def page_range(self):
left = max(self.last_accessed_page_number - self.side_pages, 2)
right = min(
self.last_accessed_page_number + self.side_pages + 1,
self.num_pages,
)
pages = []
if self.num_pages > 0:
pages = [1]
if left > 2:
pages += [0]
pages += range(left, right)
if right < self.num_pages:
pages += [0]
if self.num_pages > 1:
pages += [self.num_pages]
return pages

View File

@@ -0,0 +1,105 @@
from wiki.conf import settings
###############################
# ARTICLE PERMISSION HANDLING #
###############################
#
# All functions are:
# can_something(article, user)
# => True/False
#
# All functions can be replaced by pointing their relevant
# settings variable in wiki.conf.settings to a callable(article, user)
def can_read(article, user):
if callable(settings.CAN_READ):
return settings.CAN_READ(article, user)
else:
# Deny reading access to deleted articles if user has no delete access
article_is_deleted = (
article.current_revision and article.current_revision.deleted
)
if article_is_deleted and not article.can_delete(user):
return False
# Check access for other users...
if user.is_anonymous and not settings.ANONYMOUS:
return False
elif article.other_read:
return True
elif user.is_anonymous:
return False
if user == article.owner:
return True
if article.group_read:
if (
article.group
and user.groups.filter(id=article.group.id).exists()
):
return True
if article.can_moderate(user):
return True
return False
def can_write(article, user):
if callable(settings.CAN_WRITE):
return settings.CAN_WRITE(article, user)
# Check access for other users...
if user.is_anonymous and not settings.ANONYMOUS_WRITE:
return False
elif article.other_write:
return True
elif user.is_anonymous:
return False
if user == article.owner:
return True
if article.group_write:
if (
article.group
and user
and user.groups.filter(id=article.group.id).exists()
):
return True
if article.can_moderate(user):
return True
return False
def can_assign(article, user):
if callable(settings.CAN_ASSIGN):
return settings.CAN_ASSIGN(article, user)
return not user.is_anonymous and user.has_perm("wiki.assign")
def can_assign_owner(article, user):
if callable(settings.CAN_ASSIGN_OWNER):
return settings.CAN_ASSIGN_OWNER(article, user)
return False
def can_change_permissions(article, user):
if callable(settings.CAN_CHANGE_PERMISSIONS):
return settings.CAN_CHANGE_PERMISSIONS(article, user)
return not user.is_anonymous and (
article.owner == user or user.has_perm("wiki.assign")
)
def can_delete(article, user):
if callable(settings.CAN_DELETE):
return settings.CAN_DELETE(article, user)
return not user.is_anonymous and article.can_write(user)
def can_moderate(article, user):
if callable(settings.CAN_MODERATE):
return settings.CAN_MODERATE(article, user)
return not user.is_anonymous and user.has_perm("wiki.moderate")
def can_admin(article, user):
if callable(settings.CAN_ADMIN):
return settings.CAN_ADMIN(article, user)
return not user.is_anonymous and user.has_perm("wiki.admin")

View File

View File

@@ -0,0 +1,70 @@
from django import forms
from django.utils.translation import gettext as _
"""Base classes for different plugin objects.
* BasePlugin: Create a wiki_plugin.py with a class that inherits from BasePlugin.
* PluginSidebarFormMixin: Mix in this class in the form that should be rendered in the editor sidebar
* PluginSettingsFormMixin: ..and this one for a form in the settings tab.
Please have a look in wiki.models.pluginbase to see where to inherit your
plugin's models.
"""
class BasePlugin:
"""Plugins should inherit from this"""
# Must fill in!
slug = None
# Optional
settings_form = None # A form class to add to the settings tab
urlpatterns = {
# General urlpatterns that will reside in /wiki/plugins/plugin-slug/...
"root": [],
# urlpatterns that receive article_id or urlpath, i.e.
# /wiki/ArticleName/plugin/plugin-slug/...
"article": [],
}
article_tab = None # (_('Attachments'), "fa fa-file")
article_view = None # A view for article_id/plugin/slug/
# A list of notification handlers to be subscribed if the notification
# system is active
notifications = []
# Example
# [{'model': models.AttachmentRevision,
# 'message': lambda obj: _("A file was changed: %s") % obj.get_filename(),
# 'key': ARTICLE_EDIT,
# 'created': True,
# 'get_article': lambda obj: obj.attachment.article}
# ]
markdown_extensions = []
class RenderMedia:
js = []
css = {}
class PluginSidebarFormMixin(forms.ModelForm):
unsaved_article_title = forms.CharField(
widget=forms.HiddenInput(), required=True
)
unsaved_article_content = forms.CharField(
widget=forms.HiddenInput(), required=False
)
def get_usermessage(self):
pass
class PluginSettingsFormMixin:
settings_form_headline = _("Settings for plugin")
settings_order = 1
settings_write_access = False
def get_usermessage(self):
pass

View File

@@ -0,0 +1,5 @@
from django.utils.module_loading import autodiscover_modules
def load_wiki_plugins():
autodiscover_modules("wiki_plugin")

View File

@@ -0,0 +1,77 @@
from importlib import import_module
_cache = {}
_settings_forms = []
_markdown_extensions = []
_article_tabs = []
_sidebar = []
_html_whitelist = []
_html_attributes = {}
def register(PluginClass):
"""
Register a plugin class. This function will call back your plugin's
constructor.
"""
if PluginClass in _cache:
raise Exception("Plugin class already registered")
plugin = PluginClass()
_cache[PluginClass] = plugin
settings_form = getattr(PluginClass, "settings_form", None)
if settings_form:
if isinstance(settings_form, str):
klassname = settings_form.split(".")[-1]
modulename = ".".join(settings_form.split(".")[:-1])
form_module = import_module(modulename)
settings_form = getattr(form_module, klassname)
_settings_forms.append(settings_form)
if getattr(PluginClass, "article_tab", None):
_article_tabs.append(plugin)
if getattr(PluginClass, "sidebar", None):
_sidebar.append(plugin)
_markdown_extensions.extend(
getattr(PluginClass, "markdown_extensions", [])
)
_html_whitelist.extend(getattr(PluginClass, "html_whitelist", []))
_html_attributes.update(getattr(PluginClass, "html_attributes", {}))
def get_plugins():
"""Get loaded plugins - do not call before all plugins are loaded."""
return _cache
def get_markdown_extensions():
"""Get all markdown extension classes from plugins"""
return _markdown_extensions
def get_article_tabs():
"""Get all article tab dictionaries from plugins"""
return _article_tabs
def get_sidebar():
"""Returns plugin classes that should connect to the sidebar"""
return _sidebar
def get_settings_forms():
return _settings_forms
def get_html_whitelist():
"""Returns additional html tags that should be whitelisted"""
return _html_whitelist
def get_html_attributes():
"""Returns additional html attributes that should be whitelisted"""
return _html_attributes

14
src/wiki/core/utils.py Normal file
View File

@@ -0,0 +1,14 @@
from django.http.response import JsonResponse
def object_to_json_response(obj, status=200):
"""
Given an object, returns an HttpResponse object with a JSON serialized
version of that object
"""
return JsonResponse(
data=obj,
status=status,
safe=False,
json_dumps_params={"ensure_ascii": False},
)

204
src/wiki/decorators.py Normal file
View File

@@ -0,0 +1,204 @@
from functools import wraps
from urllib.parse import quote as urlquote
from django.http import Http404
from django.http import HttpResponseForbidden
from django.http import HttpResponseNotFound
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.urls import reverse
from wiki.conf import settings
from wiki.core.exceptions import NoRootURL
from . import models
def response_forbidden(request, article, urlpath, read_denied=False):
if request.user.is_anonymous:
qs = request.META.get("QUERY_STRING", "")
if qs:
qs = urlquote("?" + qs)
else:
qs = ""
return redirect(settings.LOGIN_URL + "?next=" + request.path + qs)
else:
return HttpResponseForbidden(
render_to_string(
"wiki/permission_denied.html",
context={
"article": article,
"urlpath": urlpath,
"read_denied": read_denied,
},
request=request,
)
)
def which_article(path=None, article_id=None, **kwargs):
# fetch by path
if path is not None:
urlpath = models.URLPath.get_by_path(path, select_related=True)
if urlpath.article:
# urlpath is already smart about prefetching items on article
# (like current_revision), so we don't have to
article = urlpath.article
else:
# Be robust: Somehow article is gone but urlpath exists...
# clean up
urlpath.delete()
raise models.URLPath.DoesNotExist()
# fetch by article.id
elif article_id is not None:
# TODO We should try to grab the article from URLPath so the
# caching is good, and fall back to grabbing it from
# Article.objects if not
article = models.Article.objects.get(id=article_id)
try:
urlpath = models.URLPath.objects.get(articles__article=article)
except (
models.URLPath.DoesNotExist,
models.URLPath.MultipleObjectsReturned,
):
urlpath = None
else:
raise TypeError("You should specify either article_id or path")
return article, urlpath
# TODO: This decorator is too complex (C901)
def get_article( # noqa: max-complexity 19
func=None,
can_read=True,
can_write=False,
deleted_contents=False,
not_locked=False,
can_delete=False,
can_moderate=False,
can_create=False,
):
"""View decorator for processing standard url keyword args: Intercepts the
keyword args path or article_id and looks up an article, calling the decorated
func with this ID.
Will accept a ``func(request, article, *args, **kwargs)``
NB! This function will redirect if an article does not exist, permissions
are missing or the article is deleted.
Arguments:
can_read=True and/or can_write=True: Check that the current request.user
has correct permissions.
can_delete and can_moderate: Verifies with wiki.core.permissions
can_create: Same as can_write but adds an extra global setting for anonymous access (ANONYMOUS_CREATE)
deleted_contents=True: Do not redirect if the article has been deleted.
not_locked=True: Return permission denied if the article is locked
Also see: wiki.views.mixins.ArticleMixin
"""
def wrapper(request, *args, **kwargs):
path = kwargs.pop("path", None)
article_id = kwargs.pop("article_id", None)
try:
article, urlpath = which_article(path, article_id)
except NoRootURL:
return redirect("wiki:root_create")
except models.Article.DoesNotExist:
raise Http404(f"Article id {article_id} not found")
except models.URLPath.DoesNotExist:
try:
pathlist = list(
filter(
lambda x: x != "",
path.split("/"),
)
)
path = "/".join(pathlist[:-1])
parent = models.URLPath.get_by_path(path)
return HttpResponseRedirect(
reverse("wiki:create", kwargs={"path": parent.path})
+ "?slug=%s" % pathlist[-1].lower()
)
except models.URLPath.DoesNotExist:
return HttpResponseNotFound(
render_to_string(
"wiki/error.html",
context={"error_type": "ancestors_missing"},
request=request,
)
)
if not deleted_contents:
# If the article has been deleted, show a special page.
if urlpath:
if urlpath.is_deleted(): # This also checks all ancestors
return redirect("wiki:deleted", path=urlpath.path)
else:
if (
article.current_revision
and article.current_revision.deleted
):
return redirect("wiki:deleted", article_id=article.id)
if article.current_revision.locked and not_locked:
return response_forbidden(request, article, urlpath)
if can_read and not article.can_read(request.user):
return response_forbidden(
request, article, urlpath, read_denied=True
)
if (can_write or can_create) and not article.can_write(request.user):
return response_forbidden(request, article, urlpath)
if can_create and not (
request.user.is_authenticated or settings.ANONYMOUS_CREATE
):
return response_forbidden(request, article, urlpath)
if can_delete and not article.can_delete(request.user):
return response_forbidden(request, article, urlpath)
if can_moderate and not article.can_moderate(request.user):
return response_forbidden(request, article, urlpath)
kwargs["urlpath"] = urlpath
return func(request, article, *args, **kwargs)
if func:
return wrapper
else:
return lambda func: get_article(
func,
can_read=can_read,
can_write=can_write,
deleted_contents=deleted_contents,
not_locked=not_locked,
can_delete=can_delete,
can_moderate=can_moderate,
can_create=can_create,
)
def disable_signal_for_loaddata(signal_handler):
"""
Decorator that turns off signal handlers when loading fixture data.
"""
@wraps(signal_handler)
def wrapper(*args, **kwargs):
if kwargs.get("raw", False):
return
return signal_handler(*args, **kwargs)
return wrapper

View File

@@ -0,0 +1,19 @@
from django.urls import get_callable
from wiki.conf import settings
_EditorClass = None
_editor = None
def getEditorClass():
global _EditorClass
if not _EditorClass:
_EditorClass = get_callable(settings.EDITOR)
return _EditorClass
def getEditor():
global _editor
if not _editor:
_editor = getEditorClass()()
return _editor

26
src/wiki/editors/base.py Normal file
View File

@@ -0,0 +1,26 @@
from django import forms
class BaseEditor:
"""Editors should inherit from this. See wiki.editors for examples."""
# The editor id can be used for conditional testing. If you write your
# own editor class, you can use the same editor_id as some editor
editor_id = "plaintext"
media_admin = ()
media_frontend = ()
def get_admin_widget(self, revision=None):
return forms.Textarea()
def get_widget(self, revision=None):
return forms.Textarea()
class AdminMedia:
css = {}
js = ()
class Media:
css = {}
js = ()

View File

@@ -0,0 +1,59 @@
from django import forms
from wiki.editors.base import BaseEditor
class MarkItUpWidget(forms.Widget):
template_name = "wiki/forms/markitup.html"
def __init__(self, attrs=None):
# The 'rows' and 'cols' attributes are required for HTML correctness.
default_attrs = {
"class": "markItUp",
"rows": "10",
"cols": "40",
}
if attrs:
default_attrs.update(attrs)
super().__init__(default_attrs)
class MarkItUpAdminWidget(MarkItUpWidget):
"""A simplified more fail-safe widget for the backend"""
template_name = "wiki/forms/markitup-admin.html"
class MarkItUp(BaseEditor):
editor_id = "markitup"
def get_admin_widget(self, revision=None):
return MarkItUpAdminWidget()
def get_widget(self, revision=None):
return MarkItUpWidget()
class AdminMedia:
css = {
"all": (
"wiki/markitup/skins/simple/style.css",
"wiki/markitup/sets/admin/style.css",
)
}
js = (
"wiki/markitup/admin.init.js",
"wiki/markitup/jquery.markitup.js",
"wiki/markitup/sets/admin/set.js",
)
class Media:
css = {
"all": (
"wiki/markitup/skins/simple/style.css",
"wiki/markitup/sets/frontend/style.css",
)
}
js = (
"wiki/markitup/frontend.init.js",
"wiki/markitup/jquery.markitup.js",
"wiki/markitup/sets/frontend/set.js",
)

650
src/wiki/forms.py Normal file
View File

@@ -0,0 +1,650 @@
__all__ = [
"UserCreationForm",
"UserUpdateForm",
"WikiSlugField",
"SpamProtectionMixin",
"CreateRootForm",
"MoveForm",
"EditForm",
"SelectWidgetBootstrap",
"TextInputPrepend",
"CreateForm",
"DeleteForm",
"PermissionsForm",
"DirFilterForm",
"SearchForm",
]
from datetime import timedelta
from django import forms
from django.apps import apps
from django.contrib.auth import get_user_model
from django.core import validators
from django.core.validators import RegexValidator
from django.forms.widgets import HiddenInput
from django.shortcuts import get_object_or_404
from django.urls import Resolver404, resolve
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy as _, pgettext_lazy
from wiki import models
from wiki.conf import settings
from wiki.core import permissions
from wiki.core.diff import simple_merge
from wiki.core.plugins.base import PluginSettingsFormMixin
from wiki.editors import getEditor
from .forms_account_handling import UserCreationForm, UserUpdateForm
validate_slug_numbers = RegexValidator(
r"^[0-9]+$",
_("A 'slug' cannot consist solely of numbers."),
"invalid",
inverse_match=True,
)
class WikiSlugField(forms.CharField):
"""
In future versions of Django, we might be able to define this field as
the default field directly on the model. For now, it's used in CreateForm.
"""
default_validators = [validators.validate_slug, validate_slug_numbers]
def __init__(self, *args, **kwargs):
self.allow_unicode = kwargs.pop("allow_unicode", False)
if self.allow_unicode:
self.default_validators = [
validators.validate_unicode_slug,
validate_slug_numbers,
]
super().__init__(*args, **kwargs)
def _clean_slug(slug, urlpath):
if slug.startswith("_"):
raise forms.ValidationError(
gettext("A slug may not begin with an underscore.")
)
if slug == "admin":
raise forms.ValidationError(
gettext("'admin' is not a permitted slug name.")
)
if settings.URL_CASE_SENSITIVE:
already_existing_slug = models.URLPath.objects.filter(
slug=slug, parent=urlpath
)
else:
slug = slug.lower()
already_existing_slug = models.URLPath.objects.filter(
slug__iexact=slug, parent=urlpath
)
if already_existing_slug:
already_urlpath = already_existing_slug[0]
if (
already_urlpath.article
and already_urlpath.article.current_revision.deleted
):
raise forms.ValidationError(
gettext('A deleted article with slug "%s" already exists.')
% already_urlpath.slug
)
else:
raise forms.ValidationError(
gettext('A slug named "%s" already exists.')
% already_urlpath.slug
)
if settings.CHECK_SLUG_URL_AVAILABLE:
try:
# Fail validation if URL resolves to non-wiki app
match = resolve(urlpath.path + "/" + slug + "/")
if match.app_name != "wiki":
raise forms.ValidationError(
gettext("This slug conflicts with an existing URL.")
)
except Resolver404:
pass
return slug
User = get_user_model()
Group = apps.get_model(settings.GROUP_MODEL)
class SpamProtectionMixin:
"""Check a form for spam. Only works if properties 'request' and 'revision_model' are set."""
revision_model = models.ArticleRevision
# TODO: This method is too complex (C901)
def check_spam(self): # noqa
"""Check that user or IP address does not perform content edits that
are not allowed.
current_revision can be any object inheriting from models.BaseRevisionMixin
"""
request = self.request
user = None
ip_address = None
if request.user.is_authenticated:
user = request.user
else:
ip_address = request.META.get(
"HTTP_X_REAL_IP", None
) or request.META.get("REMOTE_ADDR", None)
if not (user or ip_address):
raise forms.ValidationError(
gettext(
"Spam protection failed to find both a logged in user and an IP address."
)
)
def check_interval(from_time, max_count, interval_name):
from_time = timezone.now() - timedelta(
minutes=settings.REVISIONS_MINUTES_LOOKBACK
)
revisions = self.revision_model.objects.filter(
created__gte=from_time,
)
if user:
revisions = revisions.filter(user=user)
if ip_address:
revisions = revisions.filter(ip_address=ip_address)
revisions = revisions.count()
if revisions >= max_count:
raise forms.ValidationError(
gettext(
"Spam protection: You are only allowed to create or edit %(revisions)d article(s) per %(interval_name)s."
)
% {"revisions": max_count, "interval_name": interval_name}
)
if not settings.LOG_IPS_ANONYMOUS:
return
if request.user.has_perm("wiki.moderator"):
return
from_time = timezone.now() - timedelta(
minutes=settings.REVISIONS_MINUTES_LOOKBACK
)
if request.user.is_authenticated:
per_minute = settings.REVISIONS_PER_MINUTES
else:
per_minute = settings.REVISIONS_PER_MINUTES_ANONYMOUS
check_interval(
from_time,
per_minute,
_("minute")
if settings.REVISIONS_MINUTES_LOOKBACK == 1
else (_("%d minutes") % settings.REVISIONS_MINUTES_LOOKBACK),
)
from_time = timezone.now() - timedelta(minutes=60)
if request.user.is_authenticated:
per_hour = settings.REVISIONS_PER_MINUTES
else:
per_hour = settings.REVISIONS_PER_MINUTES_ANONYMOUS
check_interval(from_time, per_hour, _("hour"))
class CreateRootForm(forms.Form):
title = forms.CharField(
label=_("Title"),
help_text=_(
"Initial title of the article. May be overridden with revision titles."
),
)
content = forms.CharField(
label=_("Type in some contents"),
help_text=_(
"This is just the initial contents of your article. After creating it, you can use more complex features like adding plugins, meta data, related articles etc..."
),
required=False,
widget=getEditor().get_widget(),
) # @UndefinedVariable
class MoveForm(forms.Form):
destination = forms.CharField(label=_("Destination"))
slug = WikiSlugField(max_length=models.URLPath.SLUG_MAX_LENGTH)
redirect = forms.BooleanField(
label=_("Redirect pages"),
help_text=_("Create a redirect page for every moved article?"),
required=False,
)
def clean(self):
cd = super().clean()
if cd.get("slug"):
dest_path = get_object_or_404(
models.URLPath, pk=self.cleaned_data["destination"]
)
cd["slug"] = _clean_slug(cd["slug"], dest_path)
return cd
class EditForm(forms.Form, SpamProtectionMixin):
title = forms.CharField(
label=_("Title"),
)
content = forms.CharField(
label=_("Contents"), required=False
) # @UndefinedVariable
summary = forms.CharField(
label=pgettext_lazy("Revision comment", "Summary"),
help_text=_(
"Give a short reason for your edit, which will be stated in the revision log."
),
required=False,
)
current_revision = forms.IntegerField(
required=False, widget=forms.HiddenInput()
)
def __init__(self, request, current_revision, *args, **kwargs):
self.request = request
self.no_clean = kwargs.pop("no_clean", False)
self.preview = kwargs.pop("preview", False)
self.initial_revision = current_revision
self.presumed_revision = None
if current_revision:
# For e.g. editing a section of the text: The content provided by the caller is used.
# Otherwise use the content of the revision.
provided_content = True
content = kwargs.pop("content", None)
if content is None:
provided_content = False
content = current_revision.content
initial = {
"content": content,
"title": current_revision.title,
"current_revision": current_revision.id,
}
initial.update(kwargs.get("initial", {}))
# Manipulate any data put in args[0] such that the current_revision
# is reset to match the actual current revision.
data = None
if len(args) > 0:
data = args[0]
args = args[1:]
if data is None:
data = kwargs.get("data", None)
if data:
self.presumed_revision = data.get("current_revision", None)
if not str(self.presumed_revision) == str(
self.initial_revision.id
):
newdata = {}
for k, v in data.items():
newdata[k] = v
newdata["current_revision"] = self.initial_revision.id
# Don't merge if content comes from the caller
if provided_content:
self.presumed_revision = self.initial_revision.id
else:
newdata["content"] = simple_merge(
content, data.get("content", "")
)
newdata["title"] = current_revision.title
kwargs["data"] = newdata
else:
# Always pass as kwarg
kwargs["data"] = data
kwargs["initial"] = initial
super().__init__(*args, **kwargs)
self.fields["content"].widget = getEditor().get_widget(
current_revision
)
def clean_title(self):
title = self.cleaned_data.get("title", None)
title = (title or "").strip()
if not title:
raise forms.ValidationError(
gettext("Article is missing title or has an invalid title")
)
return title
def clean(self):
"""Validates form data by checking for the following
No new revisions have been created since user attempted to edit
Revision title or content has changed
"""
if self.no_clean or self.preview:
return self.cleaned_data
if not str(self.initial_revision.id) == str(self.presumed_revision):
raise forms.ValidationError(
gettext(
"While you were editing, someone else changed the revision. Your contents have been automatically merged with the new contents. Please review the text below."
)
)
if (
"title" in self.cleaned_data
and self.cleaned_data["title"] == self.initial_revision.title
and self.cleaned_data["content"] == self.initial_revision.content
):
raise forms.ValidationError(
gettext("No changes made. Nothing to save.")
)
self.check_spam()
return self.cleaned_data
class SelectWidgetBootstrap(forms.Select):
"""
Formerly, we used Bootstrap 3's dropdowns. They look nice. But to
reduce bugs and reliance on JavaScript, it's now been replaced by
a conventional system platform drop-down.
https://getbootstrap.com/docs/4.4/components/dropdowns/
"""
def __init__(self, attrs=None, choices=()):
if attrs is None:
attrs = {"class": ""}
elif "class" not in attrs:
attrs["class"] = ""
attrs["class"] += " form-control"
super().__init__(attrs, choices)
class TextInputPrepend(forms.TextInput):
template_name = "wiki/forms/text.html"
def __init__(self, *args, **kwargs):
self.prepend = kwargs.pop("prepend", "")
super().__init__(*args, **kwargs)
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context["prepend"] = mark_safe(self.prepend)
return context
class CreateForm(forms.Form, SpamProtectionMixin):
def __init__(self, request, urlpath_parent, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
self.urlpath_parent = urlpath_parent
title = forms.CharField(
label=_("Title"),
)
slug = WikiSlugField(
label=_("Slug"),
help_text=_(
"This will be the address where your article can be found. Use only alphanumeric characters and - or _.<br>Note: If you change the slug later on, links pointing to this article are <b>not</b> updated."
),
max_length=models.URLPath.SLUG_MAX_LENGTH,
)
content = forms.CharField(
label=_("Contents"), required=False, widget=getEditor().get_widget()
) # @UndefinedVariable
summary = forms.CharField(
label=pgettext_lazy("Revision comment", "Summary"),
help_text=_("Write a brief message for the article's history log."),
required=False,
)
def clean_slug(self):
return _clean_slug(self.cleaned_data["slug"], self.urlpath_parent)
def clean(self):
self.check_spam()
return self.cleaned_data
class DeleteForm(forms.Form):
def __init__(self, *args, **kwargs):
self.article = kwargs.pop("article")
self.has_children = kwargs.pop("has_children")
super().__init__(*args, **kwargs)
confirm = forms.BooleanField(required=False, label=_("Yes, I am sure"))
purge = forms.BooleanField(
widget=HiddenInput(),
required=False,
label=_("Purge"),
help_text=_(
"Purge the article: Completely remove it (and all its contents) with no undo. Purging is a good idea if you want to free the slug such that users can create new articles in its place."
),
)
revision = forms.ModelChoiceField(
models.ArticleRevision.objects.all(),
widget=HiddenInput(),
required=False,
)
def clean(self):
if not self.cleaned_data["confirm"]:
raise forms.ValidationError(gettext("You are not sure enough!"))
if self.cleaned_data["revision"] != self.article.current_revision:
raise forms.ValidationError(
gettext(
"While you tried to delete this article, it was modified. TAKE CARE!"
)
)
return self.cleaned_data
class PermissionsForm(PluginSettingsFormMixin, forms.ModelForm):
locked = forms.BooleanField(
label=_("Lock article"),
help_text=_("Deny all users access to edit this article."),
required=False,
)
settings_form_headline = _("Permissions")
settings_order = 5
settings_write_access = False
owner_username = forms.CharField(
required=False,
label=_("Owner"),
help_text=_("Enter the username of the owner."),
)
group = forms.ModelChoiceField(
Group.objects.all(),
empty_label=_("(none)"),
label=_("Group"),
required=False,
widget=forms.Select(attrs={"class": "form-control"}),
)
if settings.USE_BOOTSTRAP_SELECT_WIDGET:
group.widget = SelectWidgetBootstrap()
recursive = forms.BooleanField(
label=_("Inherit permissions"),
help_text=_(
"Check here to apply the above permissions (excluding group and owner of the article) recursively to articles below this one."
),
required=False,
)
recursive_owner = forms.BooleanField(
label=_("Inherit owner"),
help_text=_(
"Check here to apply the ownership setting recursively to articles below this one."
),
required=False,
)
recursive_group = forms.BooleanField(
label=_("Inherit group"),
help_text=_(
"Check here to apply the group setting recursively to articles below this one."
),
required=False,
)
def get_usermessage(self):
if self.changed_data:
return _("Permission settings for the article were updated.")
else:
return _(
"Your permission settings were unchanged, so nothing saved."
)
def __init__(self, article, request, *args, **kwargs):
self.article = article
self.user = request.user
self.request = request
kwargs["instance"] = article
kwargs["initial"] = {"locked": article.current_revision.locked}
super().__init__(*args, **kwargs)
self.can_change_groups = False
self.can_assign = False
if permissions.can_assign(article, request.user):
self.can_assign = True
self.can_change_groups = True
self.fields["group"].queryset = Group.objects.all()
elif permissions.can_assign_owner(article, request.user):
self.fields["group"].queryset = Group.objects.filter(
user=request.user
)
self.can_change_groups = True
else:
# Quick-fix...
# Set the group dropdown to readonly and with the current
# group as only selectable option
self.fields["group"] = forms.ModelChoiceField(
queryset=Group.objects.filter(id=self.instance.group.id)
if self.instance.group
else Group.objects.none(),
empty_label=_("(none)"),
required=False,
widget=SelectWidgetBootstrap(attrs={"disabled": True})
if settings.USE_BOOTSTRAP_SELECT_WIDGET
else forms.Select(attrs={"disabled": True}),
)
self.fields["group_read"].widget = forms.HiddenInput()
self.fields["group_write"].widget = forms.HiddenInput()
if not self.can_assign:
self.fields["owner_username"].widget = forms.TextInput(
attrs={"readonly": "true"}
)
self.fields["recursive"].widget = forms.HiddenInput()
self.fields["recursive_group"].widget = forms.HiddenInput()
self.fields["recursive_owner"].widget = forms.HiddenInput()
self.fields["locked"].widget = forms.HiddenInput()
self.fields["owner_username"].initial = (
getattr(article.owner, User.USERNAME_FIELD)
if article.owner
else ""
)
def clean_owner_username(self):
if self.can_assign:
username = self.cleaned_data["owner_username"]
if username:
try:
kwargs = {User.USERNAME_FIELD: username}
user = User.objects.get(**kwargs)
except User.DoesNotExist:
raise forms.ValidationError(
gettext("No user with that username")
)
else:
user = None
else:
user = self.article.owner
return user
def save(self, commit=True):
article = super().save(commit=False)
# Alter the owner according to the form field owner_username
# TODO: Why not rename this field to 'owner' so this happens
# automatically?
article.owner = self.cleaned_data["owner_username"]
# Revert any changes to group permissions if the
# current user is not allowed (see __init__)
# TODO: Write clean methods for this instead!
if not self.can_change_groups:
article.group = self.article.group
article.group_read = self.article.group_read
article.group_write = self.article.group_write
if self.can_assign:
if self.cleaned_data["recursive"]:
article.set_permissions_recursive()
if self.cleaned_data["recursive_owner"]:
article.set_owner_recursive()
if self.cleaned_data["recursive_group"]:
article.set_group_recursive()
if (
self.cleaned_data["locked"]
and not article.current_revision.locked
):
revision = models.ArticleRevision()
revision.inherit_predecessor(self.article)
revision.set_from_request(self.request)
revision.automatic_log = _("Article locked for editing")
revision.locked = True
self.article.add_revision(revision)
elif (
not self.cleaned_data["locked"]
and article.current_revision.locked
):
revision = models.ArticleRevision()
revision.inherit_predecessor(self.article)
revision.set_from_request(self.request)
revision.automatic_log = _("Article unlocked for editing")
revision.locked = False
self.article.add_revision(revision)
article.save()
class Meta:
model = models.Article
fields = (
"locked",
"owner_username",
"recursive_owner",
"group",
"recursive_group",
"group_read",
"group_write",
"other_read",
"other_write",
"recursive",
)
widgets = {}
class DirFilterForm(forms.Form):
query = forms.CharField(
widget=forms.TextInput(
attrs={"placeholder": _("Filter..."), "class": "search-query"}
),
required=False,
)
class SearchForm(forms.Form):
q = forms.CharField(
widget=forms.TextInput(
attrs={"placeholder": _("Search..."), "class": "search-query"}
),
required=False,
)

View File

@@ -0,0 +1,106 @@
import random
import string
import django.contrib.auth.models
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import FieldDoesNotExist
from django.db.models.fields import CharField
from django.db.models.fields import EmailField
from django.utils.translation import gettext_lazy as _
from wiki.conf import settings
def _get_field(model, field):
try:
return model._meta.get_field(field)
except FieldDoesNotExist:
return
User = get_user_model()
def check_user_field(user_model):
return isinstance(
_get_field(user_model, user_model.USERNAME_FIELD), CharField
)
def check_email_field(user_model):
return isinstance(
_get_field(user_model, user_model.get_email_field_name()), EmailField
)
# django parses the ModelForm (and Meta classes) on class creation, which fails with custom models without expected fields.
# We need to check this here, because if this module can't load then system checks can't run.
CustomUser = (
User
if (
settings.ACCOUNT_HANDLING
and check_user_field(User)
and check_email_field(User)
)
else django.contrib.auth.models.User
)
class UserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Add honeypots
self.honeypot_fieldnames = "address", "phone"
self.honeypot_class = "".join(
random.choice(string.ascii_uppercase + string.digits)
for __ in range(10)
)
self.honeypot_jsfunction = "f" + "".join(
random.choice(string.ascii_uppercase + string.digits)
for __ in range(10)
)
for fieldname in self.honeypot_fieldnames:
self.fields[fieldname] = forms.CharField(
widget=forms.TextInput(attrs={"class": self.honeypot_class}),
required=False,
)
def clean(self):
super().clean()
for fieldname in self.honeypot_fieldnames:
if self.cleaned_data[fieldname]:
raise forms.ValidationError(
"Thank you, non-human visitor. Please keep trying to fill in the form."
)
return self.cleaned_data
class Meta:
model = CustomUser
fields = (CustomUser.USERNAME_FIELD, CustomUser.get_email_field_name())
class UserUpdateForm(forms.ModelForm):
password1 = forms.CharField(
label="New password", widget=forms.PasswordInput(), required=False
)
password2 = forms.CharField(
label="Confirm password", widget=forms.PasswordInput(), required=False
)
def clean(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password1 != password2:
raise forms.ValidationError(_("Passwords don't match"))
return self.cleaned_data
class Meta:
model = CustomUser
fields = [CustomUser.get_email_field_name()]

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

1
src/wiki/locale/pt Normal file
View File

@@ -0,0 +1 @@
pt_PT

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

1
src/wiki/locale/zh_Hans Normal file
View File

@@ -0,0 +1 @@
zh_CN

Binary file not shown.

184
src/wiki/managers.py Normal file
View File

@@ -0,0 +1,184 @@
from django.db import models
from django.db.models import Count
from django.db.models import Q
from django.db.models.query import EmptyQuerySet
from django.db.models.query import QuerySet
from mptt.managers import TreeManager
class ArticleQuerySet(QuerySet):
def can_read(self, user):
"""Filter objects so only the ones with a user's reading access
are included"""
if user.has_perm("wiki.moderator"):
return self
if user.is_anonymous:
q = self.filter(other_read=True)
else:
q = self.filter(
Q(other_read=True)
| Q(owner=user)
| (Q(group__user=user) & Q(group_read=True))
).annotate(Count("id"))
return q
def can_write(self, user):
"""Filter objects so only the ones with a user's writing access
are included"""
if user.has_perm("wiki.moderator"):
return self
if user.is_anonymous:
q = self.filter(other_write=True)
else:
q = self.filter(
Q(other_write=True)
| Q(owner=user)
| (Q(group__user=user) & Q(group_write=True))
)
return q
def active(self):
return self.filter(current_revision__deleted=False)
class ArticleEmptyQuerySet(EmptyQuerySet):
def can_read(self, user):
return self
def can_write(self, user):
return self
def active(self):
return self
class ArticleFkQuerySetMixin:
def can_read(self, user):
"""Filter objects so only the ones with a user's reading access
are included"""
if user.has_perm("wiki.moderate"):
return self
if user.is_anonymous:
q = self.filter(article__other_read=True)
else:
# https://github.com/django-wiki/django-wiki/issues/67
q = self.filter(
Q(article__other_read=True)
| Q(article__owner=user)
| (Q(article__group__user=user) & Q(article__group_read=True))
).annotate(Count("id"))
return q
def can_write(self, user):
"""Filter objects so only the ones with a user's writing access
are included"""
if user.has_perm("wiki.moderate"):
return self
if user.is_anonymous:
q = self.filter(article__other_write=True)
else:
# https://github.com/django-wiki/django-wiki/issues/67
q = self.filter(
Q(article__other_write=True)
| Q(article__owner=user)
| (Q(article__group__user=user) & Q(article__group_write=True))
).annotate(Count("id"))
return q
def active(self):
return self.filter(article__current_revision__deleted=False)
class ArticleFkEmptyQuerySetMixin:
def can_read(self, user):
return self
def can_write(self, user):
return self
def active(self):
return self
class ArticleFkQuerySet(ArticleFkQuerySetMixin, QuerySet):
pass
class ArticleFkEmptyQuerySet(ArticleFkEmptyQuerySetMixin, EmptyQuerySet):
pass
class ArticleManager(models.Manager):
def get_empty_query_set(self):
return self.get_queryset().none()
def get_queryset(self):
return ArticleQuerySet(self.model, using=self._db)
def active(self):
return self.get_queryset().active()
def can_read(self, user):
return self.get_queryset().can_read(user)
def can_write(self, user):
return self.get_queryset().can_write(user)
class ArticleFkManager(models.Manager):
def get_empty_query_set(self):
return self.get_queryset().none()
def get_queryset(self):
return ArticleFkQuerySet(self.model, using=self._db)
def active(self):
return self.get_queryset().active()
def can_read(self, user):
return self.get_queryset().can_read(user)
def can_write(self, user):
return self.get_queryset().can_write(user)
class URLPathEmptyQuerySet(EmptyQuerySet, ArticleFkEmptyQuerySetMixin):
def select_related_common(self):
return self
def default_order(self):
return self
class URLPathQuerySet(QuerySet, ArticleFkQuerySetMixin):
def select_related_common(self):
return self.select_related(
"parent", "article__current_revision", "article__owner"
)
def default_order(self):
"""Returns elements by there article order"""
return self.order_by("article__current_revision__title")
class URLPathManager(TreeManager):
def get_empty_query_set(self):
return self.get_queryset().none()
def get_queryset(self):
"""Return a QuerySet with the same ordering as the TreeManager."""
return URLPathQuerySet(self.model, using=self._db).order_by(
self.tree_id_attr, self.left_attr
)
def select_related_common(self):
return self.get_queryset().common_select_related()
def active(self):
return self.get_queryset().active()
def can_read(self, user):
return self.get_queryset().can_read(user)
def can_write(self, user):
return self.get_queryset().can_write(user)

View File

@@ -0,0 +1,455 @@
import django.db.models.deletion
import mptt.fields
from django.conf import settings
from django.db import migrations
from django.db import models
from django.db.models.fields import GenericIPAddressField as IPAddressField
from wiki.conf.settings import GROUP_MODEL
class Migration(migrations.Migration):
dependencies = [
("sites", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("contenttypes", "0001_initial"),
("auth", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Article",
fields=[
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
(
"created",
models.DateTimeField(verbose_name="created", auto_now_add=True),
),
(
"modified",
models.DateTimeField(
verbose_name="modified",
auto_now=True,
help_text="Article properties last modified",
),
),
(
"group_read",
models.BooleanField(default=True, verbose_name="group read access"),
),
(
"group_write",
models.BooleanField(
default=True, verbose_name="group write access"
),
),
(
"other_read",
models.BooleanField(
default=True, verbose_name="others read access"
),
),
(
"other_write",
models.BooleanField(
default=True, verbose_name="others write access"
),
),
],
options={
"permissions": (
("moderate", "Can edit all articles and lock/unlock/restore"),
("assign", "Can change ownership of any article"),
("grant", "Can assign permissions to other users"),
),
},
bases=(models.Model,),
),
migrations.CreateModel(
name="ArticleForObject",
fields=[
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
("object_id", models.PositiveIntegerField(verbose_name="object ID")),
("is_mptt", models.BooleanField(default=False, editable=False)),
(
"article",
models.ForeignKey(to="wiki.Article", on_delete=models.CASCADE),
),
(
"content_type",
models.ForeignKey(
related_name="content_type_set_for_articleforobject",
verbose_name="content type",
to="contenttypes.ContentType",
on_delete=models.CASCADE,
),
),
],
options={
"verbose_name_plural": "Articles for object",
"verbose_name": "Article for object",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="ArticlePlugin",
fields=[
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
("deleted", models.BooleanField(default=False)),
("created", models.DateTimeField(auto_now_add=True)),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name="ArticleRevision",
fields=[
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
(
"revision_number",
models.IntegerField(verbose_name="revision number", editable=False),
),
("user_message", models.TextField(blank=True)),
("automatic_log", models.TextField(blank=True, editable=False)),
(
"ip_address",
IPAddressField(
null=True, verbose_name="IP address", blank=True, editable=False
),
),
("modified", models.DateTimeField(auto_now=True)),
("created", models.DateTimeField(auto_now_add=True)),
("deleted", models.BooleanField(default=False, verbose_name="deleted")),
("locked", models.BooleanField(default=False, verbose_name="locked")),
(
"content",
models.TextField(blank=True, verbose_name="article contents"),
),
(
"title",
models.CharField(
max_length=512,
verbose_name="article title",
help_text="Each revision contains a title field that must be filled out, even if the title has not changed",
),
),
(
"article",
models.ForeignKey(
to="wiki.Article",
verbose_name="article",
on_delete=models.CASCADE,
),
),
(
"previous_revision",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
to="wiki.ArticleRevision",
),
),
(
"user",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
to=settings.AUTH_USER_MODEL,
verbose_name="user",
),
),
],
options={
"get_latest_by": "revision_number",
"ordering": ("created",),
},
bases=(models.Model,),
),
migrations.CreateModel(
name="ReusablePlugin",
fields=[
(
"articleplugin_ptr",
models.OneToOneField(
primary_key=True,
parent_link=True,
to="wiki.ArticlePlugin",
serialize=False,
auto_created=True,
on_delete=models.CASCADE,
),
),
(
"articles",
models.ManyToManyField(
related_name="shared_plugins_set", to="wiki.Article"
),
),
],
options={},
bases=("wiki.articleplugin",),
),
migrations.CreateModel(
name="RevisionPlugin",
fields=[
(
"articleplugin_ptr",
models.OneToOneField(
primary_key=True,
parent_link=True,
to="wiki.ArticlePlugin",
serialize=False,
auto_created=True,
on_delete=models.CASCADE,
),
),
],
options={},
bases=("wiki.articleplugin",),
),
migrations.CreateModel(
name="RevisionPluginRevision",
fields=[
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
(
"revision_number",
models.IntegerField(verbose_name="revision number", editable=False),
),
("user_message", models.TextField(blank=True)),
("automatic_log", models.TextField(blank=True, editable=False)),
(
"ip_address",
IPAddressField(
null=True, verbose_name="IP address", blank=True, editable=False
),
),
("modified", models.DateTimeField(auto_now=True)),
("created", models.DateTimeField(auto_now_add=True)),
("deleted", models.BooleanField(default=False, verbose_name="deleted")),
("locked", models.BooleanField(default=False, verbose_name="locked")),
(
"plugin",
models.ForeignKey(
related_name="revision_set",
to="wiki.RevisionPlugin",
on_delete=models.CASCADE,
),
),
(
"previous_revision",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
to="wiki.RevisionPluginRevision",
),
),
(
"user",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
to=settings.AUTH_USER_MODEL,
verbose_name="user",
),
),
],
options={
"get_latest_by": "revision_number",
"ordering": ("-created",),
},
bases=(models.Model,),
),
migrations.CreateModel(
name="SimplePlugin",
fields=[
(
"articleplugin_ptr",
models.OneToOneField(
primary_key=True,
parent_link=True,
to="wiki.ArticlePlugin",
serialize=False,
auto_created=True,
on_delete=models.CASCADE,
),
),
(
"article_revision",
models.ForeignKey(
to="wiki.ArticleRevision", on_delete=models.CASCADE
),
),
],
options={},
bases=("wiki.articleplugin",),
),
migrations.CreateModel(
name="URLPath",
fields=[
(
"id",
models.AutoField(
serialize=False,
primary_key=True,
auto_created=True,
verbose_name="ID",
),
),
("slug", models.SlugField(null=True, blank=True, verbose_name="slug")),
("lft", models.PositiveIntegerField(db_index=True, editable=False)),
("rght", models.PositiveIntegerField(db_index=True, editable=False)),
("tree_id", models.PositiveIntegerField(db_index=True, editable=False)),
("level", models.PositiveIntegerField(db_index=True, editable=False)),
(
"article",
models.ForeignKey(
help_text="This field is automatically updated, but you need to populate it when creating a new URL path.",
on_delete=django.db.models.deletion.CASCADE,
to="wiki.Article",
verbose_name="article",
),
),
(
"parent",
mptt.fields.TreeForeignKey(
blank=True,
help_text="Position of URL path in the tree.",
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="children",
to="wiki.URLPath",
),
),
(
"site",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="sites.Site"
),
),
],
options={
"verbose_name_plural": "URL paths",
"verbose_name": "URL path",
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name="urlpath",
unique_together={("site", "parent", "slug")},
),
migrations.AddField(
model_name="revisionplugin",
name="current_revision",
field=models.OneToOneField(
related_name="plugin_set",
null=True,
help_text="The revision being displayed for this plugin. If you need to do a roll-back, simply change the value of this field.",
blank=True,
to="wiki.RevisionPluginRevision",
verbose_name="current revision",
on_delete=models.CASCADE,
),
preserve_default=True,
),
migrations.AlterUniqueTogether(
name="articlerevision",
unique_together={("article", "revision_number")},
),
migrations.AddField(
model_name="articleplugin",
name="article",
field=models.ForeignKey(
to="wiki.Article", verbose_name="article", on_delete=models.CASCADE
),
preserve_default=True,
),
migrations.AlterUniqueTogether(
name="articleforobject",
unique_together={("content_type", "object_id")},
),
migrations.AddField(
model_name="article",
name="current_revision",
field=models.OneToOneField(
related_name="current_set",
null=True,
help_text="The revision being displayed for this article. If you need to do a roll-back, simply change the value of this field.",
blank=True,
to="wiki.ArticleRevision",
verbose_name="current revision",
on_delete=models.CASCADE,
),
preserve_default=True,
),
migrations.AddField(
model_name="article",
name="group",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
help_text="Like in a UNIX file system, permissions can be given to a user according to group membership. Groups are handled through the Django auth system.",
blank=True,
to=GROUP_MODEL,
verbose_name="group",
),
preserve_default=True,
),
migrations.AddField(
model_name="article",
name="owner",
field=models.ForeignKey(
related_name="owned_articles",
null=True,
on_delete=django.db.models.deletion.SET_NULL,
help_text="The owner of the article, usually the creator. The owner always has both read and write access.",
blank=True,
to=settings.AUTH_USER_MODEL,
verbose_name="owner",
),
preserve_default=True,
),
]

View File

@@ -0,0 +1,27 @@
# Generated by Django 1.10.7 on 2017-06-06 23:18
import django.db.models.deletion
import mptt.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("wiki", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="urlpath",
name="moved_to",
field=mptt.fields.TreeForeignKey(
blank=True,
help_text="Article path was moved to this location",
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="moved_from",
to="wiki.URLPath",
verbose_name="Moved to",
),
),
]

View File

@@ -0,0 +1,42 @@
# Upgrades fields changed in django-mptt
# See: https://github.com/django-mptt/django-mptt/pull/578
# Generated by Django 2.2.7 on 2020-02-06 20:36
import django.db.models.deletion
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
("wiki", "0002_urlpath_moved_to"),
]
operations = [
migrations.AlterField(
model_name="urlpath",
name="level",
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name="urlpath",
name="lft",
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name="urlpath",
name="rght",
field=models.PositiveIntegerField(editable=False),
),
# Added as a no-op when upgrading to django-mptt 0.13
migrations.AlterField(
model_name="articleforobject",
name="content_type",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="content_type_set_for_%(class)s",
to="contenttypes.contenttype",
verbose_name="content type",
),
),
]

View File

@@ -0,0 +1,43 @@
# Generated by Django 5.2.6 on 2025-09-16 19:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wiki', '0003_mptt_upgrade'),
]
operations = [
migrations.AlterField(
model_name='article',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='articleforobject',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='articleplugin',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='articlerevision',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='revisionpluginrevision',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='urlpath',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]

View File

View File

@@ -0,0 +1,49 @@
from django import shortcuts
from django import urls
from django.urls import base
from django.utils.functional import lazy
from .article import * # noqa
from .pluginbase import * # noqa
from .urlpath import * # noqa
original_django_reverse = urls.reverse
def reverse(*args, **kwargs):
"""Now this is a crazy and silly hack, but it is basically here to
enforce that an empty path always takes precedence over an article_id
such that the root article doesn't get resolved to /ID/ but /.
Another crazy hack that this supports is transforming every wiki url
by a function. If _transform_url is set on this function, it will
return the result of calling reverse._transform_url(reversed_url)
for every url in the wiki namespace.
"""
if isinstance(args[0], str) and args[0].startswith("wiki:"):
url_kwargs = kwargs.get("kwargs", {})
path = url_kwargs.get("path", False)
# If a path is supplied then discard the article_id
if path is not False:
url_kwargs.pop("article_id", None)
url_kwargs["path"] = path
kwargs["kwargs"] = url_kwargs
url = original_django_reverse(*args, **kwargs)
if hasattr(reverse, "_transform_url"):
url = reverse._transform_url(url)
else:
url = original_django_reverse(*args, **kwargs)
return url
reverse_lazy = lazy(reverse, str)
# Patch up other locations of the reverse function
base.reverse = reverse
base.reverse_lazy = reverse_lazy
urls.reverse = reverse
urls.reverse_lazy = reverse_lazy
shortcuts.reverse = reverse

510
src/wiki/models/article.py Normal file
View File

@@ -0,0 +1,510 @@
from django.conf import settings as django_settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.db import models
from django.db.models.fields import GenericIPAddressField as IPAddressField
from django.db.models.signals import post_save
from django.db.models.signals import pre_delete
from django.db.models.signals import pre_save
from django.urls import reverse
from django.utils import translation
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from mptt.models import MPTTModel
from wiki import managers
from wiki.conf import settings
from wiki.core import permissions
from wiki.core.markdown import article_markdown
from wiki.decorators import disable_signal_for_loaddata
__all__ = [
"Article",
"ArticleForObject",
"ArticleRevision",
"BaseRevisionMixin",
]
class Article(models.Model):
objects = managers.ArticleManager()
current_revision = models.OneToOneField(
"ArticleRevision",
verbose_name=_("current revision"),
blank=True,
null=True,
related_name="current_set",
on_delete=models.CASCADE,
help_text=_(
"The revision being displayed for this article. If you need to do a roll-back, simply change the value of this field."
),
)
created = models.DateTimeField(
auto_now_add=True,
verbose_name=_("created"),
)
modified = models.DateTimeField(
auto_now=True,
verbose_name=_("modified"),
help_text=_("Article properties last modified"),
)
owner = models.ForeignKey(
django_settings.AUTH_USER_MODEL,
verbose_name=_("owner"),
blank=True,
null=True,
related_name="owned_articles",
help_text=_(
"The owner of the article, usually the creator. The owner always has both read and write access."
),
on_delete=models.SET_NULL,
)
group = models.ForeignKey(
settings.GROUP_MODEL,
verbose_name=_("group"),
blank=True,
null=True,
help_text=_(
"Like in a UNIX file system, permissions can be given to a user according to group membership. Groups are handled through the Django auth system."
),
on_delete=models.SET_NULL,
)
group_read = models.BooleanField(
default=True, verbose_name=_("group read access")
)
group_write = models.BooleanField(
default=True, verbose_name=_("group write access")
)
other_read = models.BooleanField(
default=True, verbose_name=_("others read access")
)
other_write = models.BooleanField(
default=True, verbose_name=_("others write access")
)
# PERMISSIONS
def can_read(self, user):
return permissions.can_read(self, user)
def can_write(self, user):
return permissions.can_write(self, user)
def can_delete(self, user):
return permissions.can_delete(self, user)
def can_moderate(self, user):
return permissions.can_moderate(self, user)
def can_assign(self, user):
return permissions.can_assign(self, user)
def ancestor_objects(self):
"""NB! This generator is expensive, so use it with care!!"""
for obj in self.articleforobject_set.filter(is_mptt=True):
yield from obj.content_object.get_ancestors()
def descendant_objects(self):
"""NB! This generator is expensive, so use it with care!!"""
for obj in self.articleforobject_set.filter(is_mptt=True):
yield from obj.content_object.get_descendants()
def get_children(self, max_num=None, user_can_read=None, **kwargs):
"""NB! This generator is expensive, so use it with care!!"""
cnt = 0
for obj in self.articleforobject_set.filter(is_mptt=True):
if user_can_read:
objects = (
obj.content_object.get_children()
.filter(**kwargs)
.can_read(user_can_read)
)
else:
objects = obj.content_object.get_children().filter(**kwargs)
for child in objects.order_by(
"articles__article__current_revision__title"
):
cnt += 1
if max_num and cnt > max_num:
return
yield child
# All recursive permission methods will use descendant_objects to access
# generic relations and check if they are using MPTT and have
# INHERIT_PERMISSIONS=True
def set_permissions_recursive(self):
for descendant in self.descendant_objects():
if descendant.INHERIT_PERMISSIONS:
descendant.article.group_read = self.group_read
descendant.article.group_write = self.group_write
descendant.article.other_read = self.other_read
descendant.article.other_write = self.other_write
descendant.article.save()
def set_group_recursive(self):
for descendant in self.descendant_objects():
if descendant.INHERIT_PERMISSIONS:
descendant.article.group = self.group
descendant.article.save()
def set_owner_recursive(self):
for descendant in self.descendant_objects():
if descendant.INHERIT_PERMISSIONS:
descendant.article.owner = self.owner
descendant.article.save()
def add_revision(self, new_revision, save=True):
"""
Sets the properties of a revision and ensures its the current
revision.
"""
assert self.id or save, (
"Article.add_revision: Sorry, you cannot add a"
"revision to an article that has not been saved "
"without using save=True"
)
if not self.id:
self.save()
revisions = self.articlerevision_set.all()
try:
new_revision.revision_number = (
revisions.latest().revision_number + 1
)
except ArticleRevision.DoesNotExist:
new_revision.revision_number = 0
new_revision.article = self
new_revision.previous_revision = self.current_revision
if save:
new_revision.clean()
new_revision.save()
self.current_revision = new_revision
if save:
self.save()
def add_object_relation(self, obj):
return ArticleForObject.objects.get_or_create(
article=self,
content_type=ContentType.objects.get_for_model(obj),
object_id=obj.id,
is_mptt=isinstance(obj, MPTTModel),
)
@classmethod
def get_for_object(cls, obj):
return ArticleForObject.objects.get(
object_id=obj.id,
content_type=ContentType.objects.get_for_model(obj),
).article
def __str__(self):
if self.current_revision:
return self.current_revision.title
obj_name = _("Article without content (%(id)d)") % {"id": self.id}
return str(obj_name)
class Meta:
permissions = (
("moderate", _("Can edit all articles and lock/unlock/restore")),
("assign", _("Can change ownership of any article")),
("grant", _("Can assign permissions to other users")),
)
def render(self, preview_content=None, user=None):
if not self.current_revision:
return ""
if preview_content:
content = preview_content
else:
content = self.current_revision.content
return mark_safe(
article_markdown(
content, self, preview=preview_content is not None, user=user
)
)
def get_cache_key(self):
"""Returns per-article cache key."""
lang = translation.get_language()
key_raw = "wiki-article-{id}-{lang}".format(
id=self.current_revision.id if self.current_revision else self.id,
lang=lang,
)
# https://github.com/django-wiki/django-wiki/issues/1065
return slugify(key_raw, allow_unicode=True)
def get_cache_content_key(self, user=None):
"""Returns per-article-user cache key."""
key_raw = "{key}-{user}".format(
key=self.get_cache_key(),
user=user.get_username() if user else "-anonymous",
)
# https://github.com/django-wiki/django-wiki/issues/1065
return slugify(key_raw, allow_unicode=True)
def get_cached_content(self, user=None):
"""Returns cached version of rendered article.
The cache contains one "per-article" entry plus multiple
"per-article-user" entries. The per-article-user entries contain the
rendered article, the per-article entry contains list of the
per-article-user keys. The rendered article in cache (per-article-user)
is used only if the key is in the per-article entry. To delete
per-article invalidates all article cache entries."""
if user and user.is_anonymous:
user = None
cache_key = self.get_cache_key()
cache_content_key = self.get_cache_content_key(user)
cached_items = cache.get(cache_key, [])
if cache_content_key in cached_items:
cached_content = cache.get(cache_content_key)
if cached_content is not None:
return mark_safe(cached_content)
cached_content = self.render(user=user)
cached_items.append(cache_content_key)
cache.set(cache_key, cached_items, settings.CACHE_TIMEOUT)
cache.set(cache_content_key, cached_content, settings.CACHE_TIMEOUT)
return mark_safe(cached_content)
def clear_cache(self):
cache.delete(self.get_cache_key())
def get_url_kwargs(self):
urlpaths = self.urlpath_set.all()
if urlpaths.exists():
return {"path": urlpaths[0].path}
return {"article_id": self.id}
def get_absolute_url(self):
return reverse("wiki:get", kwargs=self.get_url_kwargs())
class ArticleForObject(models.Model):
objects = managers.ArticleFkManager()
article = models.ForeignKey("Article", on_delete=models.CASCADE)
# Same as django.contrib.comments
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
verbose_name=_("content type"),
related_name="content_type_set_for_%(class)s",
)
object_id = models.PositiveIntegerField(_("object ID"))
content_object = GenericForeignKey("content_type", "object_id")
is_mptt = models.BooleanField(default=False, editable=False)
def __str__(self):
return str(self.article)
class Meta:
verbose_name = _("Article for object")
verbose_name_plural = _("Articles for object")
# Do not allow several objects
unique_together = ("content_type", "object_id")
class BaseRevisionMixin(models.Model):
"""This is an abstract model used as a mixin: Do not override any of the
core model methods but respect the inheritor's freedom to do so itself."""
revision_number = models.IntegerField(
editable=False, verbose_name=_("revision number")
)
user_message = models.TextField(
blank=True,
)
automatic_log = models.TextField(
blank=True,
editable=False,
)
ip_address = IPAddressField(
_("IP address"), blank=True, null=True, editable=False
)
user = models.ForeignKey(
django_settings.AUTH_USER_MODEL,
verbose_name=_("user"),
blank=True,
null=True,
on_delete=models.SET_NULL,
)
modified = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
previous_revision = models.ForeignKey(
"self", blank=True, null=True, on_delete=models.SET_NULL
)
# NOTE! The semantics of these fields are not related to the revision itself
# but the actual related object. If the latest revision says "deleted=True" then
# the related object should be regarded as deleted.
deleted = models.BooleanField(
verbose_name=_("deleted"),
default=False,
)
locked = models.BooleanField(
verbose_name=_("locked"),
default=False,
)
def set_from_request(self, request):
if request.user.is_authenticated:
self.user = request.user
if settings.LOG_IPS_USERS:
self.ip_address = request.META.get("REMOTE_ADDR", None)
elif settings.LOG_IPS_ANONYMOUS:
self.ip_address = request.META.get("REMOTE_ADDR", None)
def inherit_predecessor(self, predecessor):
"""
This is a naive way of inheriting, assuming that ``predecessor`` is in
fact the predecessor and there hasn't been any intermediate changes!
:param: predecessor is an instance of whatever object for which
object.current_revision implements BaseRevisionMixin.
"""
predecessor = predecessor.current_revision
self.previous_revision = predecessor
self.deleted = predecessor.deleted
self.locked = predecessor.locked
self.revision_number = predecessor.revision_number + 1
class Meta:
abstract = True
class ArticleRevision(BaseRevisionMixin, models.Model):
"""This is where main revision data is stored. To make it easier to
copy, do NEVER create m2m relationships."""
objects = managers.ArticleFkManager()
article = models.ForeignKey(
"Article", on_delete=models.CASCADE, verbose_name=_("article")
)
# This is where the content goes, with whatever markup language is used
content = models.TextField(blank=True, verbose_name=_("article contents"))
# This title is automatically set from either the article's title or
# the last used revision...
title = models.CharField(
max_length=512,
verbose_name=_("article title"),
null=False,
blank=False,
help_text=_(
"Each revision contains a title field that must be filled out, even if the title has not changed"
),
)
# TODO:
# Allow a revision to redirect to another *article*. This
# way, we can have redirects and still maintain old content.
# redirect = models.ForeignKey('Article', null=True, blank=True,
# verbose_name=_('redirect'),
# help_text=_('If set, the article will redirect to the contents of another article.'),
# related_name='redirect_set')
def __str__(self):
return "%s (%d)" % (self.title, self.revision_number)
def clean(self):
# Enforce DOS line endings \r\n. It is the standard for web browsers,
# but when revisions are created programatically, they might
# have UNIX line endings \n instead.
self.content = self.content.replace("\r", "").replace("\n", "\r\n")
def inherit_predecessor(self, article):
"""
Inherit certain properties from predecessor because it's very
convenient. Remember to always call this method before
setting properties :)"""
predecessor = article.current_revision
self.article = predecessor.article
self.content = predecessor.content
self.title = predecessor.title
self.deleted = predecessor.deleted
self.locked = predecessor.locked
class Meta:
get_latest_by = "revision_number"
ordering = ("created",)
unique_together = ("article", "revision_number")
######################################################
# SIGNAL HANDLERS
######################################################
# clear the ancestor cache when saving or deleting articles so things like
# article_lists will be refreshed
def _clear_ancestor_cache(article):
for ancestor in article.ancestor_objects():
ancestor.article.clear_cache()
@disable_signal_for_loaddata
def on_article_save_clear_cache(instance, **kwargs):
on_article_delete_clear_cache(instance, **kwargs)
@disable_signal_for_loaddata
def on_article_delete_clear_cache(instance, **kwargs):
_clear_ancestor_cache(instance)
instance.clear_cache()
@disable_signal_for_loaddata
def on_article_revision_pre_save(**kwargs):
instance = kwargs["instance"]
if instance._state.adding:
revision_changed = (
not instance.previous_revision
and instance.article
and instance.article.current_revision
and instance.article.current_revision != instance
)
if revision_changed:
instance.previous_revision = instance.article.current_revision
if not instance.revision_number:
try:
previous_revision = instance.article.articlerevision_set.latest()
instance.revision_number = previous_revision.revision_number + 1
except ArticleRevision.DoesNotExist:
instance.revision_number = 1
@disable_signal_for_loaddata
def on_article_revision_post_save(**kwargs):
instance = kwargs["instance"]
if not instance.article.current_revision:
# If I'm saved from Django admin, then article.current_revision is
# me!
instance.article.current_revision = instance
instance.article.save()
pre_save.connect(on_article_revision_pre_save, ArticleRevision)
post_save.connect(on_article_revision_post_save, ArticleRevision)
post_save.connect(on_article_save_clear_cache, Article)
pre_delete.connect(on_article_delete_clear_cache, Article)

Some files were not shown because too many files have changed in this diff Show More