$ git clone http://thingshare.ion.nu/thingshare.git
commit 4feba30f27b4cd7ef2ab04b52d4b80e7626faa43
Author: Alicia <...>
Date:   Sat Mar 14 01:22:21 2020 +0100

    Initial commit

diff --git a/.htaccess b/.htaccess
new file mode 100644
index 0000000..e208db5
--- /dev/null
+++ b/.htaccess
@@ -0,0 +1,6 @@
+# Keep mod_negotiation from getting in the way
+Options -Multiviews
+# Redirect requests to paths that don't exist to index.php
+RewriteEngine On
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteRule .* index.php
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are 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.
+
+  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.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  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 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 work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  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 AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/Dependencies b/Dependencies
new file mode 100644
index 0000000..8e5d611
--- /dev/null
+++ b/Dependencies
@@ -0,0 +1,12 @@
+Site dependencies (clone directly to web directory)
+Parsedown (git clone https://github.com/erusev/parsedown)
+Mdjs (git clone https://github.com/hangxingliu/mdjs)
+
+Web dependencies:
+PHP
+PHP curl module
+PHP MariaDB/MySQL module
+
+System dependencies (just need to be installed and findable in path)
+assimp (to convert 3D models to a common format for preview generation)
+One of: povray, openscad (to generate previews)
diff --git a/Licenses b/Licenses
new file mode 100644
index 0000000..e58aa7d
--- /dev/null
+++ b/Licenses
@@ -0,0 +1,7 @@
+Thingshare is released under the terms of the AGPLv3+. For details, see COPYING.
+
+External resources used by Thingshare, and their respective licenses:
+parsedown: under the terms of the MIT license (https://github.com/erusev/parsedown)
+mdjs: under the terms of the Apache license (https://github.com/hangxingliu/mdjs)
+icons/default.svg: "Editor, software, text icon" from the Macaron icon set by Goescat Wei, under the terms of the Creative Commons Attribution 3.0 Unported (https://www.iconfinder.com/icons/3246744/editor_software_text_icon)
+icons/scad.png: GNU GPLv2 (https://github.com/openscad/openscad/blob/master/icons/SCAD.png)
diff --git a/admin.php b/admin.php
new file mode 100644
index 0000000..93ad9de
--- /dev/null
+++ b/admin.php
@@ -0,0 +1,37 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+if(isset($_COOKIE['PHPSESSID'])){session_start();}
+if(!isset($_SESSION['id'])){header('Location: '.BASEURL.'/login?returnto='.urlencode($_SERVER['REQUEST_URI']));}
+include_once('head.php');
+switch($path[2])
+{
+  case 'privileges': include('admin_privileges.php'); break;
+  case 'moderate': include('admin_moderate.php'); break;
+  case 'federation': include('admin_federation.php'); break;
+  case 'filetypes': include('admin_filetypes.php'); break;
+  case 'licenses': include('admin_licenses.php'); break;
+  default:
+    if($privileges&PRIV_PRIVILEGES){print('<a href="'.BASEURL.'/admin/privileges">Manage user privileges</a><br />');}
+    if($privileges&PRIV_MODERATE){print('<a href="'.BASEURL.'/admin/moderate">Moderation options</a><br />');}
+    if($privileges&PRIV_FEDERATION){print('<a href="'.BASEURL.'/admin/federation">Manage peer federation</a><br />');}
+    if($privileges&PRIV_FILETYPES){print('<a href="'.BASEURL.'/admin/filetypes">Manage filetypes</a><br />');}
+    if($privileges&PRIV_LICENSES){print('<a href="'.BASEURL.'/admin/licenses">Manage the license list</a><br />');}
+}
+?>
diff --git a/admin_federation.php b/admin_federation.php
new file mode 100644
index 0000000..ab601fc
--- /dev/null
+++ b/admin_federation.php
@@ -0,0 +1,66 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+include_once('nonce.php');
+if(!isset($_SESSION['id'])){die(_('Insufficient privileges'));}
+if(!($privileges&PRIV_FEDERATION)){die(_('Insufficient privileges'));}
+
+if(checknonce()) // Save changes
+{
+  if(isset($_POST['options']))
+  {
+    setoption('autofollow', isset($_POST['autofollow']));
+  }
+  if(isset($_POST['addpeer']) || isset($_POST['blacklistpeer']))
+  {
+    $peer=mysqli_real_escape_string($db, $_POST['newpeer']);
+    $blacklist=(isset($_POST['blacklistpeer'])?'1':'0');
+    mysqli_query($db, 'delete from peers where domain="'.$peer.'"');
+    mysqli_query($db, 'insert into peers(domain, blacklist) values("'.$peer.'", '.$blacklist.')');
+  }
+  if(isset($_POST['deletepeer']))
+  {
+    $peer=mysqli_real_escape_string($db, $_POST['deletepeer']);
+    mysqli_query($db, 'delete from peers where domain="'.$peer.'"');
+  }
+}
+
+// Load current
+$peers='';
+$res=mysqli_query($db, 'select domain, blacklist from peers order by domain asc');
+while($row=mysqli_fetch_assoc($res))
+{
+  $domain=htmlentities($row['domain']);
+  if($row['blacklist']){$domain='<span class="blacklist">'.$domain.'</span>';}
+  $peers.=$domain.'<button name="deletepeer" value="'.htmlentities($row['domain']).'">X</button><br />';
+}
+$autofollowcheck=(getoption('autofollow')?' checked':'');
+?>
+<form method="post">
+  <?=nonce()?>
+  <h2><?=_('Options')?></h2>
+  <label><input type="checkbox" name="autofollow"<?=$autofollowcheck?> />Automatically follow peers</label><br />
+  <input type="submit" name="options" value="<?=_('Save')?>" />
+</form>
+<form method="post">
+<h2><?=_('Peers')?></h2>
+<?=$peers?>
+  <input type="text" name="newpeer" placeholder="<?=_('domain.tld')?>" /><button name="addpeer"><?=_('Add peer')?></button><button name="blacklistpeer" title="<?=_('Don\'t autofollow this peer')?>"><?=_('Add peer to blacklist')?></button>
+</form>
diff --git a/admin_filetypes.php b/admin_filetypes.php
new file mode 100644
index 0000000..c30a514
--- /dev/null
+++ b/admin_filetypes.php
@@ -0,0 +1,69 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+include_once('nonce.php');
+if(!isset($_SESSION['id'])){die(_('Insufficient privileges'));}
+if(!($privileges&PRIV_FILETYPES)){die(_('Insufficient privileges'));}
+if(checknonce()) // Save changes
+{
+  if(isset($_POST['action']) && $_POST['action']=='newfiletype')
+  {
+    $extension=mysqli_real_escape_string($db, $_POST['newextension']);
+    $mimetype=mysqli_real_escape_string($db, $_POST['newmimetype']);
+    mysqli_query($db, 'insert into filetypes(extension, mimetype) values("'.$extension.'", "'.$mimetype.'")');
+  }
+  if(isset($_POST['removefiletype']))
+  {
+    $extension=mysqli_real_escape_string($db, $_POST['removefiletype']);
+    mysqli_query($db, 'delete from filetypes where extension="'.$extension.'"');
+  }
+}
+
+// Load current
+$filetypes='';
+$res=mysqli_query($db, 'select extension, mimetype from filetypes order by extension asc');
+while($row=mysqli_fetch_assoc($res))
+{
+  $extension=htmlentities($row['extension']);
+  $mimetype=htmlentities($row['mimetype']);
+  $filetypes.='<tr>';
+  $filetypes.='  <td>'.$extension.'</td>';
+  $filetypes.='  <td>'.$mimetype.'</td>';
+  $filetypes.='  <td><button name="removefiletype" value="'.$extension.'">X</button></td>';
+  $filetypes.='</tr>';
+}
+?>
+<h1><?=_('Filetypes')?></h1>
+<p><?=('This list serves a dual purpose of providing MIME types and controlling which files can be uploaded')?></p>
+<form method="post"><?=nonce()?>
+  <table>
+    <tr>
+      <th><?=_('Filename extension')?></th>
+      <th><?=_('MIME type')?></th>
+      <th></th>
+    </tr>
+    <?=$filetypes?>
+  </table>
+</form>
+<form method="post"><?=nonce()?>
+  <?=_('Filename extension')?>: <input type="text" name="newextension" /><br />
+  <?=_('MIME type')?>: <input type="text" name="newmimetype" /><br />
+  <button name="action" value="newfiletype"><?=_('Add')?></button>
+</form>
diff --git a/admin_licenses.php b/admin_licenses.php
new file mode 100644
index 0000000..c80b20b
--- /dev/null
+++ b/admin_licenses.php
@@ -0,0 +1,90 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+include_once('nonce.php');
+if(!isset($_SESSION['id'])){die(_('Insufficient privileges'));}
+if(!($privileges&PRIV_LICENSES)){die(_('Insufficient privileges'));}
+if(checknonce()) // Save changes
+{
+  if(isset($_POST['action']) && $_POST['action']=='newlicense')
+  {
+    $name=mysqli_real_escape_string($db, $_POST['newname']);
+    $simple=mysqli_real_escape_string($db, $_POST['newsimple']);
+    $full=mysqli_real_escape_string($db, $_POST['newfull']);
+    if(!mysqli_query($db, 'insert into licenses(name, simple, full, removed, defaultlicense) values("'.$name.'", "'.$simple.'", "'.$full.'", false, false)'))
+    {
+      mysqli_query($db, 'update licenses set simple="'.$simple.'", full="'.$full.'", removed=false, defaultlicense=false where name="'.$name.'" and removed');
+    }
+  }
+  if(isset($_POST['removelicense']))
+  {
+    $name=mysqli_real_escape_string($db, $_POST['removelicense']);
+    mysqli_query($db, 'update licenses set removed=true where name="'.$name.'"');
+  }
+  if(isset($_POST['defaultlicense']))
+  {
+    $name=mysqli_real_escape_string($db, $_POST['defaultlicense']);
+    mysqli_query($db, 'update licenses set defaultlicense=false where name!="'.$name.'"');
+    mysqli_query($db, 'update licenses set defaultlicense=true where name="'.$name.'"');
+  }
+}
+
+// Load current
+$licenses='';
+$res=mysqli_query($db, 'select name, simple, full, defaultlicense from licenses where !removed order by name asc');
+while($row=mysqli_fetch_assoc($res))
+{
+  $name=htmlentities($row['name']);
+  $simple=htmlentities($row['simple']);
+  $full=htmlentities($row['full']);
+  $licenses.='<tr>';
+  $licenses.='  <td>'.$name.'</td>';
+  $licenses.='  <td><div class="scrolltext">'.$simple.'</div></td>';
+  $licenses.='  <td><div class="scrolltext">'.$full.'</div></td>';
+  $licenses.='  <td>';
+  $licenses.='    <button name="removelicense" value="'.$name.'">X</button>';
+  if(!$row['defaultlicense'])
+  {
+    $licenses.='  <button name="defaultlicense" value="'.$name.'">'._('Make default').'</button>';
+  }
+  $licenses.='  </td>';
+  $licenses.='</tr>';
+}
+?>
+<h1><?=_('Licenses')?></h1>
+<form method="post"><?=nonce()?>
+  <table>
+    <tr>
+      <th><?=_('Name')?></th>
+      <th><?=_('Simple')?></th>
+      <th><?=_('Full (or link to full)')?></th>
+      <th></th>
+    </tr>
+    <?=$licenses?>
+  </table>
+</form>
+<form method="post"><?=nonce()?>
+  <?=_('Name')?>: <input type="text" name="newname" /><br />
+  <?=_('Simplified terms')?>:<br />
+  <textarea name="newsimple"></textarea><br />
+  <?=_('Full license text (or link)')?>:<br />
+  <textarea name="newfull"></textarea><br />
+  <button name="action" value="newlicense"><?=_('Add')?></button>
+</form>
diff --git a/admin_moderate.php b/admin_moderate.php
new file mode 100644
index 0000000..9d8e4d6
--- /dev/null
+++ b/admin_moderate.php
@@ -0,0 +1,118 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+include_once('nonce.php');
+if(!isset($_SESSION['id'])){die(_('Insufficient privileges'));}
+if(!($privileges&PRIV_MODERATE)){die(_('Insufficient privileges'));}
+
+// Report management
+if(isset($_POST['report']) && isset($_POST['action']) && checknonce())
+{
+  $report=(int)$_POST['report'];
+  $res=mysqli_query($db, 'select target, reason from reports where id='.$report);
+  $row=mysqli_fetch_assoc($res);
+  if(!$row){die('<div class="error"><h1>Report not found</h1></div>');}
+  $target=$row['target'];
+  $reason=$row['reason'];
+  $action='';
+  switch($_POST['action'])
+  {
+    case 'deletething':
+      if(substr($target,0,6)!='thing/' || !is_numeric(substr($target,6))){die('<div class="error"><h1>Not a thing</h1></div>');}
+      $id=(int)substr($target,6);
+      // Non-destructive removal
+      mysqli_query($db, 'update things set removed=true where thingid='.$id);
+      $action='deleted thing';
+      break;
+    case 'ban':
+      // Track down user
+      if(substr($target,0,6)!='thing/' || !is_numeric(substr($target,6))){die('<div class="error"><h1>Not a thing</h1></div>');} // TODO: Handle comments
+      $id=(int)substr($target,6);
+      $res=mysqli_query($db, 'select user from things where id='.$id);
+      $user=(int)mysqli_fetch_row($res)[0];
+      mysqli_query($db, 'update users set status='.ACCOUNT_BANNED.' where id='.$user);
+      $action='banned user <...>'.db_getuser($user).'</a>';
+      break;
+    case 'deletereport':
+// TODO: Modlog report deletion too? seems excessive but could be useful
+      mysqli_query($db, 'delete from reports where id='.$report);
+      break;
+  }
+  if($action!='') // Log action
+  {
+    $action=mysqli_real_escape_string($db, $action.' for report "'.$reason.'"');
+    $timestamp=mysqli_real_escape_string($db, date('Y-m-d H:i:s'));
+    $target=mysqli_real_escape_string($db, $target);
+    mysqli_query($db, 'insert into moderationlog(user, timestamp, action, target) values('.(int)$_SESSION['id'].', "'.$timestamp.'", "'.$action.'", "'.$target.'")');
+  }
+}
+if(isset($_POST['unban']) && checknonce())
+{
+  $user=mysqli_real_escape_string($db, $_POST['unban']);
+  $timestamp=mysqli_real_escape_string($db, date('Y-m-d H:i:s'));
+  mysqli_query($db, 'update users set status='.ACCOUNT_ACTIVE.' where name="'.$user.'"');
+  mysqli_query($db, 'insert into moderationlog(user, timestamp, action, target) values('.(int)$_SESSION['id'].', "'.$timestamp.'", "unbanned user", "user/'.$user.'")');
+}
+
+// Gather moderation log entries
+$modlog='';
+$res=mysqli_query($db, 'select user, timestamp, action, target from moderationlog order by timestamp desc limit 20'); // TODO: Paging?
+while($row=mysqli_fetch_assoc($res))
+{
+// TODO: Figure out timezones
+  $modlog.=$row['timestamp'].' <...>'.db_getuser($row['user']).'</a> '.$row['action'].' on <...>'.$row['target'].'</a><br />';
+}
+if(mysqli_num_rows($res)==20){$modlog.='TODO: Paging?<br />';}
+
+// Gather reports
+$reports='';
+$res=mysqli_query($db, 'select id, user, target, reason, timestamp from reports order by timestamp');
+while($row=mysqli_fetch_assoc($res))
+{
+  $id=$row['id'];
+  $user=htmlentities($row['user']);
+  $subject=htmlentities($row['target']);
+  $reason=htmlentities($row['reason']);
+  $timestamp=htmlentities($row['timestamp']);
+  $reports.='<tr><td><a href="'.BASEURL.'/user/'.$user.'">'.$user.'</a></td>';
+  $reports.='<td><...>'.$subject.'</a></td>';
+  $reports.='<td>'.$reason.'</td>';
+  $reports.='<td>'.$timestamp.'</td>';
+  $reports.='<td><form method="post">'.nonce();
+  $reports.='<input type="hidden" name="report" value="'.$id.'" />';
+  $reports.='<button name="action" value="deletething">'._('Delete thing').'</button>';
+  $reports.='<button name="action" value="ban">'._('Ban user').'</button>';
+  $reports.='<button name="action" value="deletereport">X</button>';
+  $reports.='</form></td></tr>';
+}
+?>
+<h1><?=_('Reports')?></h1>
+<table>
+  <tr>
+    <th><?=_('Reported by')?></th>
+    <th><?=_('Subject')?></th>
+    <th><?=_('Reason')?></th>
+    <th><?=_('Timestamp')?></th>
+    <th></th>
+  </tr>
+  <?=$reports?>
+</table>
+<h1><?=_('Moderation log')?></h1>
+<?=$modlog?>
diff --git a/admin_privileges.php b/admin_privileges.php
new file mode 100644
index 0000000..501f8a8
--- /dev/null
+++ b/admin_privileges.php
@@ -0,0 +1,81 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+include_once('nonce.php');
+if(!isset($_SESSION['id'])){die(_('Insufficient privileges'));}
+if(!($privileges&PRIV_PRIVILEGES)){die(_('Insufficient privileges'));}
+
+if(checknonce()) // Save changes
+{
+  $priv=0;
+  foreach($_POST['privileges'] as $p){$priv+=$p;}
+  $q='';
+  if(isset($_POST['addprivileges']) && $_POST['addprivileges']!='')
+  {
+    $user=mysqli_real_escape_string($db, $_POST['addprivileges']);
+    $q.='name="'.$user.'"';
+  }
+  elseif(isset($_POST['editprivileges'])){$q='id='.(int)$_POST['editprivileges'];}
+  if($q!='')
+  {
+    mysqli_query($db, 'update users set privileges='.(int)$priv.' where '.$q);
+  }
+}
+
+// Load current
+$users='';
+$res=mysqli_query($db, 'select id, name, displayname, privileges from users where privileges>0 order by privileges desc');
+while($row=mysqli_fetch_assoc($res))
+{
+  $name=htmlentities($row['name']);
+  $displayname=htmlentities($row['displayname']);
+  $users.='<tr>';
+  $users.='  <td><a href="'.BASEURL.'/user/'.$name.'@'.DOMAIN.'" title="'.$name.'@'.DOMAIN.'">'.$displayname.'</a></td>';
+  $users.='  <td><form method="post">'.nonce();
+  foreach(PRIV_NAMES as $n=>$priv)
+  {
+    $checked=(($row['privileges']&(2**$n))?' checked':'');
+    $users.='<label><input type="checkbox" name="privileges[]" value="'.(2**$n).'"'.$checked.' />';
+    $users.=$priv.'</label><br />';
+  }
+  $users.='  <button name="editprivileges" value="'.$row['id'].'">'._('Save').'</button></form></td>';
+  $users.='</tr>';
+}
+// Gather privileges for new admins
+$privileges='';
+foreach(PRIV_NAMES as $n=>$priv)
+{
+  $privileges.='<label><input type="checkbox" name="privileges[]" value="'.(2**$n).'" />';
+  $privileges.=$priv.'</label><br />';
+}
+?>
+<h2><?=_('Privileges')?></h2>
+<table>
+  <tr>
+    <th><?=_('User')?></th>
+    <th><?=_('Privileges')?></th>
+  </tr>
+  <?=$users?>
+</table>
+<form method="post"><?=nonce()?>
+  <input type="text" name="addprivileges" placeholder="<?=_('Username')?>" /><br />
+  <?=$privileges?>
+  <button><?=('Save')?></button>
+</form>
diff --git a/config.php.sample b/config.php.sample
new file mode 100644
index 0000000..ab9eb9a
--- /dev/null
+++ b/config.php.sample
@@ -0,0 +1,24 @@
+<?php
+// Database settings
+define('DB_USER', ''); // Database username
+define('DB_PASS', ''); // Database password
+define('DB_NAME', ''); // Database name
+define('DB_HOST', 'localhost'); // Database host
+
+// General settings
+define('DOMAIN', ''); // Domain name
+define('NODENAME', 'Thingshare'); // Name of Thingshare instance
+define('BASEURL', ''); // Path from web root
+define('EMAIL', ''); // E-mail address for if visitors need to contact you
+define('HASH', 'sha512'); // Which hash to use for passwords and files
+define('TMPDIR', 'tmp'); // Directory to store temporary files
+
+// File storage settings (warning: this concerns finding already uploaded files, changes will need filesystem restructuring to retain previous uploads)
+define('HASHTREE_SECTION', 2); // How many characters each directory level should contain
+define('HASHTREE_LEVELS', 4); // How many levels to distribute the files over
+
+// Preview settings
+define('PREVIEW_RENDERMETHOD', 'povray'); // How to render previews of 3D models [povray, openscad (untested)]
+define('PREVIEW_COLOR', Array(0,255,0)); // Color of rendered models
+define('PREVIEW_SIZE', Array(240,240));
+?>
diff --git a/db.php b/db.php
new file mode 100644
index 0000000..1e031d4
--- /dev/null
+++ b/db.php
@@ -0,0 +1,152 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('config.php');
+define('PRIV_PRIVILEGES', 1); // Privilege of managing privileges
+define('PRIV_MODERATE', 2);   // Content moderation, deleting 'things' and comments, adding/removing tags on things, banning users. Reading reports
+define('PRIV_TAGS', 4);       // Managing tags (TODO)
+define('PRIV_FEDERATION', 8); // Control who to federate with (blacklists, auto)
+define('PRIV_FILETYPES', 16); // Manage filetypes
+define('PRIV_LICENSES', 32);  // Manage the license list
+
+define('PRIV_ALL', 63);       // Convenience macro for all privileges
+define('PRIV_NAMES', Array('Privilege of managing privileges',
+                           'Content moderation',
+                           'Tag management',
+                           'Federation',
+                           'Manage filetypes',
+                           'Manage the license list'));
+
+define('ACCOUNT_ACTIVE', 0);
+define('ACCOUNT_BANNED', 1);
+define('ACCOUNT_EMAILUNVERIFIED', 2);
+
+$db=mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
+
+function getoption($name, $default=false)
+{
+  global $db;
+  $name=mysqli_real_escape_string($db, $name);
+  $res=mysqli_query($db, 'select value from options where name="'.$name.'"');
+  if($res=mysqli_fetch_row($res))
+  {
+    return $res[0];
+  }
+  return $default;
+}
+
+function setoption($name, $value)
+{
+  global $db;
+  if($value===false){$value='0';}
+  elseif($value===true){$value='1';}
+  $name=mysqli_real_escape_string($db, $name);
+  $value=mysqli_real_escape_string($db, $value);
+  mysqli_query($db, 'update options set value="'.$value.'" where name="'.$name.'"');
+  if(substr_count(mysqli_info($db), 'Rows matched: 0')) // None to update, insert new
+  {
+    mysqli_query($db, 'insert into options(name, value) values("'.$name.'", "'.$value.'")');
+  }
+}
+
+function db_create_tables()
+{
+  global $db;
+  mysqli_query($db, 'create table users(
+    id integer primary key auto_increment,
+    name varchar(64) unique,
+    salt text,
+    password text,
+    email text,
+    displayname text,
+    profile text,
+    privileges integer,
+    status integer);');
+  mysqli_query($db, 'create table things(
+    id integer primary key auto_increment,
+    thingid integer,
+    user integer,
+    name text,
+    description text,
+    posted datetime,
+    latest boolean,
+    removed boolean,
+    license text);');
+  mysqli_query($db, 'create table files(
+    id integer primary key auto_increment,
+    thing integer,
+    name text,
+    hash text);');
+  mysqli_query($db, 'create table options(name text, value text);');
+  mysqli_query($db, 'create table peers(domain text, blacklist boolean);');
+  mysqli_query($db, 'create table cooldown(domain text, end datetime);');
+  mysqli_query($db, 'create table rpccache(hash varchar(500) primary key, timestamp datetime, cache text);');
+  mysqli_query($db, 'create table reports(
+    id integer primary key auto_increment,
+    user text,
+    target text,
+    reason text,
+    timestamp datetime);');
+  mysqli_query($db, 'create table moderationlog(user integer, timestamp datetime, action text, target text);');
+  mysqli_query($db, 'create table filetypes(extension varchar(500) primary key, mimetype text);');
+  mysqli_query($db, 'create table licenses(name varchar(500) primary key, simple text, full text, removed boolean, defaultlicense boolean);'); // Long 'defaultlicense' because 'default' is a keyword
+  mysqli_query($db, 'create table messages(id integer primary key auto_increment,
+    user integer,
+    recipient text,
+    sender text,
+    sent datetime,
+    chain integer,
+    subject text,
+    message text,
+    msgread boolean,
+    latest boolean);');
+  mysqli_query($db, 'create table userblocks(user integer, blocked text);');
+}
+
+function db_getuser($id)
+{
+  // Small cache in case the same user's name needs to be resolved multiple times on the same page
+  static $cache=Array();
+  if(isset($cache[$id])){return $cache[$id];}
+  // Fetch from DB and cache for later
+  global $db;
+  $res=mysqli_query($db, 'select name from users where id='.(int)$id);
+  $res=mysqli_fetch_row($res);
+  $cache[$id]=$res[0];
+  return $res[0];
+}
+
+function db_getmimetype($ext)
+{
+  global $db;
+  $dot=strrpos($ext, '.');
+  if($dot!==false){$ext=substr($ext, $dot+1);}
+  $ext=mysqli_real_escape_string($db, strtolower($ext));
+  // Small cache in case the same extension's MIME type needs to be resolved multiple times on the same page
+  static $cache=Array();
+  if(isset($cache[$ext])){return $cache[$ext];}
+  $res=mysqli_query($db, 'select mimetype from filetypes where extension="'.$ext.'"');
+  if($res=mysqli_fetch_row($res))
+  {
+    $cache[$ext]=$res[0];
+    return $res[0];
+  }
+  return false;
+}
+?>
diff --git a/editprofile.php b/editprofile.php
new file mode 100644
index 0000000..589838c
--- /dev/null
+++ b/editprofile.php
@@ -0,0 +1,46 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('config.php');
+if(isset($_COOKIE['PHPSESSID'])){session_start();}
+if(!isset($_SESSION['id'])){header('Location: '.BASEURL.'/login?returnto='.urlencode($_SERVER['REQUEST_URI']));}
+include_once('db.php');
+include_once('nonce.php');
+if(isset($_POST['displayname']) && isset($_POST['profile']) && checknonce())
+{
+  // Save and redirect back to profile
+  $displayname=mysqli_real_escape_string($db, $_POST['displayname']);
+  $profile=mysqli_real_escape_string($db, $_POST['profile']);
+  mysqli_query($db, 'update users set displayname="'.$displayname.'", profile="'.$profile.'" where id='.(int)$_SESSION['id']);
+  header('Location: '.BASEURL.'/user/'.$_SESSION['name'].'@'.DOMAIN);
+}
+include_once('head.php');
+$res=mysqli_query($db, 'select displayname, profile from users where id='.(int)$_SESSION['id']);
+$res=mysqli_fetch_assoc($res);
+// TODO: Profile picture?
+?>
+<script src="<?=BASEURL?>/mdjs/mdjs.js"></script>
+<form method="post">
+  <?=nonce()?>
+  Display name: <input type="text" name="displayname" value="<?=$res['displayname']?>" /><br />
+  Profile:<br />
+  <textarea name="profile" rows="15" style="width:100%;" onchange="document.getElementById('mdpreview').innerHTML='Markdown preview:<br />'+Mdjs.md2html(this.value);" onkeyup="this.onchange();"><?=$res['profile']?></textarea><br />
+  <div id="mdpreview"></div>
+  <button><?=_('Save')?></button>
+</form>
diff --git a/editthing.php b/editthing.php
new file mode 100644
index 0000000..a23e145
--- /dev/null
+++ b/editthing.php
@@ -0,0 +1,220 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('config.php');
+if(isset($_COOKIE['PHPSESSID'])){session_start();}
+if(!isset($_SESSION['id'])){header('Location: '.BASEURL.'/login?returnto='.urlencode($_SERVER['REQUEST_URI']));}
+include_once('db.php');
+include_once('nonce.php');
+include_once('files.php');
+$id=$path[2];
+$error='';
+function insertfile($thingid, $name, $hash)
+{
+  global $db;
+  $res=mysqli_query($db, 'select id from files where thing='.$thingid.', name="'.$name.'"');
+  if($id=mysqli_fetch_row($res)) // Handle name collisions (overwrite DB entry by updating the hash)
+  {
+    $id=(int)$id[0];
+    mysqli_query($db, 'update files set hash="'.$hash.'" where id='.$id);
+  }else{
+    mysqli_query($db, 'insert into files(thing, name, hash) values('.$thingid.', "'.$name.'", "'.$hash.'")');
+  }
+}
+if(isset($_POST['name']) && isset($_POST['description']) && checknonce())
+{
+// TODO: Also do as many of these checks as possible in javascript onsubmit to avoid losing file selections (and wasting time and bandwidth uploading files only to get errors)
+  // Checks
+  if($id!='new') // Make sure $id belongs to us (or is 'new')
+  {
+    $res=mysqli_query($db, 'select user, removed from things where id='.(int)$id);
+    $res=mysqli_fetch_row($res);
+    if($res[0]!=$_SESSION['id']){$error=_('Ownership error');}
+    if($res[1]){$error=_('No such thing');}
+  }
+  if($_POST['name']==''){$error=_('A thing needs a name');}
+  $filecount=0;
+  for($i=0; $i<count($_FILES['files']['error']); ++$i)
+  {
+    if($_FILES['files']['error'][$i]!=0){continue;}
+    if(db_getmimetype($_FILES['files']['name'][$i])===false)
+    {
+      $list=Array();
+      $res=mysqli_query($db, 'select extension from filetypes order by extension');
+      while($row=mysqli_fetch_row($res)){$list[]=$row[0];}
+      $error=$_FILES['files']['name'][$i].': '._('File type not allowed. Allowed file types: ').implode(', ', $list);
+      continue;
+    }
+    ++$filecount;
+  }
+  if($filecount==0 && count($_POST['oldfiles'])<1){$error=_('A thing is not a thing without any files');}
+  if($error=='') // No errors, commit to database
+  {
+    if($id!='new')
+    {
+      mysqli_query($db, 'update things set latest=false where thingid='.(int)$id);
+    }
+    $name=mysqli_real_escape_string($db, $_POST['name']);
+    $description=mysqli_real_escape_string($db, $_POST['description']);
+    $license=mysqli_real_escape_string($db, $_POST['license']);
+    $timestamp=date('Y-m-d H:i:s');
+    mysqli_query($db, 'insert into things(thingid, user, name, description, posted, latest, removed, license) values('.(int)$id.', '.(int)$_SESSION['id'].', "'.$name.'", "'.$description.'", "'.$timestamp.'", true, false, "'.$license.'")');
+    $thingid=(int)mysqli_insert_id($db);
+    if($id=='new')
+    {
+      mysqli_query($db, 'update things set thingid=LAST_INSERT_ID() where id=LAST_INSERT_ID()');
+      $id=$thingid;
+    }
+    // Handle old files
+    for($i=0; $i<count($_POST['oldfiles']); ++$i)
+    {
+      $name=mysqli_real_escape_string($db, $_POST['oldfilenames'][$i]);
+      $hash=mysqli_real_escape_string($db, $_POST['oldfiles'][$i]);
+      $filepath=getfilepath($_POST['oldfiles'][$i], true);
+      if(substr_count($hash, '.')){die('Misformed hash detected');}
+      if(substr_count($hash, '/')){die('Misformed hash detected');}
+      if(!file_exists($filepath)){die('Misformed hash detected');}
+      insertfile($thingid, $name, $hash);
+    }
+    // Save the files
+    for($i=0; $i<count($_FILES['files']['name']); ++$i)
+    {
+      if($_FILES['files']['error'][$i]!=0)
+      {
+        if($_FILES['files']['error'][$i]!=UPLOAD_ERR_NO_FILE){print('Failed to upload '.$_FILES['files']['name'][$i].', error code '.$_FILES['files']['error'][$i]."<br />\n");}
+        continue;
+      }
+      $hash=HASH.':'.hash_file(HASH, $_FILES['files']['tmp_name'][$i]);
+      $filepath=getfilepath($hash, true);
+      mkdir(dirname($filepath), 0755, true); // Make sure the directories exist
+      if(!move_uploaded_file($_FILES['files']['tmp_name'][$i], $filepath)){print('Failed to upload '.$_FILES['files']['name'][$i].", move_uploaded_file failed<br />\n"); continue;}
+      $name=mysqli_real_escape_string($db, $_FILES['files']['name'][$i]);
+      insertfile($thingid, $name, $hash);
+    }
+    header('Location: '.BASEURL.'/thing/'.$id.'@'.DOMAIN);
+    system('php genpreviews.php > /dev/null &'); // Launch preview generation in the background
+    exit();
+  }
+}
+include_once('head.php');
+$name='';
+$description='';
+$files='';
+$license='';
+if($id!='new') // Load from DB when editing a preexisting thing
+{
+  $res=mysqli_query($db, 'select id, name, description, license from things where thingid='.(int)$id.' and latest');
+  $res=mysqli_fetch_assoc($res);
+  $name=$res['name'];
+  $description=$res['description'];
+  $thingid=$res['id'];
+  $license=$res['license'];
+  // Gather files
+  $res=mysqli_query($db, 'select hash, name from files where thing='.(int)$thingid);
+  while($row=mysqli_fetch_assoc($res))
+  {
+    $files.='<div class="fileinput"><input type="hidden" name="oldfiles[]" value="'.$row['hash'].'" /><input type="text" name="oldfilenames[]" value="'.htmlentities($row['name']).'" /><button onclick="this.parentNode.remove(); return false;">X</button></div>'."\n";
+  }
+}
+// If saving was attempted, retain changes
+if(isset($_POST['name'])){$name=$_POST['name'];}
+if(isset($_POST['description'])){$description=$_POST['description'];}
+if(isset($_POST['license'])){$license=$_POST['license'];}
+
+// Gather license options
+$licenses='';
+$res=mysqli_query($db, 'select name, simple, defaultlicense from licenses where !removed');
+while($row=mysqli_fetch_assoc($res))
+{
+  $lname=htmlentities($row['name']);
+  $simple=htmlentities($row['simple']);
+  if($license=='' && $row['defaultlicense']){$license=$lname;}
+  $selected=(($lname==$license)?' selected':'');
+  $licenses.='<option value="'.$lname.'" title="'.$simple.'"'.$selected.'>'.$lname.'</option>';
+}
+$selected=(($license=='other')?' selected':'');
+$licenses.='<option value="other"'.$selected.'>'._('Other (see description)').'</option>';
+
+$maxsize=ini_get('upload_max_filesize');
+// Translate to bytes for the MAX_FILE_SIZE input
+switch(strtoupper(substr($maxsize,-1)))
+{
+  case 'Y': $maxsize=(int)$maxsize*1024;
+  case 'Z': $maxsize=(int)$maxsize*1024;
+  case 'E': $maxsize=(int)$maxsize*1024;
+  case 'P': $maxsize=(int)$maxsize*1024;
+  case 'T': $maxsize=(int)$maxsize*1024;
+  case 'G': $maxsize=(int)$maxsize*1024;
+  case 'M': $maxsize=(int)$maxsize*1024;
+  case 'K': $maxsize=(int)$maxsize*1024;
+}
+if($error!=''){$error='<div class="error">'.$error.'</div>';}
+?>
+<script src="<?=BASEURL?>/mdjs/mdjs.js"></script>
+<script>
+<!--
+function morefiles(prev)
+{
+  var oldentry=prev.parentNode;
+  var list=oldentry.parentNode;
+  var entry=document.createElement('div');
+  entry.className='fileinput';
+  var file=document.createElement('input');
+  file.type='file';
+  file.name='files[]';
+  file.onchange=function(){morefiles(this);};
+  entry.appendChild(file);
+  list.appendChild(entry);
+  prev.onchange=false; // Don't add more fields when changing file selection on an old entry
+// TODO: Rename button? Order, etc.
+  // Add 'remove' button
+  var button=document.createElement('button');
+  button.appendChild(document.createTextNode('X'));
+  button.onclick=function(){this.parentNode.remove(); return false;};
+  oldentry.appendChild(button);
+}
+// -->
+</script>
+<?=$error?>
+<form enctype="multipart/form-data" method="post">
+  <?=nonce()?>
+  <input type="hidden" name="MAX_FILE_SIZE" value="<?=$maxsize?>" /><!-- This limit is taken from the upload_max_filesize value in php.ini -->
+  <?=_('Name:')?> <input type="text" name="name" value="<?=htmlentities($name)?>" /><br />
+  <?=_('Description:')?><br />
+  <textarea name="description" rows="15" style="width:100%;" onchange="document.getElementById('mdpreview').innerHTML='Markdown preview:<br />'+Mdjs.md2html(this.value);" onkeyup="this.onchange();"><?=htmlentities($description)?></textarea><br />
+  <div id="mdpreview"></div>
+  <div class="paragraph">
+    <?=_('License')?>:
+    <select name="license">
+      <?=$licenses?>
+    </select>
+  </div>
+  <div class="paragraph">
+    <?=_('Files:')?><br />
+    <?=$files?>
+    <div class="fileinput"><input type="file" name="files[]" onchange="morefiles(this);" /></div>
+    <noscript>
+      <div class="fileinput"><input type="file" name="files[]" onchange="morefiles(this);" /></div>
+      <div class="fileinput"><input type="file" name="files[]" onchange="morefiles(this);" /></div>
+      <div class="fileinput"><input type="file" name="files[]" onchange="morefiles(this);" /></div>
+      <div class="fileinput"><input type="file" name="files[]" onchange="morefiles(this);" /></div>
+    </noscript>
+  </div>
+  <button><?=_('Save')?></button>
+</form>
diff --git a/files.php b/files.php
new file mode 100644
index 0000000..c377f9b
--- /dev/null
+++ b/files.php
@@ -0,0 +1,46 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('config.php');
+function getfilepath($hash, $serverside=false)
+{
+  $hash=explode(':', $hash);
+  $path='files/'.$hash[0];
+  $hash=$hash[1];
+  if(!$serverside){$path=BASEURL.'/'.$path;}
+  for($i=0; $i<HASHTREE_LEVELS; ++$i)
+  {
+    $path.='/'.substr($hash, 0, HASHTREE_SECTION);
+    $hash=substr($hash, HASHTREE_SECTION);
+  }
+  $path.='/'.$hash;
+  return $path;
+}
+function getpreview($name, $hash)
+{
+  $file=getfilepath($hash, true);
+  if(file_exists($file.'.png')){return BASEURL.'/'.$file.'.png';}
+  // No actual preview found, get a filetype icon
+  $dot=strrpos($name, '.');
+  $filetype=strtolower(substr($name, $dot+1));
+  if(file_exists('icons/'.$filetype.'.svg')){return BASEURL.'/icons/'.$filetype.'.svg';}
+  if(file_exists('icons/'.$filetype.'.png')){return BASEURL.'/icons/'.$filetype.'.png';}
+  return BASEURL.'/icons/default.svg';
+}
+?>
diff --git a/foot.php b/foot.php
new file mode 100644
index 0000000..763557a
--- /dev/null
+++ b/foot.php
@@ -0,0 +1,12 @@
+  </div>
+  <div class="footer">
+    <div class="c2">
+      <h4>About</h4>
+      Thingshare is a federated system for sharing data for home manufacturing. For more information see <a href="https://thingshare.ion.nu/">thingshare.ion.nu</a>
+    </div><div class="c2">
+      <h4>Contact</h4>
+      E-mail address: <a href="mailto:<?=EMAIL?>"><?=EMAIL?></a>
+    </div>
+  </div>
+</body>
+</html>
diff --git a/genpreviews.php b/genpreviews.php
new file mode 100755
index 0000000..4474627
--- /dev/null
+++ b/genpreviews.php
@@ -0,0 +1,155 @@
+#!/usr/bin/env php
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+if(PHP_SAPI!=='cli'){die('<br />Commandline only!');}
+// Launch in BG with system('php genpreviews.php > /dev/null &')
+chdir(dirname($_SERVER['SCRIPT_FILENAME']));
+// Make sure only one instance is running at a time
+$lock=fopen('files', 'r');
+if(!flock($lock, LOCK_EX|LOCK_NB)){die("Lock failed");}
+include_once('db.php');
+include_once('config.php');
+include_once('files.php');
+mkdir(TMPDIR, 755);
+$res=mysqli_query($db, 'select distinct lower(substring_index(name,".",-1)) as type, hash from files');
+while($row=mysqli_fetch_assoc($res))
+{
+  $file=getfilepath($row['hash'], true);
+  // Preview image
+  if(file_exists($file.'.png')){continue;}
+  $img=false;
+  switch($row['type'])
+  {
+    // Scale down images to more suitable sizes
+    case 'png': if(!$img){$img=imagecreatefrompng($file);}
+    case 'jpg':
+    case 'jpeg': if(!$img){$img=imagecreatefromjpeg($file);}
+    case 'gif': if(!$img){$img=imagecreatefromgif($file);}
+      if(!$img){break;} // Failed to load image
+      $x=imagesx($img);
+      $y=imagesy($img);
+      if($x/PREVIEW_SIZE[0]<$y/PREVIEW_SIZE[1]) // Maintain aspect ratio
+      {
+        $ox=$x*PREVIEW_SIZE[1]/$y;
+        $oy=PREVIEW_SIZE[1];
+      }else{
+        $ox=PREVIEW_SIZE[0];
+        $oy=$y*PREVIEW_SIZE[0]/$x;
+      }
+      $out=imagecreatetruecolor($ox, $oy);
+      imagecopyresampled($out, $img, 0, 0, 0, 0, $ox, $oy, $x, $y);
+      imagepng($out, $file.'.png');
+      imagedestroy($img);
+      imagedestroy($out);
+      break;
+    case 'blend':
+    case '3mf':
+    case 'x3d':
+    case 'obj':
+    case 'stl':
+      // Convert to STL for the next step (even for stl for bin->ascii)
+      copy($file, TMPDIR.'/thingsharepreview_orig.'.$row['type']);
+      system('assimp export '.escapeshellarg(TMPDIR.'/thingsharepreview_orig.'.$row['type']).' '.escapeshellarg(TMPDIR.'/thingsharepreview.stl'));
+      unlink(TMPDIR.'/thingsharepreview_orig.'.$row['type']);
+      switch(PREVIEW_RENDERMETHOD)
+      {
+        case 'povray':
+          // Translate STL to Povray (could have used stl2pov for this but it required a lot of tweaking of the output and didn't give us access to useful data like min/max vertex positions)
+          $min=Array(false,false,false);
+          $max=Array(false,false,false);
+          $in=fopen(TMPDIR.'/thingsharepreview.stl', 'r');
+          $out=fopen(TMPDIR.'/thingsharepreview.pov', 'w');
+          while($line=fgets($in))
+          {
+            if(substr(trim($line), 0, 7)=='vertex ')
+            {
+              $vertex=array_slice(explode(' ', trim($line)), 1);
+              $facet[]=$vertex;
+              for($i=0; $i<3; ++$i)
+              {
+                if($min[$i]===false || $vertex[$i]<$min[$i]){$min[$i]=$vertex[$i];}
+                if($max[$i]===false || $vertex[$i]>$max[$i]){$max[$i]=$vertex[$i];}
+              }
+            }
+            elseif(substr(trim($line), 0, 6)=='facet ')
+            {
+              $facet=Array(); // Start empty
+            }
+            elseif(trim($line)=='endfacet')
+            {
+              if(count($facet)==3){fwrite($out, "  triangle {\n");}
+              elseif(count($facet)==4){fwrite($out, "  square {\n");}
+              foreach($facet as $vertex)
+              {
+                fwrite($out, '    <'.$vertex[0].','.$vertex[1].','.$vertex[2].">\n");
+              }
+              fwrite($out, "  }\n");
+            }
+            elseif(substr(trim($line), 0, 6)=='solid ')
+            {
+              fwrite($out, "mesh {\n");
+            }
+          }
+          fclose($f);
+          $dist=0;
+          $maxdist=0;
+          $avg=Array();
+          for($i=0; $i<3; ++$i)
+          {
+            $avg[$i]=($max[$i]+$min[$i])/2;
+            if($max[$i]-$min[$i]>$maxdist){$maxdist=$max[$i]-$min[$i];}
+            $dist+=($max[$i]-$min[$i])/3;
+          }
+          $dist=($dist+$maxdist)/2; // $dist and $maxdist worked great for different cases, averaging gives us decent enough results for all cases. TODO: An even more accurate method would likely be to convert each vertex coordinate to be in relation to the camera
+          fwrite($out, "  texture {\n");
+          fwrite($out, '    pigment { color rgb<'.(PREVIEW_COLOR[0]/255).','.(PREVIEW_COLOR[1]/255).','.(PREVIEW_COLOR[2]/255)."> }\n");
+          fwrite($out, "    finish { ambient 0.2 diffuse 0.7 }\n");
+          fwrite($out, "  }\n}\n");
+          // Scene setup
+          fwrite($out, "global_settings { ambient_light rgb<1, 1, 1> }\n");
+          fwrite($out, "background { color rgb<1,1,1> }\n"); // TODO: Configurable background color?
+          fwrite($out, "camera {\n");
+          $dist/=1.65;
+          fwrite($out, '  location <'.($max[0]+$dist).','.($max[1]+$dist).','.($max[2]+$dist).">\n");
+          fwrite($out, '  look_at <'.$avg[0].','.$avg[1].','.$avg[2].">\n");
+          fwrite($out, '  right x*'.(PREVIEW_SIZE[0]/PREVIEW_SIZE[1])."\n");
+          fwrite($out, "  sky <0,0,1>\n}\n"); // Set Z vertical
+          fwrite($out, 'light_source { <'.($max[0]+$dist+10).','.($max[1]+$dist).','.($max[2]+$dist+20).'> color rgb<1, 1, 1> }'); // Light slightly offset from camera to distinguish corners better
+          // Render using Povray
+          $tmpfile=escapeshellarg(TMPDIR.'/thingsharepreview.pov');
+          system('povray +I'.$tmpfile.' +O'.escapeshellarg($file.'.png').' -D +P +W'.(int)PREVIEW_SIZE[0].' +H'.(int)PREVIEW_SIZE[1].' +A0.5');
+          unlink(TMPDIR.'/thingsharepreview.pov');
+          break;
+        case 'openscad': // TODO: Test this code (completely untested so far), looks like we need to rename the file for the import to identify it correctly
+          $c=sprintf('#%02x%02x%02x', PREVIEW_COLOR[0], PREVIEW_COLOR[1], PREVIEW_COLOR[2]);
+          copy($file, TMPDIR.'/thingsharepreview.'.$row['type']);
+          file_put_contents(TMPDIR.'/thingsharepreview.scad', 'color("'.$c.'")import("thingsharepreview.'.str_replace('"', '', $row['type']).'");');
+          system('openscad --imgsize '.(int)PREVIEW_SIZE[0].','.(int)PREVIEW_SIZE[1].' -o '.escapeshellarg($file.'.png').' '.escapeshellarg(TMPDIR.'/thingsharepreview.scad'));
+          unlink(TMPDIR.'/thingsharepreview.'.$row['type']);
+          unlink(TMPDIR.'/thingsharepreview.scad');
+          break;
+      }
+      unlink(TMPDIR.'/thingsharepreview.stl');
+      break;
+  }
+  // TODO: Preview 3D model (x3d)
+//  print($file.'.'.$row['type']."\n");
+}
+?>
diff --git a/head.php b/head.php
new file mode 100644
index 0000000..2225807
--- /dev/null
+++ b/head.php
@@ -0,0 +1,74 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('config.php');
+$menu=''; // Additional menu items depending on privileges/just being logged in
+if(isset($_COOKIE['PHPSESSID'])) // TODO: See if there's a better way to check if there is a session to resume
+{
+  session_start();
+  if(isset($_SESSION['id']))
+  {
+    include_once('db.php');
+    $res=mysqli_query($db, 'select privileges, status from users where id='.(int)$_SESSION['id']);
+    $res=mysqli_fetch_row($res);
+    if($res[1]==ACCOUNT_BANNED)
+    {
+      print('Banned'); // TODO: Put this nicely?
+      session_destroy();
+      exit();
+    }
+    $privileges=$res[0];
+    if($privileges>0){$menu.='<a href="'.BASEURL.'/admin">Administration</a>';}
+  }
+}
+$loginlink=BASEURL.'/login?returnto='.urlencode($_SERVER['REQUEST_URI']);
+$logoutlink=BASEURL.'/logout?returnto='.urlencode($_SERVER['REQUEST_URI']);
+$search=htmlentities(isset($_GET['q'])?$_GET['q']:'');
+?>
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <title><?=NODENAME?></title>
+  <link rel="stylesheet" href="<?=BASEURL?>/style.css" type="text/css" />
+</head>
+<body>
+  <div id="logo" title="Yes this needs a logo or something. Got any art skills?"></div>
+<!-- TODO: Responsive design -->
+  <nav>
+    <div id="menu">
+      <a href="<?=BASEURL?>/browse/new">Latest designs</a>
+      <?=$menu?>
+    </div>
+    <div id="user"><?php if(isset($_SESSION['name'])){ ?>
+      <!-- Link to user settings, messages -->
+      <a href="<?=BASEURL?>/user/<...>">My profile</a>
+      <a href="<?=$logoutlink?>">Log out</a>
+    <?php }else{ ?>
+      <a href="<?=$loginlink?>">Log in</a>
+      <a href="<?=BASEURL?>/register">Register</a>
+    <?php } ?>
+    </div>
+    <div id="search">
+      <form method="get" action="<?=BASEURL?>/search">
+        <input type="text" name="q" value="<?=$search?>" />
+        <button><img src="<?=BASEURL?>/icons/find.svg" onerror="this.src='<?=BASEURL?>/icons/find.png';" /></button>
+      </form>
+    </div>
+  </nav>
+  <div id="content">
diff --git a/icons/default.svg b/icons/default.svg
new file mode 100644
index 0000000..f7567ee
--- /dev/null
+++ b/icons/default.svg
@@ -0,0 +1 @@
+<?xml version="1.0" ?><svg height="48" id="svg8" version="1.1" viewBox="0 0 12.7 12.7" width="48" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:svg="http://www.w3.org/2000/svg"><defs id="defs2"><clipPath clipPathUnits="userSpaceOnUse" id="clipPath5343"><path d="m 3.0688351,285.55677 c -1.613568,1.19596 -2.5662181,3.08478 -2.56883509,5.09323 0,3.50701 2.84299219,6.35 6.35000009,6.35 C 10.357008,297 13.2,294.15701 13.2,290.65 c -0.0022,-0.84296 -0.452078,-2.71271 -0.500228,-2.45359 -0.02424,0.84121 -0.571809,2.35322 -0.602031,2.23138 -0.0026,-0.50621 -0.2876,-1.42626 -0.305098,-1.19509 0.02804,1.40695 -1.48374,3.17677 -2.3076623,3.50038 -0.8310457,0.36942 -1.7371637,0.56412 -2.6117267,0.56534 -0.1736918,2e-5 -1.1686519,-0.13807 -1.6443439,-0.70435 -0.826376,-0.89253 -0.00201,-1.09994 0.4625039,-1.27331 0.5055862,-0.18871 1.030887,-0.30969 1.5203212,-0.42013 0.7456988,-0.16826 0.4710618,-0.52626 0.1049028,-0.6289 -0.9266939,-0.25976 -2.044886,0.33543 -2.8654579,0.30593 -0.848406,-0.0291 -0.804618,-1.69621 -0.1405601,-1.76217 0.7394212,-0.0734 1.6665151,-0.51079 1.461779,-0.65673 -0.8303549,-0.61672 -0.9617369,-0.79081 -1.0595549,-1.16418 -0.1480201,-0.565 0.341282,-1.03557 0.05777,-0.96356 -0.2596169,0.08 -0.4110678,0.15641 -0.5988619,0.25715 -0.1672929,0.0897 -0.293814,0.0546 -0.6751841,0.002 -0.3249449,-0.045 -0.3870058,-0.0557 -0.3755009,-0.25673 0.0115,-0.20097 0.07295,-0.52125 -0.05223,-0.47648 z" id="path5345" style="fill:#7aafff;fill-opacity:1;stroke:none;stroke-width:2.01045942;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></clipPath><clipPath clipPathUnits="userSpaceOnUse" id="clipPath4543"><path d="m 1.7760088,291.5696 c -1.82613339,0.17434 -3.2940315,0.91934 -3.4903996,2.16451 -0.2629054,1.66729 1.5678591,3.34127 4.0891213,3.73893 1.2172084,0.19119 2.434234,0.053 3.3807423,-0.38387 0.7310194,0.5283 1.669357,0.90078 2.6704721,1.06008 2.5212691,0.39771 4.7783381,-0.6315 5.0412801,-2.2988 0.262905,-1.6673 -1.490667,-1.94329 -4.257163,-2.17938 -2.7664958,-0.23609 -3.6163896,-1.68839 -5.7470448,-2.04575 -0.5660191,-0.0893 -1.1380808,-0.10817 -1.6870084,-0.0557 z" id="path4545" style="opacity:1;vector-effect:none;fill:#666666;fill-opacity:1;stroke:none;stroke-width:2.11666656;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/></clipPath><clipPath clipPathUnits="userSpaceOnUse" id="clipPath5343-6"><path d="m 3.0688351,285.55677 c -1.613568,1.19596 -2.5662181,3.08478 -2.56883509,5.09323 0,3.50701 2.84299219,6.35 6.35000009,6.35 C 10.357008,297 13.2,294.15701 13.2,290.65 c -0.0022,-0.84296 -0.452078,-2.71271 -0.500228,-2.45359 -0.02424,0.84121 -0.571809,2.35322 -0.602031,2.23138 -0.0026,-0.50621 -0.2876,-1.42626 -0.305098,-1.19509 0.02804,1.40695 -1.48374,3.17677 -2.3076623,3.50038 -0.8310457,0.36942 -1.7371637,0.56412 -2.6117267,0.56534 -0.1736918,2e-5 -1.1686519,-0.13807 -1.6443439,-0.70435 -0.826376,-0.89253 -0.00201,-1.09994 0.4625039,-1.27331 0.5055862,-0.18871 1.030887,-0.30969 1.5203212,-0.42013 0.7456988,-0.16826 0.4710618,-0.52626 0.1049028,-0.6289 -0.9266939,-0.25976 -2.044886,0.33543 -2.8654579,0.30593 -0.848406,-0.0291 -0.804618,-1.69621 -0.1405601,-1.76217 0.7394212,-0.0734 1.6665151,-0.51079 1.461779,-0.65673 -0.8303549,-0.61672 -0.9617369,-0.79081 -1.0595549,-1.16418 -0.1480201,-0.565 0.341282,-1.03557 0.05777,-0.96356 -0.2596169,0.08 -0.4110678,0.15641 -0.5988619,0.25715 -0.1672929,0.0897 -0.293814,0.0546 -0.6751841,0.002 -0.3249449,-0.045 -0.3870058,-0.0557 -0.3755009,-0.25673 0.0115,-0.20097 0.07295,-0.52125 -0.05223,-0.47648 z" id="path5345-2" style="fill:#7aafff;fill-opacity:1;stroke:none;stroke-width:2.01045942;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></clipPath><clipPath clipPathUnits="userSpaceOnUse" id="clipPath4543-6"><path d="m 1.7760088,291.5696 c -1.82613339,0.17434 -3.2940315,0.91934 -3.4903996,2.16451 -0.2629054,1.66729 1.5678591,3.34127 4.0891213,3.73893 1.2172084,0.19119 2.434234,0.053 3.3807423,-0.38387 0.7310194,0.5283 1.669357,0.90078 2.6704721,1.06008 2.5212691,0.39771 4.7783381,-0.6315 5.0412801,-2.2988 0.262905,-1.6673 -1.490667,-1.94329 -4.257163,-2.17938 -2.7664958,-0.23609 -3.6163896,-1.68839 -5.7470448,-2.04575 -0.5660191,-0.0893 -1.1380808,-0.10817 -1.6870084,-0.0557 z" id="path4545-1" style="opacity:1;vector-effect:none;fill:#666666;fill-opacity:1;stroke:none;stroke-width:2.11666656;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"/></clipPath></defs><g id="layer1" transform="translate(0,-284.3)"><circle cx="6.3499999" cy="290.64999" id="path4514" r="6.3499999" style="fill:#aaccff;fill-opacity:1;stroke:none;stroke-width:1.74658811;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/><g id="g4729-8" transform="matrix(0.89946805,0,0,0.89946805,0.63032459,30.078033)"/><path d="m 3.99726,287.23444 h 5.3046825 c 0.1175919,0 0.2122599,0.0947 0.2122599,0.21226 v 7.00604 c 0,0.1176 -0.094668,0.21226 -0.2122599,0.21226 H 3.99726 c -0.117592,0 -0.2122599,-0.0947 -0.2122599,-0.21226 v -7.00604 c 0,-0.1176 0.094668,-0.21226 0.2122599,-0.21226 z" id="rect835-2" style="opacity:1;fill:#5b99f8;fill-opacity:1;stroke:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="m 3.6976587,286.93472 h 5.3046825 c 0.1175919,0 0.2122598,0.0947 0.2122598,0.21226 v 7.00605 c 0,0.11759 -0.094668,0.21226 -0.2122598,0.21226 H 3.6976587 c -0.117592,0 -0.2122599,-0.0947 -0.2122599,-0.21226 v -7.00605 c 0,-0.11759 0.094668,-0.21226 0.2122599,-0.21226 z" id="rect835" style="opacity:1;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.99999994;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="M 4.3527838,292.02725 H 7.862146 c 0.091343,0 0.1648795,0.0735 0.1648795,0.16488 v 0 c 0,0.0913 -0.073536,0.16488 -0.1648795,0.16488 H 4.3527838 c -0.091343,0 -0.1648794,-0.0735 -0.1648794,-0.16488 v 0 c 0,-0.0913 0.073536,-0.16488 0.1648794,-0.16488 z" id="rect892-5-3" style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.51573467;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="m 4.3527838,293.02374 h 3.9944327 c 0.091343,0 0.1648794,0.0735 0.1648794,0.16488 0,0.0913 -0.073536,0.16488 -0.1648794,0.16488 H 4.3527838 c -0.091343,0 -0.1648794,-0.0735 -0.1648794,-0.16488 0,-0.0913 0.073536,-0.16488 0.1648794,-0.16488 z" id="rect892-3-6" style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.51573467;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="m 4.3527838,289.7767 h 3.9944327 c 0.091343,0 0.1648794,0.0735 0.1648794,0.16488 0,0.0914 -0.073536,0.16488 -0.1648794,0.16488 H 4.3527838 c -0.091343,0 -0.1648794,-0.0735 -0.1648794,-0.16488 0,-0.0913 0.073536,-0.16488 0.1648794,-0.16488 z" id="rect892-5-5-7" style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.51573473;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="m 4.3312787,288.70816 h 3.358345 c 0.079429,0 0.1433743,0.0639 0.1433743,0.14337 v 0.043 c 0,0.0794 -0.063945,0.14337 -0.1433743,0.14337 h -3.358345 c -0.079429,0 -0.1433743,-0.0639 -0.1433743,-0.14337 v -0.043 c 0,-0.0794 0.063945,-0.14337 0.1433743,-0.14337 z" id="rect892-5-6-5" style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.51573473;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="m 4.3527838,287.69739 h 2.3526563 c 0.091343,0 0.1648795,0.0735 0.1648795,0.16488 v 0 c 0,0.0913 -0.073536,0.16488 -0.1648795,0.16488 H 4.3527838 c -0.091343,0 -0.1648794,-0.0735 -0.1648794,-0.16488 v 0 c 0,-0.0914 0.073536,-0.16488 0.1648794,-0.16488 z" id="rect892-5-6-2-3" style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.51573473;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/><path d="m 4.345616,290.88745 h 3.0610158 c 0.087372,0 0.1577117,0.0703 0.1577117,0.15771 v 0.0143 c 0,0.0874 -0.070339,0.15771 -0.1577117,0.15771 H 4.345616 c -0.087372,0 -0.1577116,-0.0703 -0.1577116,-0.15771 v -0.0143 c 0,-0.0874 0.070339,-0.15771 0.1577116,-0.15771 z" id="rect892-5-5-9-5" style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.51573473;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"/></g></svg>
\ No newline at end of file
diff --git a/icons/find.png b/icons/find.png
new file mode 100644
index 0000000..f0489cc
Binary files /dev/null and b/icons/find.png differ
diff --git a/icons/find.svg b/icons/find.svg
new file mode 100644
index 0000000..b9b6126
--- /dev/null
+++ b/icons/find.svg
@@ -0,0 +1,25 @@
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+-->
+<svg viewBox="-12 -12 36 36" xmlns="http://www.w3.org/2000/svg" version="1.1">
+<title>Find icon</title>
+  <circle cx="0" cy="0" r="10" fill="none" stroke="#000000" stroke-width="4" />
+  <polygon points="10,5.5 24,19.5 19.5,24 5.5,10" fill="#000000" />
+</svg>
diff --git a/icons/scad.png b/icons/scad.png
new file mode 100644
index 0000000..1d4e986
Binary files /dev/null and b/icons/scad.png differ
diff --git a/index.php b/index.php
new file mode 100644
index 0000000..55eb09d
--- /dev/null
+++ b/index.php
@@ -0,0 +1,81 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+// Upgrade HTTP requests to HTTPS if the client supports/requests it
+if(isset($_SERVER['HTTP_UPGRADE_INSECURE_REQUESTS']) &&
+   in_array(strtolower($_SERVER['HTTP_UPGRADE_INSECURE_REQUESTS']), Array('1','true','yes','on')) &&
+   (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS']=='off'))
+{
+  header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], true, 301);
+  exit();
+}
+if(!file_exists('config.php')){include('setup.php'); exit();}
+include_once('config.php');
+$path=$_SERVER['REQUEST_URI'];
+if(strpos($path, '?')){$path=substr($path, 0, strpos($path, '?'));}
+if(substr($path, 0, strlen(BASEURL))==BASEURL){$path=substr($path, strlen(BASEURL));}
+$path=explode('/', $path);
+switch($path[1])
+{
+  case 'login': include('login.php'); break;
+  case 'logout': include('logout.php'); break;
+  case 'register': include('register.php'); break;
+  case 'user': include('user.php'); break;
+  case 'thing': include('thing.php'); break;
+  case 'browse':
+  case 'search': include('search.php'); break;
+  case 'license': include('license.php'); break;
+  case 'editprofile': include('editprofile.php'); break;
+  case 'editthing': include('editthing.php'); break;
+  case 'messages': include('messages.php'); break;
+  case 'verifyemail': include('verifyemail.php'); break;
+  case 'report': include('report.php'); break;
+  case 'admin': include('admin.php'); break;
+  case 'rpc':
+    header('Content-type: application/json');
+    include_once('db.php');
+    if(isset($_SERVER['HTTP_X_THINGSHARE_NODE']) && $_SERVER['HTTP_X_THINGSHARE_NODE']!=DOMAIN && getoption('autofollow'))
+    {
+      $peer=mysqli_real_escape_string($db, $_SERVER['HTTP_X_THINGSHARE_NODE']);
+      $res=mysqli_query($db, 'select domain from peers where domain="'.$peer.'"');
+      if(!mysqli_fetch_row($res))
+      {
+        mysqli_query($db, 'insert into peers(domain, blacklist) values("'.$peer.'", 0)');
+      }
+    }
+    switch($path[2])
+    {
+      case 'user': include('rpc_user.php'); exit();
+      case 'thing': include('rpc_thing.php'); exit();
+      case 'search': include('rpc_search.php'); exit();
+      case 'rpckey': print(json_encode(Array('public'=>file_get_contents('rpckey.pem')), true)); exit();
+      case 'report': include('rpc_report.php'); exit();
+    }
+    header('HTTP/1.1 404 Not found');
+    die('{"httpresponse":404,"error":"Not found"}');
+    break;
+  default:
+    include_once('head.php');
+    header('HTTP/1.1 404 Not found');
+    print('<div class="error"><h1>Not found</h1></div>');
+    break;
+}
+include_once('foot.php');
+// TODO: Default/front page
+?>
diff --git a/license.php b/license.php
new file mode 100644
index 0000000..bd193cb
--- /dev/null
+++ b/license.php
@@ -0,0 +1,40 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+// Note: this file is not a license text, it's merely a script that handles license texts for 'things'
+include_once('db.php');
+$name=mysqli_real_escape_string($db, urldecode($path[2]));
+$res=mysqli_query($db, 'select full from licenses where name="'.$name.'"');
+if(!($res=mysqli_fetch_row($res)))
+{
+  header('HTTP/1.1 404 Not found');
+  include_once('head.php');
+  print('<div class="error"><h1>'._('License not found').'</h1></div>');
+}else{
+  $full=$res[0];
+  if(substr_count($full, '://')>0 && substr_count($full, "\n")==0)
+  {
+    // If 'full license text' is specified as a link, forward visitor to that link
+    header('Location: '.$full);
+  }else{
+    print($full);
+  }
+  exit();
+}
+?>
diff --git a/login.php b/login.php
new file mode 100644
index 0000000..537f91a
--- /dev/null
+++ b/login.php
@@ -0,0 +1,59 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+// TODO: Protect against excess failed logins from the same IP
+if(isset($_POST['user']) && isset($_POST['pass']))
+{
+  include_once('db.php');
+  $error=_('Incorrect username/password');
+  $user=mysqli_real_escape_string($db, $_POST['user']);
+  $res=mysqli_query($db, 'select salt, password, id, status from users where name="'.$user.'"');
+  if($res=mysqli_fetch_assoc($res))
+  {
+    $hash=explode(':', $res['password']);
+    $pass=hash($hash[0], $_POST['pass'].$res['salt']);
+    if($pass==$hash[1])
+    {
+      switch($res['status'])
+      {
+        case ACCOUNT_ACTIVE:
+          session_start();
+          $_SESSION['name']=$_POST['user'];
+          $_SESSION['id']=$res['id'];
+          header('Location: '.(isset($_GET['returnto'])?urldecode($_GET['returnto']):BASEURL));
+          exit();
+        case ACCOUNT_BANNED: $error=_('Banned'); break;
+        case ACCOUNT_EMAILUNVERIFIED: $error=_('Please check for a verification e-mail'); break;
+      }
+    }
+  }
+  $error='<div class="error">'.$error.'</div>';
+}else{
+  $error='';
+}
+include_once('head.php');
+?>
+<form method="post" id="loginform">
+  <center>
+    <?=$error?>
+    <input type="text" name="user" placeholder="<?=_('Username')?>" /><br />
+    <input type="password" name="pass" placeholder="<?=_('Password')?>" /><br />
+    <button><?=_('Log in')?></button>
+  </center>
+<form>
diff --git a/logout.php b/logout.php
new file mode 100644
index 0000000..29047a3
--- /dev/null
+++ b/logout.php
@@ -0,0 +1,25 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+session_start();
+// TODO: Also unset the PHPSESSID cookie?
+session_destroy();
+header('Location: '.(isset($_GET['returnto'])?urldecode($_GET['returnto']):BASEURL));
+exit();
+?>
diff --git a/nonce.php b/nonce.php
new file mode 100644
index 0000000..24f1573
--- /dev/null
+++ b/nonce.php
@@ -0,0 +1,33 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+function nonce()
+{
+  $num=($_SESSION['noncenum']++)%500; // Incremental suffix to avoid collisions
+  $_SESSION['nonce'.$num]=bin2hex(random_bytes(16));
+  return '<input type="hidden" name="nonce" value="'.$num.':'.$_SESSION['nonce'.$num]."\" />\n";
+}
+function checknonce()
+{
+  $nonce=explode(':', $_POST['nonce']);
+  $res=(isset($_SESSION['nonce'.$nonce[0]]) && $_SESSION['nonce'.$nonce[0]]==$nonce[1]);
+  unset($_SESSION['nonce'.$nonce[0]]);
+  return $res;
+}
+?>
diff --git a/register.php b/register.php
new file mode 100644
index 0000000..2672174
--- /dev/null
+++ b/register.php
@@ -0,0 +1,83 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('head.php');
+include_once('db.php');
+$user='';
+$email='';
+$pass='';
+$pass2='';
+$error='';
+$form=true;
+if(isset($_POST['user']) && isset($_POST['email']) && isset($_POST['pass']) && isset($_POST['pass2']))
+{
+  $user=$_POST['user'];
+  $email=$_POST['email'];
+  $pass=$_POST['pass'];
+  $pass2=$_POST['pass2'];
+  // Error checks
+  if(!isset($_POST['tos'])){$error=_('Agreeing to the terms of service is mandatory');}
+  if(substr_count($email, '@')!=1){$error=sprintf(_('%s does not appear to be a valid e-mail address'), $email);}
+  if($pass!=$pass2){$error=_('The passwords don\'t match');}
+  if(strlen($pass)<...>0){$error=sprintf(_("Usernames may not contain '%s'"), $char);}
+  }
+  $user_esc=mysqli_real_escape_string($db, $user);
+  $email_esc=mysqli_real_escape_string($db, $email);
+  $res=mysqli_query($db, 'select name from users where name="'.$user_esc.'"');
+  if(mysqli_fetch_row($res)){$error=_('A user by that name already exists on this node. Please pick a different username');}
+  $res=mysqli_query($db, 'select name from users where email="'.$email_esc.'"');
+  if(mysqli_fetch_row($res)){$error=_('A user with that e-mail address already exists on this node');}
+  if($error=='')
+  {
+    $salt=bin2hex(random_bytes(32));
+    $hash=HASH.':'.hash(HASH, $pass.$salt);
+    $usercount=mysqli_query($db, 'select count(*) from users');
+    $usercount=mysqli_fetch_row($usercount)[0];
+    $privileges=($usercount==0?PRIV_ALL:0); // First one in is an administrator
+    mysqli_query($db, 'insert into users(name, salt, password, email, displayname, profile, privileges, status) values("'.$user_esc.'", "'.$salt.'", "'.$hash.'", "'.$email_esc.'", "'.$user_esc.'", "", '.$privileges.', '.ACCOUNT_EMAILUNVERIFIED.')');
+    // Email verification
+    $verifycode=hash(HASH, $email.$salt.date('j'));
+    // TODO: HTML email? Alternative email methods? PHPMailer seems popular but I'm not sure what the need or appeal is
+    mail($email, _('Thingshare e-mail verification'), _('Please follow this link to verify your e-mail address and activate your Thingshare account:')."\nhttps://".$_SERVER['HTTP_HOST'].BASEURL.'/verifyemail?u='.urlencode($user).'&c='.$verifycode, Array('From'=>NODENAME.' <'.EMAIL.'>', 'Date'=>date('r')));
+    print('<h1>'._('Welcome!').'</h1>');
+    print(_('You will shortly receive a verification e-mail, please follow the link to activate your account'));
+    $form=false;
+  }
+}
+if($error!=''){$error='<div class="error">'.$error.'</div>';}
+if($form)
+{
+?>
+<br />
+<form method="post">
+  <center>
+    <?=$error?>
+    <input type="text" name="user" placeholder="Username" value="<?=$user?>" /><br />
+    <input type="text" name="email" placeholder="E-mail address" value="<?=$email?>" /><br />
+    <input type="password" name="pass" placeholder="Password" value="<?=$pass?>" /><br />
+    <input type="password" name="pass2" placeholder="Password again" value="<?=$pass2?>" /><br />
+    <label><input type="checkbox" name="tos"<?=(isset($_POST['tos'])?' checked':'')?> /> I agree to the terms of service which disclaim any and all liability, responsibility, and accountability (TODO: Write a real ToS document)</label><br />
+    <button><?=_('Create account')?></button>
+  </center>
+<form>
+<?php } ?>
diff --git a/report.php b/report.php
new file mode 100644
index 0000000..74a88ac
--- /dev/null
+++ b/report.php
@@ -0,0 +1,62 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('head.php');
+// Only accept reports from logged in users
+if(!isset($_SESSION['id'])){header('Location: '.BASEURL.'/login?returnto='.urlencode($_SERVER['REQUEST_URI']));}
+include_once('nonce.php');
+include_once('rpc.php');
+$target=$path[2];
+// TODO: See if this works well for comments too, only things and comments need reports
+$item=explode('@',$path[3]);
+$path[3]=$item[0];
+for($i=3; $i<count($path); ++$i){$target.='/'.$path[$i];}
+if(checknonce() && isset($_POST['reason']))
+{
+  $reason=$_POST['reason'];
+  if($reason=='other' && isset($_POST['reason_other'])){$reason.=': '.$_POST['reason_other'];}
+  $obj=Array(
+    'user'=>$_SESSION['name'],
+    'reason'=>$reason,
+    'target'=>$target);
+  $res=rpc_post($item[1], 'report', $obj);
+  if(isset($res['status']) && strtoupper($res['status'])=='OK')
+  {
+    print('<h1>'._('Report received').'</h1>');
+    include_once('foot.php');
+    exit();
+  }
+}
+
+// Get the name of the target
+$obj=rpc_get($item[1], $path[2].'/'.$item[0]);
+$targetname=htmlentities($target.'@'.$item[1].' ('.$obj['name'].')');
+?>
+<form method="post">
+  <?=nonce()?>
+  <h1><?=_('Report')?></h1>
+  <p><?=$targetname?></p>
+<!--
+TODO: Mod-defined canned reports? Local or target's node?
+target's node makes sense from the perspective of adding canned reports based on what people fill in as "other". E.g. if a node is dealing with a problem specific to that node they'll see that a new canned report may be needed. And the local node wouldn't see it unless it faces the same problem.
+So target's it is
+-->
+  <label><input type="radio" name="reason" value="other" id="report_other" />Other: <input type="text" name="reason_other" onfocus="document.getElementById('report_other').checked=true;" /></label><br />
+  <button>Report</button>
+</form>
diff --git a/rpc.php b/rpc.php
new file mode 100644
index 0000000..08e4a7a
--- /dev/null
+++ b/rpc.php
@@ -0,0 +1,228 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+function rpc_curlinit($domain, $rpc)
+{
+  $curl=curl_init('https://'.$domain.'/rpc/'.$rpc);
+  curl_setopt_array($curl, Array(
+    CURLOPT_RETURNTRANSFER=>true,
+    CURLOPT_FOLLOWLOCATION=>true,
+    CURLOPT_MAXREDIRS=>10,
+    CURLOPT_HTTPHEADER=>Array('X-Thingshare-node: '.DOMAIN), // Let other nodes know who we are in case they want to federate back, and for signature verification
+    CURLOPT_USERAGENT=>'Thingshare RPC'));
+  return $curl;
+}
+
+function rpc_cooldown_check($domain)
+{
+  global $db;
+  $domain=mysqli_real_escape_string($db, $domain);
+  $timestamp=mysqli_real_escape_string($db, date('Y-m-d H:i:s'));
+  mysqli_query($db, 'delete from cooldown where end<"'.$timestamp.'"'); // Clear old cooldowns
+  $res=mysqli_query($db, 'select domain from cooldown where domain="'.$domain.'"');
+  return (mysqli_fetch_row($res)===null);
+}
+
+function rpc_cooldown($domain)
+{
+  global $db;
+  $domain=mysqli_real_escape_string($db, $domain);
+  $timestamp=mysqli_real_escape_string($db, date('Y-m-d H:i:s', time()+3600)); // One hour sounds good, not too long for temporarily unavailable nodes and not too short for "flood" targets
+  mysqli_query($db, 'insert into cooldown(domain, end) values("'.$domain.'", "'.$timestamp.'")');
+}
+
+function rpc_cache($domain, $rpc, $content)
+{
+  if($domain==DOMAIN){return;} // Don't cache self (or is there a good reason to? other than testing)
+  global $db;
+  $timestamp=mysqli_real_escape_string($db, date('Y-m-d H:i:s'));
+  $hash=hash(HASH, $domain.'/'.$rpc);
+  $content=mysqli_real_escape_string($db, $content);
+  mysqli_query($db, 'delete from rpccache where hash="'.$hash.'"'); // Erase duplicate (avoids primary key duplication)
+  mysqli_query($db, 'insert into rpccache(hash, timestamp, cache) values("'.$hash.'", "'.$timestamp.'", "'.$content.'")');
+}
+
+function rpc_getcache($domain, $rpc, $fallback=false)
+{
+  if($domain==DOMAIN){return false;} // Don't cache self (or is there a good reason to? other than testing)
+  global $db;
+  $limit=mysqli_real_escape_string($db, date('Y-m-d H:i:s', time()-3600)); // TODO: Configurable cache time limit
+  mysqli_query($db, 'delete from rpccache where timestamp<"'.$limit.'"');
+  $hash=hash(HASH, $domain.'/'.$rpc);
+  $q='select cache from rpccache where hash="'.$hash.'"';
+  if(!$fallback)
+  {
+    $limit=mysqli_real_escape_string($db, date('Y-m-d H:i:s', time()-600)); // TODO: Configurable cache time limit
+    $q.=' and timestamp>"'.$limit.'"';
+  }
+// else{print('Trying to use the cache as fallback<br />');}
+  $res=mysqli_query($db, $q);
+  if($res=mysqli_fetch_row($res))
+  {
+// print('Cache hit ('.$domain.'/'.$rpc.')<br />');
+    return $res[0];
+  }
+// print('Cache miss ('.$domain.'/'.$rpc.')<br />');
+  return false;
+}
+
+function rpc_get($domain, $rpc)
+{
+  // Check whether the domain is in cooldown first
+  if(!rpc_cooldown_check($domain))
+  {
+    // Attempt to fall back on the cache (without the soft time limit)
+    if($obj=rpc_getcache($domain, $rpc, true)){return json_decode($obj, true);}
+    return Array('error'=>'Domain is in cooldown');
+  }
+  // Check for cached response first
+  if($obj=rpc_getcache($domain, $rpc)){return json_decode($obj, true);}
+  $curl=rpc_curlinit($domain, $rpc);
+  $data=curl_exec($curl);
+  curl_close($curl);
+  $obj=json_decode($data, true);
+  if($obj===null) // Unexpected response, set cooldown to prevent flooding of non-thingshare domains
+  {
+    rpc_cooldown($domain);
+    // Attempt to fall back on the cache (without the soft time limit)
+    if($obj=rpc_getcache($domain, $rpc, true)){return json_decode($obj, true);}
+    return Array('error'=>'Unexpected response, putting domain in cooldown');
+  }
+  rpc_cache($domain, $rpc, $data);
+  return $obj;
+}
+
+function rpc_search($domains, $rpc) // TODO: Is there a more appropriate name for this function?
+{
+  $multi=curl_multi_init();
+  $responses=Array();
+  $curls=Array();
+  // Set up each request
+  foreach($domains as $domain)
+  {
+    if($cache=rpc_getcache($domain, $rpc))
+    {
+      $responses[$domain]=json_decode($cache, true);
+      continue;
+    }
+    if(!rpc_cooldown_check($domain))
+    {
+      $responses[$domain]=Array('error'=>'Domain is in cooldown');
+      $cache=rpc_getcache($domain, $rpc, true); // Attempt to use cache as fallback
+      if($cache){$responses[$domain]=json_decode($cache, true);}
+      continue;
+    }
+    $curl=rpc_curlinit($domain, $rpc);
+    curl_setopt($curl, CURLOPT_TIMEOUT, 2); // TODO: Make this configurable? maybe use TIMEOUT_MS?
+    curl_multi_add_handle($multi, $curl);
+    $curls[$domain]=$curl;
+  }
+  // Run requests in parallel
+  while(($status=curl_multi_exec($multi, $running))==CURLM_OK && $running)
+  {
+    curl_multi_select(); // Wait for activity
+  }
+  // Handle responses
+  foreach($domains as $domain)
+  {
+    if(!isset($curls[$domain])){continue;} // Already handled, cache or cooldown
+    $curl=$curls[$domain];
+    $content=curl_multi_getcontent($curl);
+    $obj=json_decode($content, true);
+    if($obj===null) // Unexpected response, set cooldown
+    {
+      rpc_cooldown($domain);
+      $obj=Array('error'=>'Unexpected response, putting domain in cooldown');
+      $cache=rpc_getcache($domain, $rpc, true); // Attempt to use cache as fallback
+      if($cache){$obj=json_decode($cache, true);}
+    }else{
+      rpc_cache($domain, $rpc, $content);
+    }
+    $responses[$domain]=$obj;
+    curl_multi_remove_handle($multi, $curl);
+  }
+  curl_multi_close($multi);
+  return $responses;
+}
+
+function rpc_post($domain, $rpc, $data) // For comments, reports, etc.
+{
+  // Check whether the domain is in cooldown first
+  if(!rpc_cooldown_check($domain))
+  {
+    return Array('error'=>'Domain is in cooldown');
+  }
+  // Encode $data to string if it isn't already
+  if(is_array($data)){$data=json_encode($data);}
+  // Sign content and bundle it up with signature and hash algorithm used
+  openssl_sign($data, $sig, getoption('rpckey'), 'sha512');
+  $obj=Array(
+    'data'=>$data,
+    'signature'=>base64_encode($sig),
+    'algorithm'=>'sha512');
+  // Make the request
+  $curl=rpc_curlinit($domain, $rpc);
+  curl_setopt_array($curl, Array(
+    CURLOPT_POST=>true,
+    CURLOPT_SAFE_UPLOAD=>true,
+    CURLOPT_POSTFIELDS=>$obj));
+  $data=curl_exec($curl);
+  curl_close($curl);
+  $obj=json_decode($data, true);
+  if($obj===null) // Unexpected response, set cooldown to prevent flooding of non-thingshare domains
+  {
+    rpc_cooldown($domain);
+    return Array('error'=>'Unexpected response, putting domain in cooldown');
+  }
+  return $obj;
+}
+
+function rpc_verifypost(&$peer)
+{
+  // Basic check
+  if(!isset($_POST['data']) || !isset($_POST['signature']) || !isset($_POST['algorithm']) || !isset($_SERVER['HTTP_X_THINGSHARE_NODE']))
+  {
+    die('{"error":"Missing data, signature, algorithm, or Thingshare node identifier header"}');
+  }
+  $peer=$_SERVER['HTTP_X_THINGSHARE_NODE'];
+  // TODO: Check algorithm against a whitelist? Might be good to avoid known weak hash algorithms and obscure algorithms which have avoided scrutiny
+  // Get the public key
+  $key=rpc_get($peer, 'rpckey');
+  if(isset($key['error']) || !isset($key['public']))
+  {
+    die('{"error":"Failed to fetch public key for verification","suberror":'.json_encode($key).'}');
+  }
+  // Verify signature
+  $key=$key['public'];
+  $data=$_POST['data'];
+  $sig=base64_decode($_POST['signature']);
+  $algo=$_POST['algorithm'];
+  if(!openssl_verify($data, $sig, $key, $algo))
+  {
+    die('{"error":"Signature check failed"}');
+  }
+  $obj=json_decode($data, true);
+  if($obj===null)
+  {
+    die('{"error":"Failed to decode data"}');
+  }
+  return $obj;
+}
+?>
diff --git a/rpc_report.php b/rpc_report.php
new file mode 100644
index 0000000..b267d81
--- /dev/null
+++ b/rpc_report.php
@@ -0,0 +1,33 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('rpc.php');
+include_once('db.php');
+$obj=rpc_verifypost($peer);
+$user=mysqli_real_escape_string($db, $obj['user'].'@'.$peer);
+$target=mysqli_real_escape_string($db, $obj['target']);
+$reason=mysqli_real_escape_string($db, $obj['reason']);
+$timestamp=mysqli_real_escape_string($db, date('Y-m-d H:i:s'));
+if(mysqli_query($db, 'insert into reports(user, target, reason, timestamp) values("'.$user.'", "'.$target.'", "'.$reason.'", "'.$timestamp.'")'))
+{
+  print('{"status":"OK"}');
+}else{
+  print('{"error":"Database error"}');
+}
+?>
diff --git a/rpc_search.php b/rpc_search.php
new file mode 100644
index 0000000..6ff317f
--- /dev/null
+++ b/rpc_search.php
@@ -0,0 +1,97 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('db.php');
+include_once('files.php');
+// If you experience problem with slashes in searches you may need 'AllowEncodedSlashes NoDecode' in your Apache config (outside of <Directory>. More info at https://httpd.apache.org/docs/current/mod/core.html#allowencodedslashes )
+$words=explode(' ', urldecode($path[3]));
+$order=$path[4]; // TODO: Test (at time of writing there was only one 'thing')
+$count=(int)$path[5];
+$skip=(int)$path[6];
+if(!$count){$count=10;}
+switch($order)
+{
+  case 'alpha': $order='name asc'; break;
+  case 'old': $order='posted asc'; break;
+  case 'new':
+  default: $order='posted desc'; break;
+}
+// Find quotes and combine into one "word"
+$qstart=false;
+for($i=0; $i<count($words); ++$i)
+{
+  if(substr_count($words[$i],'"')==1 && $qstart!==false){$qstart=$i;} // Don't be picky about the qoute starting at the beginning or it'll break the modes and negative matches below
+  elseif(substr($words[$i],-1)=='"') // End quote
+  {
+    $word=implode(' ', array_slice($words, $qstart, $i-$qstart+1));
+    $word=str_replace('"','',$word); // Strip quotes
+    array_splice($words, $qstart, $i-$qstart+1, $word);
+    $qstart=false;
+  }
+}
+$q='';
+foreach($words as $word)
+{
+  // TODO: Avoid matching partial words?
+
+  // Modes (e.g. name-only, description-only)
+  $mode='';
+  if(substr_count($word, ':'))
+  {
+    $mode=explode(':', $word)[0]; // Grab mode
+    $word=substr($word, strlen($mode)+1); // Cut mode from word
+  }
+  // Negative matches
+  $like='like';
+  $or='or';
+  if(substr($word,0,1)=='-'){$like='not like'; $or='and'; $word=substr($word,1);}
+  // Escape
+  $word=addcslashes(mysqli_real_escape_string($db, $word), '%_');
+  if($q!=''){$q.=' and ';}
+  switch($mode)
+  {
+    case 'name': $q.='(name '.$like.' "%'.$word.'%")'; break;
+    case 'description': $q.='(description '.$like.' "%'.$word.'%")'; break;
+    default: $q.='(name '.$like.' "%'.$word.'%" '.$or.' description '.$like.' "%'.$word.'%")'; break;
+  }
+}
+if($words==Array('')){$q='1';}
+$obj=Array();
+// Gather things
+$res=mysqli_query($db, 'select id, thingid, name, description, posted, user from things where '.$q.' and latest and !removed order by '.$order.' limit '.$count.' offset '.$skip);
+while($row=mysqli_fetch_assoc($res))
+{
+  $thing=Array('id'=>$row['thingid'],
+               'name'=>$row['name'],
+               'description'=>$row['description'],
+               'date'=>$row['posted']);
+  $user=$row['user'];
+  // Grab preview from the first file
+// TODO: Figure out file ordering so we get the first one (chosen preview)
+  $res2=mysqli_query($db, 'select name, hash from files where thing='.(int)$row['id'].' limit 1');
+  $row=mysqli_fetch_assoc($res2);
+  $thing['preview']=getpreview($row['name'], $row['hash']);
+  // Designer
+  $res2=mysqli_query($db, 'select displayname, name from users where id='.$user);
+  $row=mysqli_fetch_assoc($res2);
+  $thing['by']=$row;
+  $obj[]=$thing;
+}
+print(json_encode($obj));
+?>
diff --git a/rpc_thing.php b/rpc_thing.php
new file mode 100644
index 0000000..9ee70c0
--- /dev/null
+++ b/rpc_thing.php
@@ -0,0 +1,58 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+if(!isset($path[3])){die();}
+include_once('db.php');
+include_once('files.php');
+$id=(int)$path[3];
+$res=mysqli_query($db, 'select id, name, description, user, posted, license from things where thingid='.$id.' and latest and !removed');
+$row=mysqli_fetch_assoc($res);
+if(!$row){header('HTTP/1.1 404 Not found'); die('{"error":"Thing not found"}');}
+$thing=Array('id'=>$id,
+             'name'=>$row['name'],
+             'description'=>$row['description'],
+             'date'=>$row['posted'],
+             'files'=>Array(),
+             'license'=>Array('name'=>$row['license']));
+$user=(int)$row['user'];
+// List files
+$res=mysqli_query($db, 'select name, hash from files where thing='.(int)$row['id']);
+while($row=mysqli_fetch_assoc($res))
+{
+  $file=Array('name'=>$row['name'],
+              'path'=>getfilepath($row['hash']),
+              'preview'=>getpreview($row['name'], $row['hash']));
+  // Grab mimetype, if set
+  $mime=db_getmimetype($row['name']);
+  if($mime!==false){$file['type']=$mime;}
+  $thing['files'][]=$file; // Add to list
+}
+// Designer
+$res=mysqli_query($db, 'select displayname, name from users where id='.$user);
+$row=mysqli_fetch_assoc($res);
+$thing['by']=$row;
+// Look up license's simplified description
+if($thing['license']['name']!='other')
+{
+  $name=mysqli_real_escape_string($db, $thing['license']['name']);
+  $res=mysqli_query($db, 'select simple from licenses where name="'.$name.'"');
+  if($row=mysqli_fetch_row($res)){$thing['license']['simple']=$row[0];}
+}
+print(json_encode($thing));
+?>
diff --git a/rpc_user.php b/rpc_user.php
new file mode 100644
index 0000000..eeafd75
--- /dev/null
+++ b/rpc_user.php
@@ -0,0 +1,50 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+if(!isset($path[3])){die();}
+include_once('db.php');
+include_once('files.php');
+$user=mysqli_real_escape_string($db, $path[3]);
+$res=mysqli_query($db, 'select id, displayname, profile, status from users where name="'.$user.'"');
+$res=mysqli_fetch_assoc($res);
+if(!$res){header('HTTP/1.1 404 Not found'); die('{"error":"User not found"}');}
+$id=(int)$res['id'];
+$obj=Array();
+// Populate user info
+$obj['displayname']=$res['displayname'];
+$obj['profile']=$res['profile'];
+$obj['things']=Array();
+if($res['status']==ACCOUNT_BANNED){$obj['banned']=true;}
+// Gather things
+$res=mysqli_query($db, 'select id, thingid, name, description, posted from things where user='.$id.' and latest and !removed order by posted desc');
+while($row=mysqli_fetch_assoc($res))
+{
+  $thing=Array('id'=>$row['thingid'],
+               'name'=>$row['name'],
+               'description'=>$row['description'],
+               'date'=>$row['posted']);
+  // Grab preview from the first file
+// TODO: Figure out sorting so we get the first one (chosen preview)
+  $res2=mysqli_query($db, 'select name, hash from files where thing='.(int)$row['id'].' limit 1');
+  $row=mysqli_fetch_assoc($res2);
+  $thing['preview']=getpreview($row['name'], $row['hash']);
+  $obj['things'][]=$thing;
+}
+print(json_encode($obj));
+?>
diff --git a/search.php b/search.php
new file mode 100644
index 0000000..cb3f646
--- /dev/null
+++ b/search.php
@@ -0,0 +1,88 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('head.php');
+include_once('db.php');
+include_once('rpc.php');
+// Get list of federated nodes
+$peers=Array(DOMAIN);
+$res=mysqli_query($db, 'select domain from peers where !blacklist');
+while($row=mysqli_fetch_row($res)){$peers[]=$row[0];}
+$perpage=20;
+$page=(int)(isset($_GET['page'])?$_GET['page']:0);
+$perpeer=round($perpage/count($peers));
+$sortby=(isset($_GET['sort'])?$_GET['sort']:'new');
+if($path[1]=='browse'){$sortby=$path[2];} // Handle 'Browse' links
+$res=rpc_search($peers, 'search/'.urlencode($_GET['q']).'/'.urlencode($sortby).'/'.$perpeer.'/'.($page*$perpage));
+// Construct navigation links for pages
+$pagefull=false;
+foreach($res as $r){if(count($r)==$perpeer){$pagefull=true;}}
+$pagenav='';
+if($page>1){$pagenav.='<a href="?q='.urlencode($_GET['q']).'" class="pagenav">'._('First page').'</a>';}
+if($page>0){$pagenav.='<a href="?q='.urlencode($_GET['q']).'&page='.($page-1).'" class="pagenav">'._('Previous page').'</a>';}
+if($pagefull){$pagenav.='<a href="?q='.urlencode($_GET['q']).'&page='.($page+1).'" class="pagenav">'._('Next page').'</a>';}
+
+// Flatten the results into a single array with peer information for each item
+$results=Array();
+foreach($res as $peer=>$res2)
+{
+  if(isset($res2['error']))
+  {
+    print('<div class="error">'.$peer.': '.$res2['error'].'</div>');
+    continue;
+  }
+  foreach($res2 as $thing)
+  {
+    $thing['peer']=$peer;
+    $results[]=$thing;
+  }
+}
+function sortthings($a, $b)
+{
+  global $sortby;
+  // TODO: More sorting options?
+  switch($sortby)
+  {
+    case 'alpha': return ord($b['name'])-ord($a['name']);
+    case 'old': return strtotime($b['date'])-strtotime($a['date']);
+    case 'new':
+    default: return strtotime($a['date'])-strtotime($b['date']);
+  }
+}
+usort($results, 'sortthings');
+
+// Construct the results page
+$things='';
+foreach($results as $thing)
+{
+  $things.='<div class="thing"><div class="boxtop">By <a href="'.BASEURL.'/user/'.$thing['by']['name'].'@'.$thing['peer'].'" title="'.$thing['by']['name'].'@'.$thing['peer'].'">'.$thing['by']['displayname'].'</a></div><...><div class="boxbottom">'.htmlentities($thing['name']).'</div><img src="https://'.$thing['peer'].$thing['preview'].'" /></a></div>';
+}
+?>
+<div class="sidebar">
+  <?=_('Results per page (approximately. TODO):')?> <input type="number" name="perpage" value="<?=$perpage?>" /><br />
+  <p>
+    <h4><?=_('Advanced search options')?></h4>
+    <?=_('To search for something specifically in the name:')?> <span class="code">name:searchterm</span><br />
+    <?=_('To search for something specifically in the description:')?> <span class="code">description:searchterm</span><br />
+    <?=_('To negate a searchterm, skipping everything that matches:')?> <span class="code">-searchterm</span><br />
+    <?=_('To match a specific phrase:')?> <span class="code">&quot;searchterm in multiple words&quot;</span><br />
+  </p>
+</div><br />
+<?=$things?>
+<?=$pagenav?>
diff --git a/setup.php b/setup.php
new file mode 100644
index 0000000..ea43d7b
--- /dev/null
+++ b/setup.php
@@ -0,0 +1,177 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+if(file_exists('config.php')){die('Already set up');}
+// TODO: Check that mod_rewrite/equivalent works? Might need to come after the data collection, considering domain and path
+// TODO: Check that session.gc_maxlifetime is set to at least a few hours? (with a warning, not an error)
+// Step 1: PHP Modules
+$modules=Array();
+if(!function_exists('curl_exec')){$modules[]='curl';}
+if(!function_exists('mysqli_connect')){$modules[]='mysqli';}
+if(!function_exists('imagepng')){$modules[]='gd';}
+if(!function_exists('openssl_sign')){$modules[]='openssl';}
+if(!function_exists('_')){$modules[]='gettext';} // TODO: Offer to create a noop _() and stick to english?
+if(count($modules)>0)
+{
+  print('<h1>PHP Modules</h1>');
+  print('To continue setting up Thingshare, make sure the following PHP modules are installed and enabled:<ul>');
+  foreach($modules as $m){print('<li>'.$m.'</li>');}
+  print('</ul>');
+  print('<form><button>Continue</button></form>');
+  exit();
+}
+// Step 2: Check that . is writable
+if(!touch('configtest'))
+{
+  print('<h1>Filesystem Permissions</h1>');
+  print('The account this script runs as ('.exec('whoami').') is unable to write to the web root directory, make sure the filesystem permissions are correct and that there is enough available disk space');
+  print('<form><button>Continue</button></form>');
+  exit();
+}
+unlink('configtest');
+// Step 3: Gather information to write a config.php
+if(!isset($_POST['DOMAIN']))
+{
+// TODO: Handle preview color and size
+  print('<form method="post">');
+  $baseurl=$_SERVER['REQUEST_URI'];
+  $baseurl=substr($baseurl,0,strrpos($baseurl,'/'));
+  // This ended up being a little bit longer than just copying the sample file and adjusting the format to be a form, but now it won't need to be updated when the sample config changes
+  $f=fopen('config.php.sample', 'r');
+  $title='';
+  while($line=fgets($f))
+  {
+    if(substr($line,0,2)=='//'){$title=substr($line,2);}
+    if(preg_match("/define\('([^']*)', *'([^']*)'\); *\/\/(.*)/", $line, $matches))
+    {
+      if($title!=''){print('<h1>'.$title.'</h1>'); $title='';}
+      $key=$matches[1];
+      $default=$matches[2];
+      $name=$matches[3];
+      if($key=='DOMAIN'){$default=$_SERVER['HTTP_HOST'];} // Special defaults
+      if($key=='BASEURL'){$default=$baseurl;}
+      if($optionpos=strpos($name, '[')) // Dropdown for options
+      {
+        $options=substr($name, $optionpos+1);
+        if($end=strpos($options, ']')){$options=substr($options,0,$end);}
+        $options=explode(',', $options);
+        $name=substr($name, 0, $optionpos);
+        print($name.': <select name="'.$key.'">');
+        foreach($options as $option)
+        {
+          $optiontrim=$option;
+          if($end=strpos($option, '(')){$optiontrim=substr($option,0,$end);}
+          $sel=($optiontrim==$default?' selected':'');
+          print('<option value="'.trim($optiontrim).'"'.$sel.'>'.$option.'</option>');
+        }
+        print('</select><br />');
+      }else{ // Regular text input
+        print($name.': <input type="text" name="'.$key.'" value="'.$default.'" /><br />');
+      }
+    }
+  }
+  print('<button>Continue</button></form>');
+}else{
+  // Step 4: Write config.php based on config.php.sample and the submitted values
+// TODO: Sanity check on the provided values (database info, tmpdir)
+  $config=file_get_contents('config.php.sample');
+  foreach($_POST as $key=>$value)
+  {
+    $config=preg_replace("/define\('".$key."', *'[^']*'\)/", "define('".$key."', '".$value."')", $config);
+  }
+  file_put_contents('config.php', $config);
+  print('<h1>Done!</h1>');
+  print('Your Thingshare instance is now live.<br />');
+  print('<a href="'.$_POST['BASEURL'].'/register">Click here</a> to register the first account, which will get the administrative privileges');
+  // Step 5: Initiate database
+  include_once('db.php');
+  create_db_tables();
+  // Generate and store key, used to verify remote activities of local users
+  $config = array(
+    'digest_alg'=>'sha512', // TODO: Is there a better digest for this? Would using HASH from config.php be a good idea? (I suspect not)
+    'private_key_bits'=>4096,
+    'private_key_type'=>OPENSSL_KEYTYPE_RSA,
+  );
+  $res=openssl_pkey_new($config);
+  openssl_pkey_export($res, $pem); // Store this in DB
+  setoption('rpckey', $pem);
+  $res=openssl_pkey_get_details($res);//['key'];
+  file_put_contents('rpckey.pem', $res['key']);
+  // Insert some default allowed filetypes
+  foreach(Array(
+    // Meshes
+    '3mf'=>'model/3mf',
+    'obj'=>'model/obj',
+    'stl'=>'model/stl',
+    'x3d'=>'model/x3d+xml',
+    // Interchange formats
+    'iges'=>'model/iges',
+    'step'=>'application/step',
+    'stp'=>'application/step',
+    // Source files
+    'blend'=>'application/x-blender',
+    'blender'=>'application/x-blender',
+    'fcstd'=>'application/x-extension-fcstd',
+    'scad'=>'application/x-openscad',
+    // Images
+    'gif'=>'image/gif',
+    'jpeg'=>'image/jpeg',
+    'jpg'=>'image/jpeg',
+    'png'=>'image/png',
+    'svg'=>'image/svg+xml',
+    'txt'=>'text/plain') as $ext=>$mime)
+  {
+    mysqli_query($db, 'insert into filetypes(extension, mimetype) values("'.$ext.'", "'.$mime.'")');
+  }
+  // Insert some sane default licenses, TODO: Include CC0? Or maybe not, CC themselves make a rather big deal out of it and it seems to be somewhat country-specific
+  foreach(Array(
+    Array('Creative Commons BY 4.0',
+          'Free to share, use for commercial purposes, and create derivative works, requiring attribution',
+          'https://creativecommons.org/licenses/by/4.0/'),
+    Array('Creative Commons BY-SA 4.0',
+          'Free to share, use for commercial purposes, and create derivative works, requiring attribution and that derivative works use the same license',
+          'https://creativecommons.org/licenses/by-sa/4.0/', true),
+    Array('Creative Commons BY-ND 4.0',
+          'Free to share and use for commercial purposes, requiring attribution, forbidding derivative works',
+          'https://creativecommons.org/licenses/by-nd/4.0/'),
+    Array('Creative Commons BY-NC 4.0',
+          'Free to share and create derivative works, requiring attribution, forbidding commercial use',
+          'https://creativecommons.org/licenses/by-nc/4.0/'),
+    Array('Creative Commons BY-NC-SA 4.0',
+          'Free to share and create derivative works, requiring attribution and that derivative works use the same license, forbidding commercial use',
+          'https://creativecommons.org/licenses/by-nc-sa/4.0/'),
+    Array('Creative Commons BY-NC-ND 4.0',
+          'Free to share, requiring attribution, forbidding commercial use and derivative works',
+          'https://creativecommons.org/licenses/by-nc-nd/4.0/'),
+    Array('AGPL 3.0',
+          'Free to share, use for commercial purposes, and create derivative works, requiring attribution, source files, and that derivative works use the same license. Considers remote interaction equivalent to distribution',
+          'https://www.gnu.org/licenses/agpl-3.0.txt'),
+    Array('GPL 3.0',
+          'Free to share, use for commercial purposes, and create derivative works, requiring attribution, source files, and that derivative works use the same license',
+          'https://www.gnu.org/licenses/gpl-3.0.txt'),
+    ) as $license)
+  {
+    $name=mysqli_real_escape_string($db, $license[0]);
+    $simple=mysqli_real_escape_string($db, $license[1]);
+    $full=mysqli_real_escape_string($db, $license[2]);
+    $default=((isset($license[3]) && $license[3])?'true':'false');
+    mysqli_query($db, 'insert into licenses(name, simple, full, removed, defaultlicense) values("'.$name.'", "'.$simple.'", "'.$full.'", false, '.$default.')');
+  }
+}
+?>
diff --git a/style.css b/style.css
new file mode 100644
index 0000000..b4efb05
--- /dev/null
+++ b/style.css
@@ -0,0 +1,152 @@
+/*
+    This file is part of Thingshare, a federated system for sharing data for home manufacturing (e.g. 3D models to 3D print)
+    https://thingshare.ion.nu/
+    Copyright (C) 2020  Alicia <...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+body {
+  margin:0px;
+  font-family:arial,sans;
+}
+#logo {
+  height:60px;
+  background-color:#00ff00;
+}
+#user {
+  float:right;
+}
+#search {
+  float:right;
+  padding-top:0px;
+}
+#search input {
+  vertical-align:top;
+}
+#search button {
+  padding:0px;
+  border:none;
+  background:transparent;
+  height:100%;
+}
+#search button>img {
+  height:calc(1em + 10px);
+  margin-top:5px;
+}
+#menu>a {
+  margin-left:10px;
+}
+#user>a {
+  margin-right:10px;
+}
+#loginform {
+/* This doesn't work as intended, but it seems to work ok for now */
+  padding-top:12%;
+}
+.error {
+  color:#f00000;
+}
+#content {
+  width:80%;
+  margin-left:auto;
+  margin-right:auto;
+  margin-top:10px;
+}
+small.subheader {
+  color:#a0a0a0;
+  font-size:14px;
+}
+div.thing {
+  display:inline-block;
+  width:240px;
+  height:240px;
+  border:solid 1px #000000;
+  margin:5px;
+  vertical-align:top;
+  position:relative;
+}
+div.thing-add {
+  text-align:center;
+}
+div.thing-add>a {
+  font-size:240px;
+  text-decoration:none;
+}
+div.paragraph {
+  margin-top:14px;
+  margin-bottom:14px;
+}
+nav {
+  background: #d0d0d0; /* For non-css3 browsers */
+  background: -webkit-linear-gradient(#e0e0e0, #c0c0c0);
+  background: -o-linear-gradient(#e0e0e0, #c0c0c0);
+  background: -moz-linear-gradient(#e0e0e0, #c0c0c0);
+  background: linear-gradient(#e0e0e0, #c0c0c0);
+}
+nav>div {
+  padding: 10px;
+  display:inline-block;
+}
+nav>div>a {
+  color:#000000;
+}
+div.boxbottom {
+  position:absolute;
+  bottom:0px;
+  text-align:center;
+  width:100%;
+  background-color:#ffffffa0;
+}
+div.boxtop {
+  position:absolute;
+  top:0px;
+  background-color:#ffffffa0;
+}
+div.thing>a>img {
+  width:100%;
+  height:100%;
+  object-fit:contain;
+}
+span.blacklist {
+  background-color:#ff0000;
+}
+div.sidebar {
+  float:left;
+  width:240px;
+  margin:5px;
+  border:solid 1px #ffffff;
+}
+span.code {
+  font-family:monospace;
+  background-color:#00ff0040;
+}
+div.footer {
+  padding-top:80px;
+  width:80%;
+  margin-left:auto;
+  margin-right:auto;
+  padding-bottom:20px;
+  clear:both;
+}
+div.c2 {
+  display:inline-block;
+  width:50%;
+  vertical-align:top;
+}
+table {
+  width:100%;
+}
+tr:nth-child(even) {
+  background-color:#e8e8e8;
+}
diff --git a/thing.php b/thing.php
new file mode 100644
index 0000000..f2a0b68
--- /dev/null
+++ b/thing.php
@@ -0,0 +1,62 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('head.php');
+include_once('db.php');
+include_once('rpc.php');
+$thing=explode('@',$path[2]);
+$thingobj=rpc_get($thing[1], 'thing/'.$thing[0]);
+if(isset($thingobj['error']))
+{
+  print('<div class="error"><h1>'.$thingobj['error'].'</h1></div>');
+  include_once('foot.php');
+  exit();
+}
+$name=htmlentities($thingobj['name']);
+$license=$thingobj['license']['name'];
+if($license=='other')
+{
+  $license='Other, see description';
+}else{
+  $simple=(isset($thingobj['license']['simple'])?' title="'.htmlentities($thingobj['license']['simple']).'"':'');
+  $license='<a href="https://'.$thing[1].'/license/'.urlencode($license).'"'.$simple.'>'.htmlentities($license).'</a>';
+}
+include_once('parsedown/Parsedown.php');
+$md=new Parsedown();
+$description=$md->text($thingobj['description']);
+if(isset($_SESSION['name']))
+{
+  if($thing[1]==DOMAIN && $thingobj['by']['name']==$_SESSION['name'])
+  {
+    $description.='<a href="'.BASEURL.'/editthing/'.$thing[0].'">'._('Edit').'</a>';
+  }else{
+    $description.='<...>'._('Report').'</a>';
+  }
+}
+$files='';
+foreach($thingobj['files'] as $file)
+{
+  $type=(isset($file['type'])?$file['type']:'unknown');
+  $files.='<div class="thing"><a href="https://'.$thing[1].$file['path'].'" download="'.htmlentities($file['name']).'" type="'.$type.'"><div class="boxbottom">'.htmlentities($file['name']).'</div><img src="https://'.$thing[1].$file['preview'].'" /></a></div>';
+}
+?>
+<h1><?=$name?> <small class="subheader">by <a href="<?=BASEURL?>/user/<?=$thingobj['by']['name']?>@<?=$thing[1]?>" title="<?=$thingobj['by']['name']?>@<?=$thing[1]?>"><?=htmlentities($thingobj['by']['displayname'])?></a></small></h1>
+<small><?=sprintf(_('Published on %s under the license %s'), htmlentities($thingobj['date']), $license)?></small><br />
+<?=$description?><br />
+<?=$files?>
diff --git a/user.php b/user.php
new file mode 100644
index 0000000..84d2d27
--- /dev/null
+++ b/user.php
@@ -0,0 +1,61 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+include_once('head.php');
+include_once('db.php');
+include_once('rpc.php');
+$user=explode('@',$path[2]);
+$userobj=rpc_get($user[1], 'user/'.$user[0]);
+if(isset($userobj['error']))
+{
+  print('<div class="error">'.$userobj['error'].'</div>');
+  include_once('foot.php');
+  exit();
+}
+$displayname=htmlentities($userobj['displayname']);
+$username=htmlentities(implode('@',$user));
+include_once('parsedown/Parsedown.php');
+$md=new Parsedown();
+$profile=$md->text($userobj['profile']);
+$things='';
+if($user[1]==DOMAIN && $user[0]==$_SESSION['name'])
+{
+  $profile.='<a href="'.BASEURL.'/editprofile">'._('Edit').'</a>';
+  $things='<div class="thing thing-add"><a href="'.BASEURL.'/editthing/new">+</a></div>';
+}
+if(isset($userobj['banned']) && $userobj['banned'])
+{
+  $unban='';
+  if($user[1]==DOMAIN && $privileges&PRIV_MODERATE)
+  {
+    include_once('nonce.php');
+    $unban='<form method="post" action="'.BASEURL.'/admin/moderate">'.nonce().'<button name="unban" value="'.htmlentities($user[0]).'">'._('Unban').'</button></form>';
+  }
+  $profile=_('This user has been banned.').$unban.'<br />'.$profile;
+}
+// Iterate through 'things'
+foreach($userobj['things'] as $thing)
+{
+  $things.='<div class="thing"><...><div class="boxbottom">'.htmlentities($thing['name']).'</div><img src="https://'.$user[1].$thing['preview'].'" /></a></div>';
+}
+// TODO: Profile picture?
+?>
+<h1><?=$displayname?> <small class="subheader"><?=$username?></small></h1>
+<?=$profile?><br />
+<?=$things?>
diff --git a/verifyemail.php b/verifyemail.php
new file mode 100644
index 0000000..2e85c71
--- /dev/null
+++ b/verifyemail.php
@@ -0,0 +1,54 @@
+<...>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+*/
+$error='';
+if(!isset($_GET['u']) || !isset($_GET['c']))
+{
+  $error=_('No verification code specified');
+}else{
+  include_once('db.php');
+  $user=mysqli_real_escape_string($db, $_GET['u']);
+  $res=mysqli_query($db, 'select salt, email, status, id from users where name="'.$user.'"');
+  $res=mysqli_fetch_assoc($res);
+  if($res['status']!=ACCOUNT_EMAILUNVERIFIED)
+  {
+    $error=_('This e-mail address is already verified');
+  }else{
+    $salt=$res['salt'];
+    $email=$res['email'];
+    $error=_('Invalid verification code');
+    foreach(Array(-1,0,1) as $day) // Allow some drift for timezone borders
+    {
+      $verifycode=hash(HASH, $email.$salt.date('j', time()+(24*3600)*$day));
+      if($_GET['c']==$verifycode)
+      {
+        $error='';
+        mysqli_query($db, 'update users set status='.(int)ACCOUNT_ACTIVE.' where id='.(int)$res['id']);
+      }
+    }
+  }
+}
+include_once('head.php');
+if($error!='')
+{
+  print('<center><div class="error">'.$error.'</div></center>');
+}else{
+  print('<center><h1>'._('Verification complete').'</h1>You may now <a href="'.BASEURL.'/login">log in</a></center>');
+}
+?>