[CORE] Add ActivityPub plugin

This is not the same as the one in https://notabug.org/diogo/gnu-social-activitypub-plugin
Differences to the first "release"
-> Doesn't use guzzle nor has any composer dependencies
-> Supports HTTP Signatures
-> Has basic l10n/i18n
-> Some minor bug fixes
This commit is contained in:
Diogo Cordeiro 2019-05-11 12:27:21 +01:00
parent c0950c5fc6
commit 2ad4fa99ed
50 changed files with 7823 additions and 0 deletions

View File

@ -352,6 +352,7 @@ $default =
'Embed' => array(), 'Embed' => array(),
'OpenID' => array(), 'OpenID' => array(),
'OpportunisticQM' => array(), 'OpportunisticQM' => array(),
'ActivityPub' => array(),
'OStatus' => array(), 'OStatus' => array(),
'Poll' => array(), 'Poll' => array(),
'SimpleCaptcha' => array(), 'SimpleCaptcha' => array(),

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,93 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
# Coding Style
- We follow every [PSR-2](https://www.php-fig.org/psr/psr-2/) ...
- ... except camelCase, that's too bad, we use snake_case
## Merge Request Process
1. Ensure you strip any trailing spaces off
2. Increase the version numbers in any examples files and the README.md to the new version that this
Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
3. You may merge the Pull Request in once you have the sign-off of two other developers, or if you
do not have permission to do that, you may request the second reviewer to merge it for you.
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at diogo@fc.up.pt. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

661
plugins/ActivityPub/COPYING Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU 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 <http://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
<http://www.gnu.org/licenses/>.

View File

@ -0,0 +1,42 @@
# ActivityPub plugin for GNU social
(c) 2018-2019 Free Software Foundation, Inc
This is the README file for GNU social's ActivityPub plugin.
It includes general information about the plugin.
## About
This plugin adds [ActivityPub](https://www.w3.org/TR/activitypub/) support to GNU social.
## Credits
* **[Diogo Cordeiro](https://www.diogo.site/)**
## Special thanks
* **[Daniel Supernault](https://github.com/dansup)**
* **[Mikael Nordfeldth](https://mmn-o.se/)**
## License
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, in the file "COPYING". If not, see
<http://www.gnu.org/licenses/>.
IMPORTANT NOTE: The GNU Affero General Public License (AGPL) has
*different requirements* from the "regular" GPL. In particular, if
you make modifications to the plugin source code on your server,
you *MUST MAKE AVAILABLE* the modified version of the source code
to your users under the same license. This is a legal requirement
of using the software, and if you do not wish to share your
modifications, *YOU MAY NOT USE THIS PLUGIN*.

View File

@ -0,0 +1,134 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Actor's Followers Collection
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apActorFollowersAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Followers Collection request
*
* @return void
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function handle()
{
try {
$profile = Profile::getByID($this->trimmed('id'));
$profile_id = $profile->getID();
} catch (Exception $e) {
ActivityPubReturn::error('Invalid Actor URI.', 404);
}
if (!$profile->isLocal()) {
ActivityPubReturn::error("This is not a local user.", 403);
}
if (!isset($_GET["page"])) {
$page = 0;
} else {
$page = intval($this->trimmed('page'));
}
if ($page < 0) {
ActivityPubReturn::error('Invalid page number.');
}
$since = ($page - 1) * PROFILES_PER_MINILIST;
$limit = (($page - 1) == 0 ? 1 : $page) * PROFILES_PER_MINILIST;
/* Calculate total items */
$total_subs = $profile->subscriberCount();
$total_pages = ceil($total_subs / PROFILES_PER_MINILIST);
$res = [
'@context' => [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1",
],
'id' => common_local_url('apActorFollowers', ['id' => $profile_id]).(($page != 0) ? '?page='.$page : ''),
'type' => ($page == 0 ? 'OrderedCollection' : 'OrderedCollectionPage'),
'totalItems' => $total_subs
];
if ($page == 0) {
$res['first'] = common_local_url('apActorFollowers', ['id' => $profile_id]).'?page=1';
} else {
$res['orderedItems'] = $this->generate_followers($profile, $since, $limit);
$res['partOf'] = common_local_url('apActorFollowers', ['id' => $profile_id]);
if ($page+1 < $total_pages) {
$res['next'] = common_local_url('apActorFollowers', ['id' => $profile_id]).'page='.($page+1 == 1 ? 2 : $page+1);
}
if ($page > 1) {
$res['prev'] = common_local_url('apActorFollowers', ['id' => $profile_id]).'?page='.($page-1 <= 0 ? 1 : $page-1);
}
}
ActivityPubReturn::answer($res);
}
/**
* Generates a list of stalkers for a given profile.
*
* @param Profile $profile
* @param int $since
* @param int $limit
* @return array of URIs
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function generate_followers($profile, $since, $limit)
{
/* Fetch Followers */
try {
$sub = $profile->getSubscribers($since, $limit);
} catch (NoResultException $e) {
// Just let the exception go on its merry way
}
/* Get followers' URLs */
$subs = [];
while ($sub->fetch()) {
$subs[] = ActivityPubPlugin::actor_uri($sub);
}
return $subs;
}
}

View File

@ -0,0 +1,133 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Actor's Following Collection
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apActorFollowingAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Following Collection request
*
* @return void
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function handle()
{
try {
$profile = Profile::getByID($this->trimmed('id'));
$profile_id = $profile->getID();
} catch (Exception $e) {
ActivityPubReturn::error('Invalid Actor URI.', 404);
}
if (!$profile->isLocal()) {
ActivityPubReturn::error("This is not a local user.", 403);
}
if (!isset($_GET["page"])) {
$page = 0;
} else {
$page = intval($this->trimmed('page'));
}
if ($page < 0) {
ActivityPubReturn::error('Invalid page number.');
}
$since = ($page - 1) * PROFILES_PER_MINILIST;
$limit = (($page - 1) == 0 ? 1 : $page) * PROFILES_PER_MINILIST;
/* Calculate total items */
$total_subs = $profile->subscriptionCount();
$total_pages = ceil($total_subs / PROFILES_PER_MINILIST);
$res = [
'@context' => [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1",
],
'id' => common_local_url('apActorFollowing', ['id' => $profile_id]).(($page != 0) ? '?page='.$page : ''),
'type' => ($page == 0 ? 'OrderedCollection' : 'OrderedCollectionPage'),
'totalItems' => $total_subs
];
if ($page == 0) {
$res['first'] = common_local_url('apActorFollowing', ['id' => $profile_id]).'?page=1';
} else {
$res['orderedItems'] = $this->generate_following($profile, $since, $limit);
$res['partOf'] = common_local_url('apActorFollowing', ['id' => $profile_id]);
if ($page+1 < $total_pages) {
$res['next'] = common_local_url('apActorFollowing', ['id' => $profile_id]).'page='.($page+1 == 1 ? 2 : $page+1);
}
if ($page > 1) {
$res['prev'] = common_local_url('apActorFollowing', ['id' => $profile_id]).'?page='.($page-1 <= 0 ? 1 : $page-1);
}
}
ActivityPubReturn::answer($res);
}
/**
* Generates the list of those a given profile is stalking.
*
* @param Profile $profile
* @param int $since
* @param int $limit
* @return array of URIs
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function generate_following($profile, $since, $limit)
{
/* Fetch Following */
try {
$sub = $profile->getSubscribed($since, $limit);
} catch (NoResultException $e) {
// Just let the exception go on its merry way
}
/* Get followed' URLs */
$subs = [];
while ($sub->fetch()) {
$subs[] = ActivityPubPlugin::actor_uri($sub);
}
return $subs;
}
}

View File

@ -0,0 +1,153 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Actor's Liked Collection
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apActorLikedAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Liked Collection request
*
* @return void
* @throws EmptyPkeyValueException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function handle()
{
try {
$profile = Profile::getByID($this->trimmed('id'));
$profile_id = $profile->getID();
} catch (Exception $e) {
ActivityPubReturn::error('Invalid Actor URI.', 404);
}
if (!$profile->isLocal()) {
ActivityPubReturn::error("This is not a local user.", 403);
}
$limit = intval($this->trimmed('limit'));
$since_id = intval($this->trimmed('since_id'));
$max_id = intval($this->trimmed('max_id'));
$limit = empty($limit) ? 40 : $limit; // Default is 40
$since_id = empty($since_id) ? null : $since_id;
$max_id = empty($max_id) ? null : $max_id;
// Max is 80
if ($limit > 80) {
$limit = 80;
}
$fave = $this->fetch_faves($profile_id, $limit, $since_id, $max_id);
$faves = array();
while ($fave->fetch()) {
$faves[] = $this->pretty_fave(clone ($fave));
}
$res = [
'@context' => [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1",
],
'id' => common_local_url('apActorLiked', ['id' => $profile_id]),
'type' => 'OrderedCollection',
'totalItems' => Fave::countByProfile($profile),
'orderedItems' => $faves
];
ActivityPubReturn::answer($res);
}
/**
* Take a fave object and turns it in a pretty array to be used
* as a plugin answer
*
* @param Fave $fave_object
* @return array pretty array representating a Fave
* @throws EmptyPkeyValueException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function pretty_fave($fave_object)
{
$res = [
'created' => $fave_object->created,
'object' => Activitypub_notice::notice_to_array(Notice::getByID($fave_object->notice_id))
];
return $res;
}
/**
* Fetch faves
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param int $user_id
* @param int $limit
* @param int $since_id
* @param int $max_id
* @return Fave fetchable fave collection
*/
private static function fetch_faves(
$user_id,
$limit = 40,
$since_id = null,
$max_id = null
) {
$fav = new Fave();
$fav->user_id = $user_id;
$fav->orderBy('modified DESC');
if ($since_id != null) {
$fav->whereAdd("notice_id > {$since_id}");
}
if ($max_id != null) {
$fav->whereAdd("notice_id < {$max_id}");
}
$fav->limit($limit);
$fav->find();
return $fav;
}
}

View File

@ -0,0 +1,134 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Inbox Request Handler
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apActorOutboxAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Outbox request
*
* @author Daniel Supernault <danielsupernault@gmail.com>
*/
protected function handle()
{
try {
$profile = Profile::getByID($this->trimmed('id'));
$profile_id = $profile->getID();
} catch (Exception $e) {
ActivityPubReturn::error('Invalid Actor URI.', 404);
}
if (!$profile->isLocal()) {
ActivityPubReturn::error("This is not a local user.", 403);
}
if (!isset($_GET["page"])) {
$page = 0;
} else {
$page = intval($this->trimmed('page'));
}
if ($page < 0) {
ActivityPubReturn::error('Invalid page number.');
}
$since = ($page - 1) * PROFILES_PER_MINILIST;
$limit = (($page - 1) == 0 ? 1 : $page) * PROFILES_PER_MINILIST;
/* Calculate total items */
$total_notes = $profile->noticeCount();
$total_pages = ceil($total_notes / PROFILES_PER_MINILIST);
$res = [
'@context' => [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1",
],
'id' => common_local_url('apActorOutbox', ['id' => $profile_id]).(($page != 0) ? '?page='.$page : ''),
'type' => ($page == 0 ? 'OrderedCollection' : 'OrderedCollectionPage'),
'totalItems' => $total_notes
];
if ($page == 0) {
$res['first'] = common_local_url('apActorOutbox', ['id' => $profile_id]).'?page=1';
} else {
$res['orderedItems'] = $this->generate_outbox($profile);
$res['partOf'] = common_local_url('apActorOutbox', ['id' => $profile_id]);
if ($page+1 < $total_pages) {
$res['next'] = common_local_url('apActorOutbox', ['id' => $profile_id]).'page='.($page+1 == 1 ? 2 : $page+1);
}
if ($page > 1) {
$res['prev'] = common_local_url('apActorOutbox', ['id' => $profile_id]).'?page='.($page-1 <= 0 ? 1 : $page-1);
}
}
ActivityPubReturn::answer($res);
}
/**
* Generates a list of people following given profile.
*
* @param Profile $profile
* @return array of Notices
* @throws EmptyPkeyValueException
* @throws InvalidUrlException
* @throws ServerException
* @author Daniel Supernault <danielsupernault@gmail.com>
*/
public function generate_outbox($profile)
{
/* Fetch Notices */
$notices = [];
$notice = $profile->getNotices();
while ($notice->fetch()) {
$note = $notice;
// TODO: Handle other types
if ($note->object_type == 'http://activitystrea.ms/schema/1.0/note') {
$notices[] = Activitypub_create::create_to_array(
ActivityPubPlugin::actor_uri($note->getProfile()),
Activitypub_notice::notice_to_array($note)
);
}
}
return $notices;
}
}

View File

@ -0,0 +1,75 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Actor's profile (Local users only)
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apActorProfileAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Actor Profile request
*
* @return void
* @throws InvalidUrlException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function handle()
{
if (!empty($id = $this->trimmed('id'))) {
try {
$profile = Profile::getByID($id);
} catch (Exception $e) {
ActivityPubReturn::error('Invalid Actor URI.', 404);
}
unset($id);
} else {
try {
$profile = User::getByNickname($this->trimmed('nickname'))->getProfile();
} catch (Exception $e) {
ActivityPubReturn::error('Invalid username.', 404);
}
}
if (!$profile->isLocal()) {
ActivityPubReturn::error("This is not a local user.", 403);
}
$res = Activitypub_profile::profile_to_array($profile);
ActivityPubReturn::answer($res, 200);
}
}

View File

@ -0,0 +1,135 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Inbox Request Handler
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apInboxAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Inbox request
*
* @return void
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function handle()
{
$path = !empty($this->trimmed('id')) ? common_local_url('apInbox', ['id' => $this->trimmed('id')]) : common_local_url('apInbox');
$path = parse_url($path, PHP_URL_PATH);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
ActivityPubReturn::error('Only POST requests allowed.');
}
common_debug('ActivityPub Inbox: Received a POST request.');
$body = $data = file_get_contents('php://input');
common_debug('ActivityPub Inbox: Request contents: '.$data);
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['actor'])) {
ActivityPubReturn::error('Actor not found in the request.');
}
$actor = Activitypub_explorer::get_profile_from_url($data['actor']);
$aprofile = Activitypub_profile::from_profile($actor);
$actor_public_key = new Activitypub_rsa();
$actor_public_key = $actor_public_key->ensure_public_key($actor);
common_debug('ActivityPub Inbox: HTTP Signature: Validation will now start!');
$headers = $this->get_all_headers();
common_debug('ActivityPub Inbox: Request Headers: '.print_r($headers, true));
if (!isset($headers['signature'])) {
common_debug('ActivityPub Inbox: HTTP Signature: Missing Signature header.');
ActivityPubReturn::error('Missing Signature header.', 400);
}
// Extract the signature properties
$signatureData = HTTPSignature::parseSignatureHeader($headers['signature']);
common_debug('ActivityPub Inbox: HTTP Signature Data: '.print_r($signatureData, true));
if (isset($signatureData['error'])) {
common_debug('ActivityPub Inbox: HTTP Signature: '.json_encode($signatureData, true));
ActivityPubReturn::error(json_encode($signatureData, true), 400);
}
list($verified, $headers) = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
// If the signature fails verification the first time, update profile as it might have change public key
if($verified !== 1) {
$res = Activitypub_explorer::get_remote_user_activity($aprofile->getUri());
$actor = Activitypub_profile::update_profile($aprofile, $res);
$actor_public_key = new Activitypub_rsa();
$actor_public_key = $actor_public_key->ensure_public_key($actor);
list($verified, $headers) = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
}
// If it still failed despite profile update
if($verified !== 1) {
common_debug('ActivityPub Inbox: HTTP Signature: Invalid signature.');
ActivityPubReturn::error('Invalid signature.');
}
// HTTP signature checked out, make sure the "actor" of the activity matches that of the signature
common_debug('ActivityPub Inbox: HTTP Signature: Authorized request. Will now start the inbox handler.');
try {
new Activitypub_inbox_handler($data, $actor);
ActivityPubReturn::answer();
} catch (Exception $e) {
ActivityPubReturn::error($e->getMessage());
}
}
/**
* Get all HTTP header key/values as an associative array for the current request.
*
* @return array [string] The HTTP header key/value pairs.
* @author PHP Manual Contributed Notes <joyview@gmail.com>
*/
private function get_all_headers()
{
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[strtolower(str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))))] = $value;
}
}
return $headers;
}
}

View File

@ -0,0 +1,67 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Notice (Local notices only)
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class apNoticeAction extends ManagedAction
{
protected $needLogin = false;
protected $canPost = true;
/**
* Handle the Notice request
*
* @return void
* @throws EmptyPkeyValueException
* @throws InvalidUrlException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
protected function handle()
{
try {
$notice = Notice::getByID($this->trimmed('id'));
} catch (Exception $e) {
ActivityPubReturn::error('Invalid Notice URI.', 404);
}
if (!$notice->isLocal()) {
ActivityPubReturn::error("This is not a local notice.", 403);
}
$res = Activitypub_notice::notice_to_array($notice);
ActivityPubReturn::answer($res);
}
}

View File

@ -0,0 +1,86 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_accept extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Accept
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array $object
* @return array pretty array to be used in a response
*/
public static function accept_to_array($object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => common_root_url().'accept_follow_from_'.urlencode($object['actor']).'_to_'.urlencode($object['object']),
'type' => 'Accept',
'actor' => $object['object'],
'object' => $object
];
return $res;
}
/**
* Verifies if a given object is acceptable for an Accept Activity.
*
* @param array $object
* @return bool
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function validate_object($object)
{
if (!is_array($object)) {
throw new Exception('Invalid Object Format for Accept Activity.');
}
if (!isset($object['type'])) {
throw new Exception('Object type was not specified for Accept Activity.');
}
switch ($object['type']) {
case 'Follow':
// Validate data
if (!filter_var($object['object'], FILTER_VALIDATE_URL)) {
throw new Exception("Object is not a valid Object URI for Activity.");
}
break;
default:
throw new Exception('This is not a supported Object Type for Accept Activity.');
}
return true;
}
}

View File

@ -0,0 +1,57 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_announce extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Announce
*
* @param $actor
* @param array $object
* @return array pretty array to be used in a response
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function announce_to_array($actor, $object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
"type" => "Announce",
"actor" => $actor,
"object" => $object
];
return $res;
}
}

View File

@ -0,0 +1,67 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub Attachment representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_attachment extends Managed_DataObject
{
/**
* Generates a pretty array from an Attachment object
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param Attachment $attachment
* @return array pretty array to be used in a response
*/
public static function attachment_to_array($attachment)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'type' => 'Document',
'mediaType' => $attachment->mimetype,
'url' => $attachment->getUrl(),
'size' => $attachment->getSize(),
'name' => $attachment->getTitle(),
];
// Image
if (substr($res["mediaType"], 0, 5) == "image") {
$res["meta"]= [
'width' => $attachment->width,
'height' => $attachment->height
];
}
return $res;
}
}

View File

@ -0,0 +1,85 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_create extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Create
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $actor
* @param array $object
* @return array pretty array to be used in a response
*/
public static function create_to_array($actor, $object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => $object['id'].'/create',
'type' => 'Create',
'to' => $object['to'],
'cc' => $object['cc'],
'actor' => $actor,
'object' => $object
];
return $res;
}
/**
* Verifies if a given object is acceptable for a Create Activity.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array $object
* @throws Exception
*/
public static function validate_object($object)
{
if (!is_array($object)) {
throw new Exception('Invalid Object Format for Create Activity.');
}
if (!isset($object['type'])) {
throw new Exception('Object type was not specified for Create Activity.');
}
switch ($object['type']) {
case 'Note':
// Validate data
Activitypub_notice::validate_note($object);
break;
default:
throw new Exception('This is not a supported Object Type for Create Activity.');
}
}
}

View File

@ -0,0 +1,58 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_delete extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Delete
*
* @param $actor
* @param array $object
* @return array pretty array to be used in a response
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function delete_to_array($actor, $object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => $object.'/delete',
'type' => 'Delete',
'actor' => $actor,
'object' => $object
];
return $res;
}
}

View File

@ -0,0 +1,53 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_error extends Managed_DataObject
{
/**
* Generates a pretty error from a string
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $m
* @return array pretty array to be used in a response
*/
public static function error_message_to_array($m)
{
$res = [
'error'=> $m
];
return $res;
}
}

View File

@ -0,0 +1,91 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_follow extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a subscription
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $actor
* @param string $object
* @return array pretty array to be used in a response
*/
public static function follow_to_array($actor, $object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => common_root_url().'follow_from_'.urlencode($actor).'_to_'.urlencode($object),
'type' => 'Follow',
'actor' => $actor,
'object' => $object
];
return $res;
}
/**
* Handles a Follow Activity received by our inbox.
*
* @param Profile $actor_profile Remote Actor
* @param string $object Local Actor
* @throws AlreadyFulfilledException
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function follow($actor_profile, $object)
{
// Get Actor's Aprofile
$actor_aprofile = Activitypub_profile::from_profile($actor_profile);
// Get Object profile
$object_profile = new Activitypub_explorer;
$object_profile = $object_profile->lookup($object)[0];
if (!Subscription::exists($actor_profile, $object_profile)) {
Subscription::start($actor_profile, $object_profile);
common_debug('ActivityPubPlugin: Accepted Follow request from '.ActivityPubPlugin::actor_uri($actor_profile).' to '.$object);
} else {
common_debug('ActivityPubPlugin: Received a repeated Follow request from '.ActivityPubPlugin::actor_uri($actor_profile).' to '.$object);
}
// Notify remote instance that we have accepted their request
common_debug('ActivityPubPlugin: Notifying remote instance that we have accepted their Follow request request from '.ActivityPubPlugin::actor_uri($actor_profile).' to '.$object);
$postman = new Activitypub_postman($actor_profile, [$actor_aprofile]);
$postman->accept_follow();
}
}

View File

@ -0,0 +1,58 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_like extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Like
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $actor Actor URI
* @param string $object Notice URI
* @return array pretty array to be used in a response
*/
public static function like_to_array($actor, $object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => common_root_url().'like_from_'.urlencode($actor).'_to_'.urlencode($object),
"type" => "Like",
"actor" => $actor,
"object" => $object
];
return $res;
}
}

View File

@ -0,0 +1,57 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub Mention Tag representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_mention_tag extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Mention Tag
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $href Actor Uri
* @param array $name Mention name
* @return array pretty array to be used in a response
*/
public static function mention_tag_to_array_from_values($href, $name)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
"type" => "Mention",
"href" => $href,
"name" => $name
];
return $res;
}
}

View File

@ -0,0 +1,252 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub notice representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_notice extends Managed_DataObject
{
/**
* Generates a pretty notice from a Notice object
*
* @param Notice $notice
* @return array array to be used in a response
* @throws EmptyPkeyValueException
* @throws InvalidUrlException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function notice_to_array($notice)
{
$profile = $notice->getProfile();
$attachments = [];
foreach ($notice->attachments() as $attachment) {
$attachments[] = Activitypub_attachment::attachment_to_array($attachment);
}
$tags = [];
foreach ($notice->getTags() as $tag) {
if ($tag != "") { // Hacky workaround to avoid stupid outputs
$tags[] = Activitypub_tag::tag_to_array($tag);
}
}
$cc = [common_local_url('apActorFollowers', ['id' => $profile->getID()])];
foreach ($notice->getAttentionProfiles() as $to_profile) {
$cc[] = $href = $to_profile->getUri();
$tags[] = Activitypub_mention_tag::mention_tag_to_array_from_values($href, $to_profile->getNickname().'@'.parse_url($href, PHP_URL_HOST));
}
// In a world without walls and fences, we should make everything Public!
$to[]= 'https://www.w3.org/ns/activitystreams#Public';
$item = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => common_local_url('apNotice', ['id' => $notice->getID()]),
'type' => 'Note',
'published' => str_replace(' ', 'T', $notice->getCreated()).'Z',
'url' => $notice->getUrl(),
'attributedTo' => ActivityPubPlugin::actor_uri($profile),
'to' => ['https://www.w3.org/ns/activitystreams#Public'],
'cc' => $cc,
'atomUri' => $notice->getUrl(),
'conversation' => $notice->getConversationUrl(),
'content' => $notice->getRendered(),
'isLocal' => $notice->isLocal(),
'attachment' => $attachments,
'tag' => $tags
];
// Is this a reply?
if (!empty($notice->reply_to)) {
$item['inReplyTo'] = common_local_url('apNotice', ['id' => $notice->getID()]);
$item['inReplyToAtomUri'] = Notice::getById($notice->reply_to)->getUrl();
}
// Do we have a location for this notice?
try {
$location = Notice_location::locFromStored($notice);
$item['latitude'] = $location->lat;
$item['longitude'] = $location->lon;
} catch (Exception $e) {
// Apparently no.
}
return $item;
}
/**
* Create a Notice via ActivityPub Note Object.
* Returns created Notice.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array $object
* @param Profile|null $actor_profile
* @return Notice
* @throws Exception
*/
public static function create_notice($object, $actor_profile = null)
{
$id = $object['id']; // int
$url = $object['url']; // string
$content = $object['content']; // string
// possible keys: ['inReplyTo', 'latitude', 'longitude']
$settings = [];
if (isset($object['inReplyTo'])) {
$settings['inReplyTo'] = $object['inReplyTo'];
}
if (isset($object['latitude'])) {
$settings['latitude'] = $object['latitude'];
}
if (isset($object['longitude'])) {
$settings['longitude'] = $object['longitude'];
}
// Ensure Actor Profile
if (is_null($actor_profile)) {
$actor_profile = ActivityPub_explorer::get_profile_from_url($object['actor']);
}
$act = new Activity();
$act->verb = ActivityVerb::POST;
$act->time = time();
$act->actor = $actor_profile->asActivityObject();
$act->context = new ActivityContext();
$options = ['source' => 'ActivityPub', 'uri' => $id, 'url' => $url];
// Is this a reply?
if (isset($settings['inReplyTo'])) {
try {
$inReplyTo = ActivityPubPlugin::grab_notice_from_url($settings['inReplyTo']);
$act->context->replyToID = $inReplyTo->getUri();
$act->context->replyToUrl = $inReplyTo->getUrl();
} catch (Exception $e) {
// It failed to grab, maybe we got this note from another source
// (e.g.: OStatus) that handles this differently or we really
// failed to get it...
// Welp, nothing that we can do about, let's
// just fake we don't have such notice.
}
} else {
$inReplyTo = null;
}
// Mentions
$mentions = [];
if (isset($object['tag']) && is_array($object['tag'])) {
foreach ($object['tag'] as $tag) {
if ($tag['type'] == 'Mention') {
$mentions[] = $tag['href'];
}
}
}
$mentions_profiles = [];
$discovery = new Activitypub_explorer;
foreach ($mentions as $mention) {
try {
$mentions_profiles[] = $discovery->lookup($mention)[0];
} catch (Exception $e) {
// Invalid actor found, just let it go. // TODO: Fallback to OStatus
}
}
unset($discovery);
foreach ($mentions_profiles as $mp) {
$act->context->attention[ActivityPubPlugin::actor_uri($mp)] = 'http://activitystrea.ms/schema/1.0/person';
}
// Add location if that is set
if (isset($settings['latitude'], $settings['longitude'])) {
$act->context->location = Location::fromLatLon($settings['latitude'], $settings['longitude']);
}
/* Reject notice if it is too long (without the HTML)
if (Notice::contentTooLong($content)) {
throw new Exception('That\'s too long. Maximum notice size is %d character.');
}*/
$actobj = new ActivityObject();
$actobj->type = ActivityObject::NOTE;
$actobj->content = strip_tags($content, '<p><b><i><u><a><ul><ol><li>');
// Finally add the activity object to our activity
$act->objects[] = $actobj;
$note = Notice::saveActivity($act, $actor_profile, $options);
return $note;
}
/**
* Validates a note.
*
* @param array $object
* @return bool
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function validate_note($object)
{
if (!isset($object['attributedTo'])) {
common_debug('ActivityPub Notice Validator: Rejected because attributedTo was not specified.');
throw new Exception('No attributedTo specified.');
}
if (!isset($object['id'])) {
common_debug('ActivityPub Notice Validator: Rejected because Object ID was not specified.');
throw new Exception('Object ID not specified.');
} elseif (!filter_var($object['id'], FILTER_VALIDATE_URL)) {
common_debug('ActivityPub Notice Validator: Rejected because Object ID is invalid.');
throw new Exception('Invalid Object ID.');
}
if (!isset($object['type']) || $object['type'] !== 'Note') {
common_debug('ActivityPub Notice Validator: Rejected because of Type.');
throw new Exception('Invalid Object type.');
}
if (!isset($object['content'])) {
common_debug('ActivityPub Notice Validator: Rejected because Content was not specified.');
throw new Exception('Object content was not specified.');
}
if (!isset($object['url'])) {
throw new Exception('Object URL was not specified.');
} elseif (!filter_var($object['url'], FILTER_VALIDATE_URL)) {
common_debug('ActivityPub Notice Validator: Rejected because Object URL is invalid.');
throw new Exception('Invalid Object URL.');
}
if (!isset($object['cc'])) {
common_debug('ActivityPub Notice Validator: Rejected because Object CC was not specified.');
throw new Exception('Object CC was not specified.');
}
return true;
}
}

View File

@ -0,0 +1,109 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub's Pending follow requests
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_pending_follow_requests extends Managed_DataObject
{
public $__table = 'activitypub_pending_follow_requests';
public $local_profile_id;
public $remote_profile_id;
private $_reldb = null;
/**
* Return table definition for Schema setup and DB_DataObject usage.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return array array of column definitions
*/
public static function schemaDef()
{
return [
'fields' => [
'local_profile_id' => ['type' => 'integer', 'not null' => true],
'remote_profile_id' => ['type' => 'integer', 'not null' => true],
'relation_id' => ['type' => 'serial', 'not null' => true],
],
'primary key' => ['relation_id'],
'foreign keys' => [
'activitypub_pending_follow_requests_local_profile_id_fkey' => ['profile', ['local_profile_id' => 'id']],
'activitypub_pending_follow_requests_remote_profile_id_fkey' => ['profile', ['remote_profile_id' => 'id']],
],
];
}
public function __construct($actor, $remote_actor)
{
$this->local_profile_id = $actor;
$this->remote_profile_id = $remote_actor;
}
/**
* Add Follow request to table.
*
* @return boolean true if added, false otherwise
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function add()
{
return !$this->exists() && $this->insert();
}
/**
* Check if a Follow request is pending.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return boolean true if is pending, false otherwise
*/
public function exists()
{
$this->_reldb = clone($this);
if ($this->_reldb->find() > 0) {
$this->_reldb->fetch();
return true;
}
return false;
}
/**
* Remove a request from the pending table.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return boolean true if removed, false otherwise
*/
public function remove()
{
return $this->exists() && $this->_reldb->delete();
}
}

View File

@ -0,0 +1,476 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub Profile
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_profile extends Managed_DataObject
{
public $__table = 'activitypub_profile';
public $uri; // text() not_null
public $profile_id; // int(4) primary_key not_null
public $inboxuri; // text() not_null
public $sharedInboxuri; // text()
public $nickname; // varchar(64) multiple_key not_null
public $fullname; // text()
public $profileurl; // text()
public $homepage; // text()
public $bio; // text() multiple_key
public $location; // text()
public $created; // datetime() not_null default_CURRENT_TIMESTAMP
public $modified; // datetime() not_null default_CURRENT_TIMESTAMP
/**
* Return table definition for Schema setup and DB_DataObject usage.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return array array of column definitions
*/
public static function schemaDef()
{
return [
'fields' => [
'uri' => ['type' => 'text', 'not null' => true],
'profile_id' => ['type' => 'integer'],
'inboxuri' => ['type' => 'text', 'not null' => true],
'sharedInboxuri' => ['type' => 'text'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
],
'primary key' => ['profile_id'],
'foreign keys' => [
'activitypub_profile_profile_id_fkey' => ['profile', ['profile_id' => 'id']],
],
];
}
/**
* Generates a pretty profile from a Profile object
*
* @param Profile $profile
* @return array array to be used in a response
* @throws InvalidUrlException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function profile_to_array($profile)
{
$uri = ActivityPubPlugin::actor_uri($profile);
$id = $profile->getID();
$rsa = new Activitypub_rsa();
$public_key = $rsa->ensure_public_key($profile);
unset($rsa);
$res = [
'@context' => [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
[
'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers'
]
],
'id' => $uri,
'type' => 'Person',
'following' => common_local_url('apActorFollowing', ['id' => $id]),
'followers' => common_local_url('apActorFollowers', ['id' => $id]),
'liked' => common_local_url('apActorLiked', ['id' => $id]),
'inbox' => common_local_url('apInbox', ['id' => $id]),
'outbox' => common_local_url('apActorOutbox', ['id' => $id]),
'preferredUsername' => $profile->getNickname(),
'name' => $profile->getBestName(),
'summary' => ($desc = $profile->getDescription()) == null ? "" : $desc,
'url' => $profile->getUrl(),
'manuallyApprovesFollowers' => false,
'publicKey' => [
'id' => $uri."#public-key",
'owner' => $uri,
'publicKeyPem' => $public_key
],
'tag' => [],
'attachment' => [],
'icon' => [
'type' => 'Image',
'mediaType' => 'image/png',
'height' => AVATAR_PROFILE_SIZE,
'width' => AVATAR_PROFILE_SIZE,
'url' => $profile->avatarUrl(AVATAR_PROFILE_SIZE)
]
];
if ($profile->isLocal()) {
$res['endpoints']['sharedInbox'] = common_local_url('apInbox');
} else {
$aprofile = new Activitypub_profile();
$aprofile = $aprofile->from_profile($profile);
$res['endpoints']['sharedInbox'] = $aprofile->sharedInboxuri;
}
return $res;
}
/**
* Insert the current object variables into the database
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @access public
* @throws ServerException
*/
public function do_insert()
{
$profile = new Profile();
$profile->created = $this->created = $this->modified = common_sql_now();
$fields = [
'uri' => 'profileurl',
'nickname' => 'nickname',
'fullname' => 'fullname',
'bio' => 'bio'
];
foreach ($fields as $af => $pf) {
$profile->$pf = $this->$af;
}
$this->profile_id = $profile->insert();
if ($this->profile_id === false) {
$profile->query('ROLLBACK');
throw new ServerException('Profile insertion failed.');
}
$ok = $this->insert();
if ($ok === false) {
$profile->query('ROLLBACK');
$this->query('ROLLBACK');
throw new ServerException('Cannot save ActivityPub profile.');
}
}
/**
* Fetch the locally stored profile for this Activitypub_profile
*
* @return Profile
* @throws NoProfileException if it was not found
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function local_profile()
{
$profile = Profile::getKV('id', $this->profile_id);
if (!$profile instanceof Profile) {
throw new NoProfileException($this->profile_id);
}
return $profile;
}
/**
* Generates an Activitypub_profile from a Profile
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param Profile $profile
* @return Activitypub_profile
* @throws Exception if no Activitypub_profile exists for given Profile
*/
public static function from_profile(Profile $profile)
{
$profile_id = $profile->getID();
$aprofile = self::getKV('profile_id', $profile_id);
if (!$aprofile instanceof Activitypub_profile) {
// No Activitypub_profile for this profile_id,
if (!$profile->isLocal()) {
// create one!
$aprofile = self::create_from_local_profile($profile);
} else {
throw new Exception('No Activitypub_profile for Profile ID: '.$profile_id. ', this is a local user.');
}
}
$fields = [
'uri' => 'profileurl',
'nickname' => 'nickname',
'fullname' => 'fullname',
'bio' => 'bio'
];
foreach ($fields as $af => $pf) {
$aprofile->$af = $profile->$pf;
}
return $aprofile;
}
/**
* Given an existent local profile creates an ActivityPub profile.
* One must be careful not to give a user profile to this function
* as only remote users have ActivityPub_profiles on local instance
*
* @param Profile $profile
* @return Activitypub_profile
* @throws HTTP_Request2_Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private static function create_from_local_profile(Profile $profile)
{
$aprofile = new Activitypub_profile();
$url = $profile->getUri();
$inboxes = Activitypub_explorer::get_actor_inboxes_uri($url);
if ($inboxes == null) {
throw new Exception('This is not an ActivityPub user thus AProfile is politely refusing to proceed.');
}
$aprofile->created = $aprofile->modified = common_sql_now();
$aprofile = new Activitypub_profile;
$aprofile->profile_id = $profile->getID();
$aprofile->uri = $url;
$aprofile->nickname = $profile->getNickname();
$aprofile->fullname = $profile->getFullname();
$aprofile->bio = substr($profile->getDescription(), 0, 1000);
$aprofile->inboxuri = $inboxes["inbox"];
$aprofile->sharedInboxuri = $inboxes["sharedInbox"];
$aprofile->insert();
return $aprofile;
}
/**
* Returns sharedInbox if possible, inbox otherwise
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return string Inbox URL
*/
public function get_inbox()
{
if (is_null($this->sharedInboxuri)) {
return $this->inboxuri;
}
return $this->sharedInboxuri;
}
/**
* Getter for uri property
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return string URI
*/
public function getUri()
{
return $this->uri;
}
/**
* Getter for url property
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return string URL
*/
public function getUrl()
{
return $this->getUri();
}
/**
* Getter for id property
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return int
*/
public function getID()
{
return $this->profile_id;
}
/**
* Ensures a valid Activitypub_profile when provided with a valid URI.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $url
* @return Activitypub_profile
* @throws Exception if it isn't possible to return an Activitypub_profile
*/
public static function fromUri($url)
{
try {
return self::from_profile(Activitypub_explorer::get_profile_from_url($url));
} catch (Exception $e) {
throw new Exception('No valid ActivityPub profile found for given URI.');
}
}
/**
* Look up, and if necessary create, an Activitypub_profile for the remote
* entity with the given webfinger address.
* This should never return null -- you will either get an object or
* an exception will be thrown.
*
* @author GNU social
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $addr webfinger address
* @return Activitypub_profile
* @throws Exception on error conditions
*/
public static function ensure_web_finger($addr)
{
// Normalize $addr, i.e. add 'acct:' if missing
$addr = Discovery::normalize($addr);
// Try the cache
$uri = self::cacheGet(sprintf('activitypub_profile:webfinger:%s', $addr));
if ($uri !== false) {
if (is_null($uri)) {
// Negative cache entry
// TRANS: Exception.
throw new Exception(_m('Not a valid webfinger address (via cache).'));
}
try {
return self::fromUri($uri);
} catch (Exception $e) {
common_log(LOG_ERR, sprintf(__METHOD__ . ': Webfinger address cache inconsistent with database, did not find Activitypub_profile uri==%s', $uri));
self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), false);
}
}
// Now, try some discovery
$disco = new Discovery();
try {
$xrd = $disco->lookup($addr);
} catch (Exception $e) {
// Save negative cache entry so we don't waste time looking it up again.
// @todo FIXME: Distinguish temporary failures?
self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), null);
// TRANS: Exception.
throw new Exception(_m('Not a valid webfinger address.'));
}
$hints = array_merge(
array('webfinger' => $addr),
DiscoveryHints::fromXRD($xrd)
);
// If there's an Hcard, let's grab its info
if (array_key_exists('hcard', $hints)) {
if (!array_key_exists('profileurl', $hints) ||
$hints['hcard'] != $hints['profileurl']) {
$hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
$hints = array_merge($hcardHints, $hints);
}
}
// If we got a profile page, try that!
$profileUrl = null;
if (array_key_exists('profileurl', $hints)) {
$profileUrl = $hints['profileurl'];
try {
common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
$aprofile = self::fromUri($hints['profileurl']);
self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), $aprofile->getUri());
return $aprofile;
} catch (Exception $e) {
common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
// keep looking
//
// @todo FIXME: This means an error discovering from profile page
// may give us a corrupt entry using the webfinger URI, which
// will obscure the correct page-keyed profile later on.
}
}
// XXX: try hcard
// XXX: try FOAF
// TRANS: Exception. %s is a webfinger address.
throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'), $addr));
}
/**
* Update remote user profile in local instance
* Depends on do_update
*
* @param Activitypub_profile $aprofile
* @param array $res remote response
* @return Profile remote Profile object
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function update_profile($aprofile, $res)
{
// ActivityPub Profile
$aprofile->uri = $res['id'];
$aprofile->nickname = $res['preferredUsername'];
$aprofile->fullname = isset($res['name']) ? $res['name'] : null;
$aprofile->bio = isset($res['summary']) ? substr(strip_tags($res['summary']), 0, 1000) : null;
$aprofile->inboxuri = $res['inbox'];
$aprofile->sharedInboxuri = isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : $res['inbox'];
$profile = $aprofile->local_profile();
$profile->modified = $aprofile->modified = common_sql_now();
$fields = [
'uri' => 'profileurl',
'nickname' => 'nickname',
'fullname' => 'fullname',
'bio' => 'bio'
];
foreach ($fields as $af => $pf) {
$profile->$pf = $aprofile->$af;
}
// Profile
$profile->update();
$aprofile->update();
// Public Key
Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
// Avatar
if (isset($res['icon']['url'])) {
try {
Activitypub_explorer::update_avatar($profile, $res['icon']['url']);
} catch (Exception $e) {
// Let the exception go, it isn't a serious issue
common_debug('An error ocurred while grabbing remote avatar'.$e->getMessage());
}
}
return $profile;
}
}

View File

@ -0,0 +1,55 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_reject extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Reject
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array $object
* @return array pretty array to be used in a response
*/
public static function reject_to_array($object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'type' => 'Reject',
'object' => $object
];
return $res;
}
}

View File

@ -0,0 +1,179 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub Keys System
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_rsa extends Managed_DataObject
{
public $__table = 'activitypub_rsa';
public $profile_id; // int(4) primary_key not_null
public $private_key; // text() not_null
public $public_key; // text() not_null
public $created; // datetime() not_null default_CURRENT_TIMESTAMP
public $modified; // datetime() not_null default_CURRENT_TIMESTAMP
/**
* Return table definition for Schema setup and DB_DataObject usage.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return array array of column definitions
*/
public static function schemaDef()
{
return [
'fields' => [
'profile_id' => ['type' => 'integer'],
'private_key' => ['type' => 'text'],
'public_key' => ['type' => 'text', 'not null' => true],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
],
'primary key' => ['profile_id'],
'foreign keys' => [
'activitypub_profile_profile_id_fkey' => ['profile', ['profile_id' => 'id']],
],
];
}
public function get_private_key($profile)
{
$this->profile_id = $profile->getID();
$apRSA = self::getKV('profile_id', $this->profile_id);
if (!$apRSA instanceof Activitypub_rsa) {
// No existing key pair for this profile
if ($profile->isLocal()) {
self::generate_keys($this->private_key, $this->public_key);
$this->store_keys();
} else {
throw new Exception('This is a remote Profile, there is no Private Key for this Profile.');
}
}
return $apRSA->private_key;
}
/**
* Guarantees a Public Key for a given profile.
*
* @param Profile $profile
* @param bool $fetch
* @return string The public key
* @throws ServerException It should never occur, but if so, we break everything!
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function ensure_public_key($profile, $fetch = true)
{
$this->profile_id = $profile->getID();
$apRSA = self::getKV('profile_id', $this->profile_id);
if (!$apRSA instanceof Activitypub_rsa) {
// No existing key pair for this profile
if ($profile->isLocal()) {
self::generate_keys($this->private_key, $this->public_key);
$this->store_keys();
} else {
// This should never happen, but try to recover!
if ($fetch) {
$res = Activitypub_explorer::get_remote_user_activity(ActivityPubPlugin::actor_uri($profile));
Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
return self::ensure_public_key($profile, false);
} else {
throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened!');
}
}
}
return $apRSA->public_key;
}
/**
* Insert the current object variables into the database.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @access public
* @throws ServerException
*/
public function store_keys()
{
$this->created = $this->modified = common_sql_now();
$ok = $this->insert();
if ($ok === false) {
throw new ServerException('Cannot save ActivityPub RSA.');
}
}
/**
* Generates a pair of RSA keys.
*
* @author PHP Manual Contributed Notes <dirt@awoms.com>
* @param string $private_key in/out
* @param string $public_key in/out
*/
public static function generate_keys(&$private_key, &$public_key)
{
$config = [
'digest_alg' => 'sha512',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
];
// Create the private and public key
$res = openssl_pkey_new($config);
// Extract the private key from $res to $private_key
openssl_pkey_export($res, $private_key);
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$public_key = $pubKey["key"];
unset($pubKey);
}
/**
* Update public key.
*
* @param Profile $profile
* @param string $public_key
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function update_public_key($profile, $public_key)
{
// Public Key
$apRSA = new Activitypub_rsa();
$apRSA->profile_id = $profile->getID();
$apRSA->public_key = $public_key;
$apRSA->modified = common_sql_now();
if (!$apRSA->update()) {
$apRSA->insert();
}
}
}

View File

@ -0,0 +1,55 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub representation of a Tag
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_tag extends Managed_DataObject
{
/**
* Generates a pretty tag from a Tag object
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array Tag $tag
* @return array pretty array to be used in a response
*/
public static function tag_to_array($tag)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'name' => $tag,
'url' => common_local_url('tag', ['tag' => $tag])
];
return $res;
}
}

View File

@ -0,0 +1,87 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub error representation
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_undo extends Managed_DataObject
{
/**
* Generates an ActivityPub representation of a Undo
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array $object
* @return array pretty array to be used in a response
*/
public static function undo_to_array($object)
{
$res = [
'@context' => 'https://www.w3.org/ns/activitystreams',
'id' => $object['id'].'/undo',
'type' => 'Undo',
'actor' => $object['actor'],
'object' => $object
];
return $res;
}
/**
* Verifies if a given object is acceptable for a Undo Activity.
*
* @param array $object
* @return bool
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function validate_object($object)
{
if (!is_array($object)) {
throw new Exception('Invalid Object Format for Undo Activity.');
}
if (!isset($object['type'])) {
throw new Exception('Object type was not specified for Undo Activity.');
}
switch ($object['type']) {
case 'Follow':
case 'Like':
// Validate data
if (!filter_var($object['object'], FILTER_VALIDATE_URL)) {
throw new Exception('Object is not a valid Object URI for Activity.');
}
break;
default:
throw new Exception('This is not a supported Object Type for Undo Activity.');
}
return true;
}
}

View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>ActivityPub plugin for GNU Social API Documentation</title>
<!-- needed for adaptive design -->
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
<link rel="icon" href="https://git.gnu.io/gnu/gnu-social/raw/b286e8798b7f89cd72ef19dc335624100f43ce94/theme/neo-gnu/favicon.ico">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<redoc spec-url='openapi.json'></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
</body>
</html>

View File

@ -0,0 +1,101 @@
ActivityPub Plugin for GNU Social Doc
=====================================
## Contents
- [Objects](#entities)
- [Attachment](#attachment)
- [Error](#error)
- [Image](#image)
- [Notice](#notice)
- [Profile](#profile)
- [Tag](#tag)
- [Activities](#activities)
- [Create](#create)
- [Announce](#announce)
- [Delete](#delete)
- [Undo](#undo)
- [Accept](#accept)
- [Reject](#reject)
- [Like](#like)
- [Follow](#follow)
## Objects
### Attachment
| Attribute | Description | Nullable | Type |
| ------------------------ | ----------------------------------------------- | -------- | ------- |
| `id` | ID of the attachment | no | int32 |
| `mimetype` | Mimetype | no | string |
| `url` | URL of the locally hosted version of the image | no | string |
| `meta` | See **attachment metadata** below | yes | Array |
| `title` | Attachment title | no | string |
**Attachment metadata:**
Images may contain `width`, `height`, `size`.
### Error
The most important part of an error response is the HTTP status code. Standard semantics are followed. The body of an error is a JSON object with this structure:
| Attribute | Description | Nullable | Type |
| ------------------------ | ----------------------------------- | -------- | ------- |
| `error` | A textual description of the error | no | string |
### Image
| Attribute | Description | Nullable | Type |
| ------------------------ | --------------- | -------- | ------- |
| `type` | "Image" | no | string |
| `width` | Image's width | no | int32 |
| `height` | Image's height | no | int32 |
| `url` | Image URL | no | string |
### Notice
| Attribute | Description | Nullable | Type |
| ------------------------ | ------------------------------------------------- | -------- | ------------------------------------ |
| `id` | Notice's URL | no | string |
| `type` | Notice's Type | no | string |
| `actor` | URL of Notice owner profile page (can be remote) | no | string |
| `published` | DateTime of notice creation | no | datetime |
| `to` | To | no | string |
| `cc` | CC | no | string |
| `content` | Notice's Content in plain text | no | string |
| `url` | Notice's URL | no | string |
| `reply_to` | ID of the notice this replies | yes | int32 |
| `is_local` | Boolean, true if local, false otherwise | no | bool |
| `conversation` | Notice conversation id | no | int32 |
| `attachment` | Array of [Attachments](#attachment) | no | Array of [Attachments](#attachment) |
| `tag` | Array of [Tags](#tag) | no | Array of [Tags](#tag) |
### Profile
| Attribute | Description | Nullable | Type |
| ------------------------ | ------------------------------------------------ | -------- | ---------------- |
| `@context` | Standard compliance | no | string |
| `id` | Actor's id | no | int32 |
| `type` | "Person" | no | string |
| `nickname` | Actor's nickname | no | string |
| `is_local` | True if local, false otherwise | no | bool |
| `inbox` | URL to Actor's inbox endpoint | no | string |
| `outbox` | URL to Actor's outbox endpoint | no | string |
| `display_name` | The Actor's display name | no | string |
| `followers` | URL to Actor's followers endpoint | no | string |
| `followers_count` | Total number of followers | no | int32 |
| `following` | URL to Actor's following endpoint | no | string |
| `following_count` | Total number of following | no | int32 |
| `liked` | URL to Actor's Liked collection endpoint | no | string |
| `liked_count` | Total number of favorites | no | int32 |
| `summary` | Actor's biography | no | string |
| `url` | URL of the Actor's profile page (can be remote) | no | string |
| `avatar` | Actor's avatar | no | [Image](#image) |
### Tag
| Attribute | Description | Nullable | Type |
| ------------------------ | -------------------------------------------- | -------- | ---------- |
| `name` | The hashtag, not including the preceding `#` | no | string |
| `url` | The URL of the hashtag | no | string |

View File

@ -0,0 +1,673 @@
{
"openapi": "3.0.0",
"info": {
"description": "## Retrieving objects\nThe HTTP GET method may be dereferenced against an object's `id` property to retrieve the activity.\nThe plugin supports HTTP content negotiation as defined in [RFC7231](https://tools.ietf.org/html/rfc7231) in every endpoint suffixed with .json .\nThe plugin always presents ActivityStreams object representation in response to every request.\nThe client MUST specify an `Accept` header with the `application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"` media type in order to retrieve the activity.\n\n## Selecting ranges\n\nFor most `GET` operations that return arrays, the query parameters `max_id` and `since_id` can be used to specify the range of IDs to return.\nAPI methods that return collections of items can return a `Link` header containing URLs for the `next` and `prev` pages.\nSee the [Link header RFC](https://tools.ietf.org/html/rfc5988) for more information.\n\n## Pretty output\n\nFor most operations if the `pretty` parameter is set a formated output will be generated (useful for learning about the API or debuging purposes).\n\n## Errors\n\nIf the request you make doesn't go through, the plugin will usually respond with an [Error](#error).\n\n___\n\n> **Note:** Some attributes in the payload can have ``null`` value and are marked as _nullable_ on the tables below. Attributes that are not nullable are guaranteed to return a valid value.",
"version": "1.0.0",
"title": "ActivityPub plugin for GNU Social",
"contact": {
"email": "diogo@fc.up.pt"
},
"license": {
"name": "AGPLv3",
"url": "https://git.gnu.io/gnu/GS-ActivityPub-plugin/blob/COPYING"
}
},
"externalDocs": {
"description": "For a complete definition of the objects and activities available click here.",
"url": "https://git.gnu.io/gnu/GS-ActivityPub-plugin/doc/objects_and_activities.md"
},
"paths": {
"/{nickname}": {
"get": {
"summary": "Fetching an Actor's profile",
"description": "Returns a Profile.",
"responses": {
"200": {
"description": "Returns a Profile",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Profile"
}
}
}
}
}
},
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/json"
}
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/activity+json"
}
}
]
}
},
"/{nickname}/inbox.json": {
"post": {
"summary": "Actor Inbox endpoint",
"description": "Allows the publish of activities with attention to a given Actor",
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/json"
}
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/activity+json"
}
}
],
"responses": {
"200": {
"description": "Returns the same activity it received"
}
}
}
},
"/{nickname}/liked.json": {
"get": {
"summary": "Liked Collection",
"description": "Getting an Actor's Liked Collection",
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/json"
}
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/activity+json"
}
},
{
"name": "max_id",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"format": "int32"
},
"description": "Get a list of likes with ID less than this value",
"format": "int32"
},
{
"name": "since_id",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"format": "int32"
},
"description": "Get a list of likes with ID greater than this value"
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"format": "int32",
"default": "40"
},
"description": "Maximum number of likes to get (Max 80)"
}
],
"responses": {
"200": {
"description": "Returns Actor's Liked Collection",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Liked Collection"
}
}
}
}
}
}
}
},
"/{nickname}/followers.json": {
"get": {
"summary": "Followers Collection",
"description": "Getting an Actor's Followers Collection",
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/json"
}
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/activity+json"
}
},
{
"name": "page",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"format": "int32",
"default": "1"
},
"description": "Page index (starts in 1)"
}
],
"responses": {
"200": {
"description": "Returns Actor's Followers Collection",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Follow Collection"
}
}
}
}
}
}
}
},
"/{nickname}/following.json": {
"get": {
"summary": "Following Collection",
"description": "Getting an Actor's Following Collection",
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/json"
}
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/activity+json"
}
},
{
"name": "page",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"format": "int32",
"default": "1"
},
"description": "Page index (starts in 1)"
}
],
"responses": {
"200": {
"description": "Returns Actor's Following Collection",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Follow Collection"
}
}
}
}
}
}
}
},
"/inbox.json": {
"post": {
"summary": "SharedInbox endpoint",
"description": "Allows the publish of activities",
"parameters": [
{
"name": "Content-Type",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/json"
}
},
{
"name": "Accept",
"in": "header",
"required": true,
"schema": {
"type": "string",
"default": "application/activity+json"
}
}
],
"responses": {
"200": {
"description": "Returns the same activity it received"
}
}
}
}
},
"components": {
"schemas": {
"Note": {
"type": "object",
"required": [
"@context",
"id",
"type",
"actor",
"published",
"to",
"cc",
"content",
"url",
"reply_to",
"is_local",
"conversation",
"attachment",
"tag"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"id": {
"description": "Notice's URI",
"type": "string"
},
"type": {
"description": "Notice's Type",
"type": "string"
},
"actor": {
"description": "URL of Notice owner profile page (can be remote)",
"type": "string"
},
"published": {
"description": "DateTime of notice creation",
"type": "string",
"format": "date-time"
},
"to": {
"description": "To",
"type": "string"
},
"cc": {
"description": "CC",
"type": "string"
},
"content": {
"description": "Notice's Content in plain text",
"type": "string"
},
"url": {
"description": "Notice's URL",
"type": "string"
},
"reply_to": {
"description": "ID of the notice this replies",
"type": "string"
},
"is_local": {
"description": "true if local, false otherwise",
"type": "string"
},
"conversation": {
"description": "Notice conversation id",
"type": "integer",
"format": "int32"
},
"attachment": {
"description": "Array of Attachments",
"type": "Array of Attachments"
},
"tag": {
"description": "Array of Tags",
"type": "Array of Tags"
}
},
"xml": {
"name": "Note"
}
},
"Image": {
"type": "object",
"required": [
"@context",
"type",
"width",
"height",
"url"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"type": {
"description": "Image",
"type": "string"
},
"width": {
"description": "Image's width",
"type": "integer",
"format": "int32"
},
"height": {
"description": "Image's height",
"type": "integer",
"format": "int32"
},
"url": {
"description": "Image URL",
"type": "string"
}
},
"xml": {
"name": "Image"
}
},
"Attachment": {
"type": "object",
"required": [
"@context",
"id",
"mimetype",
"url",
"title"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"id": {
"type": "integer",
"format": "int32",
"description": "Id of the Attachment"
},
"mimetype": {
"type": "string",
"description": "Mimetype"
},
"url": {
"type": "string",
"description": "URL of locally hosted version of the attachment"
},
"meta": {
"type": "array",
"description": "Attachment metadata:\n\nImages may contain *width*, *height*, *size*.",
"items": {}
},
"title": {
"type": "string",
"description": "Attachment title"
}
},
"xml": {
"name": "Attachment"
}
},
"Profile": {
"type": "object",
"required": [
"@context",
"id",
"nickname",
"is_local",
"inbox",
"outbox",
"display_name",
"followers",
"followers_count",
"following",
"following_count",
"liked",
"liked_count",
"summary",
"url",
"avatar"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"id": {
"type": "string",
"description": "Local URI"
},
"type": "Person",
"nickname": {
"type": "string",
"description": "Actor's nickname"
},
"is_local": {
"type": "boolean",
"description": "True if local, false otherwise"
},
"inbox": {
"type": "string",
"description": "URL to Actor's inbox endpoint"
},
"sharedInbox": {
"type": "string",
"description": "URL to Actor's sharedInbox endpoint"
},
"outbox": {
"type": "string",
"description": "URL to Actor's outbox endpoint"
},
"display_name": {
"type": "string",
"description": "The Actor's display name"
},
"followers": {
"type": "string",
"description": "URL to Actor's followers collection"
},
"followers_count": {
"type": "integer",
"format": "int32",
"description": "Total number of followers"
},
"following": {
"type": "string",
"description": "URL to Actor's following collection"
},
"following_count": {
"type": "integer",
"format": "int32",
"description": "Total number of following"
},
"liked": {
"type": "string",
"description": "URL to Actor's Liked collection"
},
"liked_count": {
"type": "integer",
"format": "int32",
"description": "Total number of favorites"
},
"summary": {
"type": "string",
"description": "Actor's biography"
},
"url": {
"type": "string",
"description": "URL of the Actor's profile page (can be remote)"
},
"avatar": {
"type": "Image",
"description": "Actor's avatar"
}
},
"xml": {
"name": "Profile"
}
},
"Tag": {
"type": "object",
"required": [
"@context",
"name",
"url"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"name": {
"type": "string",
"description": "The hashtag, not including the preceding #"
},
"url": {
"type": "string",
"description": "The URL of the hashtag"
}
},
"xml": {
"name": "Tag"
}
},
"Liked Collection": {
"type": "object",
"required": [
"@context",
"id",
"type",
"totalItems",
"orderedItems"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"id": {
"type": "string",
"description": "URL for current endpoint"
},
"type": {
"type": "string",
"description": "OrderedCollection"
},
"totalItems": {
"type": "integer",
"format": "int32",
"description": "Total number of favorites"
},
"orderedItems": {
"type": "Array of Notices",
"description": "Array of Notices"
}
}
},
"Follow Collection": {
"type": "object",
"required": [
"@context",
"id",
"type",
"totalItems",
"orderedItems"
],
"properties": {
"@context": {
"type": "string",
"value": "https://www.w3.org/ns/activitystreams",
"default": "https://www.w3.org/ns/activitystreams"
},
"id": {
"type": "string",
"description": "URL for current endpoint"
},
"type": {
"type": "string",
"description": "OrderedCollection"
},
"totalItems": {
"type": "integer",
"format": "int32",
"description": "Total number of items"
},
"prev": {
"type": "string",
"description": "Previous page URL"
},
"next": {
"type": "string",
"description": "Next page URL"
},
"orderedItems": {
"type": "Array of string",
"description": "The URL of each profile"
}
}
}
},
"links": {},
"callbacks": {}
},
"security": [],
"servers": []
}

View File

@ -0,0 +1,116 @@
<?php
/**
* Note : Code is released under the GNU LGPL
*
* Please do not change the header of this file
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This library 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 Lesser General Public License for more details.
*/
/**
* The AcceptHeader page will parse and sort the different
* allowed types for the content negociations
*
* @author Pierrick Charron <pierrick@webstart.fr>
*/
class AcceptHeader extends \ArrayObject
{
/**
* Constructor
*
* @param string $header Value of the Accept header
* @return void
*/
public function __construct($header)
{
$acceptedTypes = $this->_parse($header);
usort($acceptedTypes, [$this, '_compare']);
parent::__construct($acceptedTypes);
}
/**
* Parse the accept header and return an array containing
* all the informations about the Accepted types
*
* @param string $data Value of the Accept header
* @return array
*/
private function _parse($data)
{
$array = [];
$items = explode(',', $data);
foreach ($items as $item) {
$elems = explode(';', $item);
$acceptElement = [];
$mime = current($elems);
list($type, $subtype) = explode('/', $mime);
$acceptElement['type'] = trim($type);
$acceptElement['subtype'] = trim($subtype);
$acceptElement['raw'] = $mime;
$acceptElement['params'] = [];
while (next($elems)) {
list($name, $value) = explode('=', current($elems));
$acceptElement['params'][trim($name)] = trim($value);
}
$array[] = $acceptElement;
}
return $array;
}
/**
* Compare two Accepted types with their parameters to know
* if one media type should be used instead of an other
*
* @param array $a The first media type and its parameters
* @param array $b The second media type and its parameters
* @return int
*/
private function _compare($a, $b)
{
$a_q = isset($a['params']['q']) ? floatval($a['params']['q']) : 1.0;
$b_q = isset($b['params']['q']) ? floatval($b['params']['q']) : 1.0;
if ($a_q === $b_q) {
$a_count = count($a['params']);
$b_count = count($b['params']);
if ($a_count === $b_count) {
if ($r = $this->_compareSubType($a['subtype'], $b['subtype'])) {
return $r;
} else {
return $this->_compareSubType($a['type'], $b['type']);
}
} else {
return $a_count < $b_count;
}
} else {
return $a_q < $b_q;
}
}
/**
* Compare two subtypes
*
* @param string $a First subtype to compare
* @param string $b Second subtype to compare
* @return int
*/
private function _compareSubType($a, $b)
{
if ($a === '*' && $b !== '*') {
return 1;
} elseif ($b === '*' && $a !== '*') {
return -1;
} else {
return 0;
}
}
}

View File

@ -0,0 +1,98 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* Utility class to hold a bunch of constant defining default verb types
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_activityverb2 extends Managed_DataObject
{
const FULL_LIST =
[
'Accept' => 'https://www.w3.org/ns/activitystreams#Accept',
'TentativeAccept' => 'https://www.w3.org/ns/activitystreams#TentativeAccept',
'Add' => 'https://www.w3.org/ns/activitystreams#Add',
'Arrive' => 'https://www.w3.org/ns/activitystreams#Arrive',
'Create' => 'https://www.w3.org/ns/activitystreams#Create',
'Delete' => 'https://www.w3.org/ns/activitystreams#Delete',
'Follow' => 'https://www.w3.org/ns/activitystreams#Follow',
'Ignore' => 'https://www.w3.org/ns/activitystreams#Ignore',
'Join' => 'https://www.w3.org/ns/activitystreams#Join',
'Leave' => 'https://www.w3.org/ns/activitystreams#Leave',
'Like' => 'https://www.w3.org/ns/activitystreams#Like',
'Offer' => 'https://www.w3.org/ns/activitystreams#Offer',
'Invite' => 'https://www.w3.org/ns/activitystreams#Invite',
'Reject' => 'https://www.w3.org/ns/activitystreams#Reject',
'TentativeReject' => 'https://www.w3.org/ns/activitystreams#TentativeReject',
'Remove' => 'https://www.w3.org/ns/activitystreams#Remove',
'Undo' => 'https://www.w3.org/ns/activitystreams#Undo',
'Update' => 'https://www.w3.org/ns/activitystreams#Update',
'View' => 'https://www.w3.org/ns/activitystreams#View',
'Listen' => 'https://www.w3.org/ns/activitystreams#Listen',
'Read' => 'https://www.w3.org/ns/activitystreams#Read',
'Move' => 'https://www.w3.org/ns/activitystreams#Move',
'Travel' => 'https://www.w3.org/ns/activitystreams#Travel',
'Announce' => 'https://www.w3.org/ns/activitystreams#Announce',
'Block' => 'https://www.w3.org/ns/activitystreams#Block',
'Flag' => 'https://www.w3.org/ns/activitystreams#Flag',
'Dislike' => 'https://www.w3.org/ns/activitystreams#Dislike',
'Question' => 'https://www.w3.org/ns/activitystreams#Question'
];
const KNOWN =
[
'Accept',
'Create',
'Delete',
'Follow',
'Like',
'Undo',
'Announce'
];
/**
* Converts canonical into verb.
*
* @author GNU social
* @param string $verb
* @return string
*/
public static function canonical($verb)
{
$ns = 'https://www.w3.org/ns/activitystreams#';
if (substr($verb, 0, mb_strlen($ns)) == $ns) {
return substr($verb, mb_strlen($ns));
} else {
return $verb;
}
}
}

View File

@ -0,0 +1,158 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Evan Prodromou
* @author Brion Vibber
* @author James Walker
* @author Siebrand Mazeland
* @author Mikael Nordfeldth
* @author Diogo Cordeiro
* @copyright 2010-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
class DiscoveryHints
{
public static function fromXRD(XML_XRD $xrd)
{
$hints = [];
if (Event::handle('StartDiscoveryHintsFromXRD', [$xrd, &$hints])) {
foreach ($xrd->links as $link) {
switch ($link->rel) {
case WebFingerResource_Profile::PROFILEPAGE:
$hints['profileurl'] = $link->href;
break;
case Discovery::UPDATESFROM:
if (empty($link->type) || $link->type == 'application/atom+xml') {
$hints['feedurl'] = $link->href;
}
break;
case Discovery::HCARD:
case Discovery::MF2_HCARD:
$hints['hcard'] = $link->href;
break;
default:
break;
}
}
Event::handle('EndDiscoveryHintsFromXRD', [$xrd, &$hints]);
}
return $hints;
}
public static function fromHcardUrl($url)
{
$client = new HTTPClient();
$client->setHeader('Accept', 'text/html,application/xhtml+xml');
try {
$response = $client->get($url);
if (!$response->isOk()) {
return null;
}
} catch (HTTP_Request2_Exception $e) {
// Any HTTPClient error that might've been thrown
common_log(LOG_ERR, __METHOD__ . ':'.$e->getMessage());
return null;
}
return self::hcardHints(
$response->getBody(),
$response->getEffectiveUrl()
);
}
public static function hcardHints($body, $url)
{
$hcard = self::_hcard($body, $url);
if (empty($hcard)) {
return [];
}
$hints = [];
// XXX: don't copy stuff into an array and then copy it again
if (array_key_exists('nickname', $hcard) && !empty($hcard['nickname'][0])) {
$hints['nickname'] = $hcard['nickname'][0];
}
if (array_key_exists('name', $hcard) && !empty($hcard['name'][0])) {
$hints['fullname'] = $hcard['name'][0];
}
if (array_key_exists('photo', $hcard) && count($hcard['photo'])) {
$hints['avatar'] = $hcard['photo'][0];
}
if (array_key_exists('note', $hcard) && !empty($hcard['note'][0])) {
$hints['bio'] = $hcard['note'][0];
}
if (array_key_exists('adr', $hcard) && !empty($hcard['adr'][0])) {
$hints['location'] = $hcard['adr'][0]['value'];
}
if (array_key_exists('url', $hcard) && !empty($hcard['url'][0])) {
$hints['homepage'] = $hcard['url'][0];
}
return $hints;
}
public static function _hcard($body, $url)
{
$mf2 = new Mf2\Parser($body, $url);
$mf2 = $mf2->parse();
if (empty($mf2['items'])) {
return null;
}
$hcards = [];
foreach ($mf2['items'] as $item) {
if (!in_array('h-card', $item['type'])) {
continue;
}
// We found a match, return it immediately
if (isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
return $item['properties'];
}
// Let's keep all the hcards for later, to return one of them at least
$hcards[] = $item['properties'];
}
// No match immediately for the url we expected, but there were h-cards found
if (count($hcards) > 0) {
return $hcards[0];
}
return null;
}
}

View File

@ -0,0 +1,482 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub's own Explorer
*
* Allows to discovery new (or the same) Profiles (both local or remote)
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_explorer
{
private $discovered_actor_profiles = [];
/**
* Shortcut function to get a single profile from its URL.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $url
* @return Profile
* @throws Exception
*/
public static function get_profile_from_url($url)
{
$discovery = new Activitypub_explorer;
// Get valid Actor object
$actor_profile = $discovery->lookup($url);
if (!empty($actor_profile)) {
return $actor_profile[0];
}
throw new Exception('Invalid Actor.');
}
/**
* Get every profile from the given URL
* This function cleans the $this->discovered_actor_profiles array
* so that there is no erroneous data
*
* @param string $url User's url
* @return array of Profile objects
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function lookup($url)
{
if (in_array($url, ACTIVITYPUB_PUBLIC_TO)) {
return [];
}
common_debug('ActivityPub Explorer: Started now looking for '.$url);
$this->discovered_actor_profiles = [];
return $this->_lookup($url);
}
/**
* Get every profile from the given URL
* This is a recursive function that will accumulate the results on
* $discovered_actor_profiles array
*
* @param string $url User's url
* @return array of Profile objects
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function _lookup($url)
{
// First check if we already have it locally and, if so, return it
// If the local fetch fails: grab it remotely, store locally and return
if (! ($this->grab_local_user($url) || $this->grab_remote_user($url))) {
throw new Exception('User not found.');
}
return $this->discovered_actor_profiles;
}
/**
* This ensures that we are using a valid ActivityPub URI
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $url
* @return boolean success state (related to the response)
* @throws Exception (If the HTTP request fails)
*/
private function ensure_proper_remote_uri($url)
{
$client = new HTTPClient();
$headers = [];
$headers[] = 'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
$headers[] = 'User-Agent: GNUSocialBot v0.1 - https://gnu.io/social';
$response = $client->get($url, $headers);
$res = json_decode($response->getBody(), true);
if (self::validate_remote_response($res)) {
$this->temp_res = $res;
return true;
} else {
common_debug('ActivityPub Explorer: Invalid potential remote actor while ensuring URI: '.$url. '. He returned the following: '.json_encode($res, JSON_UNESCAPED_SLASHES));
}
return false;
}
/**
* Get a local user profile from its URL and joins it on
* $this->discovered_actor_profiles
*
* @param string $uri Actor's uri
* @param bool $online
* @return boolean success state
* @throws NoProfileException
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function grab_local_user($uri, $online = false)
{
if ($online) {
common_debug('ActivityPub Explorer: Searching locally for '.$uri. ' with online resources.');
} else {
common_debug('ActivityPub Explorer: Searching locally for '.$uri. ' offline.');
}
// Ensure proper remote URI
// If an exception occurs here it's better to just leave everything
// break than to continue processing
if ($online && $this->ensure_proper_remote_uri($uri)) {
$uri = $this->temp_res["id"];
}
// Try standard ActivityPub route
// Is this a known filthy little mudblood?
$aprofile = self::get_aprofile_by_url($uri);
if ($aprofile instanceof Activitypub_profile) {
$profile = $aprofile->local_profile();
common_debug('ActivityPub Explorer: Found a local Aprofile for '.$uri);
// We found something!
$this->discovered_actor_profiles[]= $profile;
unset($this->temp_res); // IMPORTANT to avoid _dangerous_ noise in the Explorer system
return true;
} else {
common_debug('ActivityPub Explorer: Unable to find a local Aprofile for '.$uri.' - looking for a Profile instead.');
// Well, maybe it is a pure blood?
// Iff, we are in the same instance:
$ACTIVITYPUB_BASE_ACTOR_URI_length = strlen(ACTIVITYPUB_BASE_ACTOR_URI);
if (substr($uri, 0, $ACTIVITYPUB_BASE_ACTOR_URI_length) == ACTIVITYPUB_BASE_ACTOR_URI) {
try {
$profile = Profile::getByID(intval(substr($uri, $ACTIVITYPUB_BASE_ACTOR_URI_length)));
common_debug('ActivityPub Explorer: Found a Profile for '.$uri);
// We found something!
$this->discovered_actor_profiles[]= $profile;
unset($this->temp_res); // IMPORTANT to avoid _dangerous_ noise in the Explorer system
return true;
} catch (Exception $e) {
// Let the exception go on its merry way.
common_debug('ActivityPub Explorer: Unable to find a Profile for '.$uri);
}
}
}
// If offline grabbing failed, attempt again with online resources
if (!$online) {
common_debug('ActivityPub Explorer: Will try everything again with online resources against: '.$uri);
return $this->grab_local_user($uri, true);
}
return false;
}
/**
* Get a remote user(s) profile(s) from its URL and joins it on
* $this->discovered_actor_profiles
*
* @param string $url User's url
* @return boolean success state
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function grab_remote_user($url)
{
common_debug('ActivityPub Explorer: Trying to grab a remote actor for '.$url);
if (!isset($this->temp_res)) {
$client = new HTTPClient();
$headers = [];
$headers[] = 'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
$headers[] = 'User-Agent: GNUSocialBot v0.1 - https://gnu.io/social';
$response = $client->get($url, $headers);
$res = json_decode($response->getBody(), true);
} else {
$res = $this->temp_res;
unset($this->temp_res);
}
if (isset($res['type']) && $res['type'] === 'OrderedCollection' && isset($res['first'])) { // It's a potential collection of actors!!!
common_debug('ActivityPub Explorer: Found a collection of actors for '.$url);
$this->travel_collection($res['first']);
return true;
} elseif (self::validate_remote_response($res)) {
common_debug('ActivityPub Explorer: Found a valid remote actor for '.$url);
$this->discovered_actor_profiles[]= $this->store_profile($res);
return true;
} else {
common_debug('ActivityPub Explorer: Invalid potential remote actor while grabbing remotely: '.$url. '. He returned the following: '.json_encode($res, JSON_UNESCAPED_SLASHES));
}
// TODO: Fallback to OStatus
return false;
}
/**
* Save remote user profile in local instance
*
* @param array $res remote response
* @return Profile remote Profile object
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function store_profile($res)
{
// ActivityPub Profile
$aprofile = new Activitypub_profile;
$aprofile->uri = $res['id'];
$aprofile->nickname = $res['preferredUsername'];
$aprofile->fullname = isset($res['name']) ? $res['name'] : null;
$aprofile->bio = isset($res['summary']) ? substr(strip_tags($res['summary']), 0, 1000) : null;
$aprofile->inboxuri = $res['inbox'];
$aprofile->sharedInboxuri = isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : $res['inbox'];
$aprofile->do_insert();
$profile = $aprofile->local_profile();
// Public Key
$apRSA = new Activitypub_rsa();
$apRSA->profile_id = $profile->getID();
$apRSA->public_key = $res['publicKey']['publicKeyPem'];
$apRSA->store_keys();
// Avatar
if (isset($res['icon']['url'])) {
try {
$this->update_avatar($profile, $res['icon']['url']);
} catch (Exception $e) {
// Let the exception go, it isn't a serious issue
common_debug('ActivityPub Explorer: An error ocurred while grabbing remote avatar: '.$e->getMessage());
}
}
return $profile;
}
/**
* Download and update given avatar image
*
* @author GNU social
* @param Profile $profile
* @param string $url
* @return Avatar The Avatar we have on disk.
* @throws Exception in various failure cases
*/
public static function update_avatar(Profile $profile, $url)
{
common_debug('ActivityPub Explorer: Started grabbing remote avatar from: '.$url);
if (!filter_var($url, FILTER_VALIDATE_URL)) {
// TRANS: Server exception. %s is a URL.
common_debug('ActivityPub Explorer: Failed because it is an invalid url: '.$url);
throw new ServerException(sprintf('Invalid avatar URL %s.', $url));
}
// @todo FIXME: This should be better encapsulated
// ripped from oauthstore.php (for old OMB client)
$temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
try {
$imgData = HTTPClient::quickGet($url);
// Make sure it's at least an image file. ImageFile can do the rest.
if (false === getimagesizefromstring($imgData)) {
common_debug('ActivityPub Explorer: Failed because the downloaded avatar: '.$url. 'is not a valid image.');
throw new UnsupportedMediaException('Downloaded avatar was not an image.');
}
file_put_contents($temp_filename, $imgData);
unset($imgData); // No need to carry this in memory.
common_debug('ActivityPub Explorer: Stored dowloaded avatar in: '.$temp_filename);
$id = $profile->getID();
$imagefile = new ImageFile(null, $temp_filename);
$filename = Avatar::filename(
$id,
image_type_to_extension($imagefile->type),
null,
common_timestamp()
);
rename($temp_filename, Avatar::path($filename));
common_debug('ActivityPub Explorer: Moved avatar from: '.$temp_filename.' to '.$filename);
} catch (Exception $e) {
common_debug('ActivityPub Explorer: Something went wrong while processing the avatar from: '.$url.' details: '.$e->getMessage());
unlink($temp_filename);
throw $e;
}
// @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
// keep from accidentally saving images from command-line (queues)
// that can't be read from web server, which causes hard-to-notice
// problems later on:
//
// http://status.net/open-source/issues/2663
chmod(Avatar::path($filename), 0644);
$profile->setOriginal($filename);
$orig = clone($profile);
$profile->avatar = $url;
$profile->update($orig);
common_debug('ActivityPub Explorer: Seted Avatar from: '.$url.' to profile.');
return Avatar::getUploaded($profile);
}
/**
* Validates a remote response in order to determine whether this
* response is a valid profile or not
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param array $res remote response
* @return boolean success state
*/
public static function validate_remote_response($res)
{
if (!isset($res['id'], $res['preferredUsername'], $res['inbox'], $res['publicKey']['publicKeyPem'])) {
return false;
}
return true;
}
/**
* Get a ActivityPub Profile from it's uri
* Unfortunately GNU social cache is not truly reliable when handling
* potential ActivityPub remote profiles, as so it is important to use
* this hacky workaround (at least for now)
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param string $v URL
* @return boolean|Activitypub_profile false if fails | Aprofile object if successful
*/
public static function get_aprofile_by_url($v)
{
$i = Managed_DataObject::getcached("Activitypub_profile", "uri", $v);
if (empty($i)) { // false = cache miss
$i = new Activitypub_profile;
$result = $i->get("uri", $v);
if ($result) {
// Hit!
$i->encache();
} else {
return false;
}
}
return $i;
}
/**
* Given a valid actor profile url returns its inboxes
*
* @param string $url of Actor profile
* @return boolean|array false if fails | array with inbox and shared inbox if successful
* @throws HTTP_Request2_Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function get_actor_inboxes_uri($url)
{
$client = new HTTPClient();
$headers = [];
$headers[] = 'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
$headers[] = 'User-Agent: GNUSocialBot v0.1 - https://gnu.io/social';
$response = $client->get($url, $headers);
if (!$response->isOk()) {
throw new Exception('Invalid Actor URL.');
}
$res = json_decode($response->getBody(), true);
if (self::validate_remote_response($res)) {
return [
'inbox' => $res['inbox'],
'sharedInbox' => isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : $res['inbox']
];
}
return false;
}
/**
* Allows the Explorer to transverse a collection of persons.
*
* @param string $url
* @return boolean
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function travel_collection($url)
{
$client = new HTTPClient();
$headers = [];
$headers[] = 'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
$headers[] = 'User-Agent: GNUSocialBot v0.1 - https://gnu.io/social';
$response = $client->get($url, $headers);
$res = json_decode($response->getBody(), true);
if (!isset($res['orderedItems'])) {
return false;
}
foreach ($res["orderedItems"] as $profile) {
if ($this->_lookup($profile) == false) {
common_debug('ActivityPub Explorer: Found an invalid actor for '.$profile);
// TODO: Invalid actor found, fallback to OStatus
}
}
// Go through entire collection
if (!is_null($res["next"])) {
$this->_lookup($res["next"]);
}
return true;
}
/**
* Get a remote user array from its URL (this function is only used for
* profile updating and shall not be used for anything else)
*
* @param string $url User's url
* @return mixed
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public static function get_remote_user_activity($url)
{
$client = new HTTPClient();
$headers = [];
$headers[] = 'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
$headers[] = 'User-Agent: GNUSocialBot v0.1 - https://gnu.io/social';
$response = $client->get($url, $headers);
$res = json_decode($response->getBody(), true);
if (Activitypub_explorer::validate_remote_response($res)) {
common_debug('ActivityPub Explorer: Found a valid remote actor for '.$url);
return $res;
}
throw new Exception('ActivityPub Explorer: Failed to get activity.');
}
}

View File

@ -0,0 +1,139 @@
<?php
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @category Network
* @package Nautilus
* @author Aaron Parecki <aaron@parecki.com>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://github.com/aaronpk/Nautilus/blob/master/app/ActivityPub/HTTPSignature.php
*/
class HttpSignature
{
public static function sign($user, $url, $body = false, $addlHeaders = [])
{
$digest = false;
if ($body) {
$digest = self::_digest($body);
}
$headers = self::_headersToSign($url, $digest);
$headers = array_merge($headers, $addlHeaders);
$stringToSign = self::_headersToSigningString($headers);
$signedHeaders = implode(' ', array_map('strtolower', array_keys($headers)));
$actor_private_key = new Activitypub_rsa();
$actor_private_key = $actor_private_key->get_private_key($user);
$key = openssl_pkey_get_private($actor_private_key);
openssl_sign($stringToSign, $signature, $key, OPENSSL_ALGO_SHA256);
$signature = base64_encode($signature);
$signatureHeader = 'keyId="' . ActivityPubPlugin::actor_uri($user).'#public-key' . '",headers="' . $signedHeaders . '",algorithm="rsa-sha256",signature="' . $signature . '"';
unset($headers['(request-target)']);
$headers['Signature'] = $signatureHeader;
return self::_headersToCurlArray($headers);
}
private static function _digest($body)
{
if (is_array($body)) {
$body = json_encode($body);
}
return base64_encode(hash('sha256', $body, true));
}
protected static function _headersToSign($url, $digest = false)
{
$date = new DateTime('UTC');
$headers = [
'(request-target)' => 'post ' . parse_url($url, PHP_URL_PATH),
'Date' => $date->format('D, d M Y H:i:s \G\M\T'),
'Host' => parse_url($url, PHP_URL_HOST),
'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams", application/activity+json, application/json',
'User-Agent' => 'GNU social ActivityPub Plugin - https://gnu.io/social',
'Content-Type' => 'application/activity+json'
];
if ($digest) {
$headers['Digest'] = 'SHA-256=' . $digest;
}
return $headers;
}
private static function _headersToSigningString($headers)
{
return implode("\n", array_map(function ($k, $v) {
return strtolower($k) . ': ' . $v;
}, array_keys($headers), $headers));
}
private static function _headersToCurlArray($headers)
{
return array_map(function ($k, $v) {
return "$k: $v";
}, array_keys($headers), $headers);
}
public static function parseSignatureHeader($signature)
{
$parts = explode(',', $signature);
$signatureData = [];
foreach ($parts as $part) {
if (preg_match('/(.+)="(.+)"/', $part, $match)) {
$signatureData[$match[1]] = $match[2];
}
}
if (!isset($signatureData['keyId'])) {
return [
'error' => 'No keyId was found in the signature header. Found: ' . implode(', ', array_keys($signatureData))
];
}
if (!filter_var($signatureData['keyId'], FILTER_VALIDATE_URL)) {
return [
'error' => 'keyId is not a URL: ' . $signatureData['keyId']
];
}
if (!isset($signatureData['headers']) || !isset($signatureData['signature'])) {
return [
'error' => 'Signature is missing headers or signature parts'
];
}
return $signatureData;
}
public static function verify($publicKey, $signatureData, $inputHeaders, $path, $body)
{
$digest = 'SHA-256=' . base64_encode(hash('sha256', $body, true));
$headersToSign = [];
foreach (explode(' ', $signatureData['headers']) as $h) {
if ($h == '(request-target)') {
$headersToSign[$h] = 'post ' . $path;
} elseif ($h == 'digest') {
$headersToSign[$h] = $digest;
} elseif (isset($inputHeaders[$h][0])) {
$headersToSign[$h] = $inputHeaders[$h];
}
}
$signingString = self::_headersToSigningString($headersToSign);
$verified = openssl_verify($signingString, base64_decode($signatureData['signature']), $publicKey, OPENSSL_ALGO_SHA256);
return [$verified, $signingString];
}
}

View File

@ -0,0 +1,324 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub Inbox Handler
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_inbox_handler
{
private $activity;
private $actor;
private $object;
/**
* Create a Inbox Handler to receive something from someone.
*
* @param array $activity Activity we are receiving
* @param Profile $actor_profile Actor originating the activity
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function __construct($activity, $actor_profile = null)
{
$this->activity = $activity;
$this->object = $activity['object'];
// Validate Activity
$this->validate_activity();
// Get Actor's Profile
if (!is_null($actor_profile)) {
$this->actor = $actor_profile;
} else {
$this->actor = ActivityPub_explorer::get_profile_from_url($this->activity['actor']);
}
// Handle the Activity
$this->process();
}
/**
* Validates if a given Activity is valid. Throws exception if not.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @throws Exception
*/
private function validate_activity()
{
// Activity validation
// Validate data
if (!(isset($this->activity['type']))) {
throw new Exception('Activity Validation Failed: Type was not specified.');
}
if (!isset($this->activity['actor'])) {
throw new Exception('Activity Validation Failed: Actor was not specified.');
}
if (!isset($this->activity['object'])) {
throw new Exception('Activity Validation Failed: Object was not specified.');
}
// Object validation
switch ($this->activity['type']) {
case 'Accept':
Activitypub_accept::validate_object($this->object);
break;
case 'Create':
Activitypub_create::validate_object($this->object);
break;
case 'Delete':
case 'Follow':
case 'Like':
case 'Announce':
if (!filter_var($this->object, FILTER_VALIDATE_URL)) {
throw new Exception('Object is not a valid Object URI for Activity.');
}
break;
case 'Undo':
Activitypub_undo::validate_object($this->object);
break;
default:
throw new Exception('Unknown Activity Type.');
}
}
/**
* Sends the Activity to proper handler in order to be processed.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function process()
{
switch ($this->activity['type']) {
case 'Accept':
$this->handle_accept($this->actor, $this->object);
break;
case 'Create':
$this->handle_create($this->actor, $this->object);
break;
case 'Delete':
$this->handle_delete($this->actor, $this->object);
break;
case 'Follow':
$this->handle_follow($this->actor, $this->object);
break;
case 'Like':
$this->handle_like($this->actor, $this->object);
break;
case 'Undo':
$this->handle_undo($this->actor, $this->object);
break;
case 'Announce':
$this->handle_announce($this->actor, $this->object);
break;
}
}
/**
* Handles an Accept Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_accept($actor, $object)
{
switch ($object['type']) {
case 'Follow':
$this->handle_accept_follow($actor, $object);
break;
}
}
/**
* Handles an Accept Follow Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_accept_follow($actor, $object)
{
// Get valid Object profile
$object_profile = new Activitypub_explorer;
$object_profile = $object_profile->lookup($object['object'])[0];
$pending_list = new Activitypub_pending_follow_requests($actor->getID(), $object_profile->getID());
$pending_list->remove();
}
/**
* Handles a Create Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_create($actor, $object)
{
switch ($object['type']) {
case 'Note':
Activitypub_notice::create_notice($object, $actor);
break;
}
}
/**
* Handles a Delete Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws AuthorizationException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_delete($actor, $object)
{
$notice = ActivityPubPlugin::grab_notice_from_url($object['object']);
$notice->deleteAs($actor);
}
/**
* Handles a Follow Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws AlreadyFulfilledException
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \HttpSignatures\Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_follow($actor, $object)
{
Activitypub_follow::follow($actor, $object);
}
/**
* Handles a Like Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_like($actor, $object)
{
$notice = ActivityPubPlugin::grab_notice_from_url($object);
Fave::addNew($actor, $notice);
}
/**
* Handles a Undo Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws AlreadyFulfilledException
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_undo($actor, $object)
{
switch ($object['type']) {
case 'Follow':
$this->handle_undo_follow($actor, $object['object']);
break;
case 'Like':
$this->handle_undo_like($actor, $object['object']);
break;
}
}
/**
* Handles a Undo Like Activity received by our inbox.
*
* @param Profile $actor Actor
* @param array $object Activity
* @throws AlreadyFulfilledException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
private function handle_undo_like($actor, $object)
{
$notice = ActivityPubPlugin::grab_notice_from_url($object);
Fave::removeEntry($actor, $notice);
}
/**
* Handles a Undo Follow Activity received by our inbox.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param Profile $actor Actor
* @param array $object Activity
* @throws AlreadyFulfilledException
* @throws HTTP_Request2_Exception
* @throws NoProfileException
* @throws ServerException
*/
private function handle_undo_follow($actor, $object)
{
// Get Object profile
$object_profile = new Activitypub_explorer;
$object_profile = $object_profile->lookup($object)[0];
if (Subscription::exists($actor, $object_profile)) {
Subscription::cancel($actor, $object_profile);
// You are no longer following this person.
} else {
// 409: You are not following this person already.
}
}
/**
* Handles a Announce Activity received by our inbox.
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @param Profile $actor Actor
* @param array $object Activity
* @throws Exception
*/
private function handle_announce($actor, $object)
{
$object_notice = ActivityPubPlugin::grab_notice_from_url($object);
$object_notice->repeat($actor, 'ActivityPub');
}
}

View File

@ -0,0 +1,348 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
defined('GNUSOCIAL') || die();
/**
* ActivityPub's own Postman
*
* Standard workflow expects that we send an Explorer to find out destinataries'
* inbox address. Then we send our postman to deliver whatever we want to send them.
*
* @category Plugin
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Activitypub_postman
{
private $actor;
private $actor_uri;
private $to = [];
private $client;
private $headers;
/**
* Create a postman to deliver something to someone
*
* @param Profile $from Profile of sender
* @param $to
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function __construct($from, $to)
{
$this->actor = $from;
$discovery = new Activitypub_explorer();
$this->to = $to;
$followers = apActorFollowersAction::generate_followers($this->actor, 0, null);
foreach ($followers as $sub) {
try {
$to[]= Activitypub_profile::from_profile($discovery->lookup($sub)[0]);
} catch (Exception $e) {
// Not an ActivityPub Remote Follower, let it go
}
}
unset($discovery);
$this->actor_uri = ActivityPubPlugin::actor_uri($this->actor);
$this->client = new HTTPClient();
}
/**
* Send something to remote instance
*
* @param string $data request body
* @param string $inbox url of remote inbox
* @param string $method request method
* @return GNUsocial_HTTPResponse
* @throws HTTP_Request2_Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function send($data, $inbox, $method = 'POST')
{
common_debug('ActivityPub Postman: Delivering '.$data.' to '.$inbox);
$headers = HttpSignature::sign($this->actor, $inbox, $data);
common_debug('ActivityPub Postman: Delivery headers were: '.print_r($headers, true));
$this->client->setBody($data);
switch ($method) {
case 'POST':
$response = $this->client->post($inbox, $headers);
break;
case 'GET':
$response = $this->client->get($inbox, $headers);
break;
default:
throw new Exception("Unsupported request method for postman.");
}
common_debug('ActivityPub Postman: Delivery result with status code '.$response->getStatus().': '.$response->getBody());
return $response;
}
/**
* Send a follow notification to remote instance
*
* @return bool
* @throws HTTP_Request2_Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function follow()
{
$data = Activitypub_follow::follow_to_array(ActivityPubPlugin::actor_uri($this->actor), $this->to[0]->getUrl());
$res = $this->send(json_encode($data, JSON_UNESCAPED_SLASHES), $this->to[0]->get_inbox());
$res_body = json_decode($res->getBody());
if ($res->getStatus() == 200 || $res->getStatus() == 202 || $res->getStatus() == 409) {
$pending_list = new Activitypub_pending_follow_requests($this->actor->getID(), $this->to[0]->getID());
$pending_list->add();
return true;
} elseif (isset($res_body[0]->error)) {
throw new Exception($res_body[0]->error);
}
throw new Exception("An unknown error occurred.");
}
/**
* Send a Undo Follow notification to remote instance
*
* @return bool
* @throws HTTP_Request2_Exception
* @throws Exception
* @throws Exception
* @throws Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function undo_follow()
{
$data = Activitypub_undo::undo_to_array(
Activitypub_follow::follow_to_array(
ActivityPubPlugin::actor_uri($this->actor),
$this->to[0]->getUrl()
)
);
$res = $this->send(json_encode($data, JSON_UNESCAPED_SLASHES), $this->to[0]->get_inbox());
$res_body = json_decode($res->getBody());
if ($res->getStatus() == 200 || $res->getStatus() == 202 || $res->getStatus() == 409) {
$pending_list = new Activitypub_pending_follow_requests($this->actor->getID(), $this->to[0]->getID());
$pending_list->remove();
return true;
}
if (isset($res_body[0]->error)) {
throw new Exception($res_body[0]->error);
}
throw new Exception("An unknown error occurred.");
}
/**
* Send a Accept Follow notification to remote instance
*
* @return bool
* @throws HTTP_Request2_Exception
* @throws Exception
* @throws Exception
* @throws Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function accept_follow()
{
$data = Activitypub_accept::accept_to_array(
Activitypub_follow::follow_to_array(
$this->to[0]->getUrl(),
ActivityPubPlugin::actor_uri($this->actor)
)
);
$res = $this->send(json_encode($data, JSON_UNESCAPED_SLASHES), $this->to[0]->get_inbox());
$res_body = json_decode($res->getBody());
if ($res->getStatus() == 200 || $res->getStatus() == 202 || $res->getStatus() == 409) {
$pending_list = new Activitypub_pending_follow_requests($this->actor->getID(), $this->to[0]->getID());
$pending_list->remove();
return true;
}
if (isset($res_body[0]->error)) {
throw new Exception($res_body[0]->error);
}
throw new Exception("An unknown error occurred.");
}
/**
* Send a Like notification to remote instances holding the notice
*
* @param Notice $notice
* @throws HTTP_Request2_Exception
* @throws InvalidUrlException
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function like($notice)
{
$data = Activitypub_like::like_to_array(
ActivityPubPlugin::actor_uri($this->actor),
$notice->getUrl()
);
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
foreach ($this->to_inbox() as $inbox) {
$this->send($data, $inbox);
}
}
/**
* Send a Undo Like notification to remote instances holding the notice
*
* @param Notice $notice
* @throws HTTP_Request2_Exception
* @throws InvalidUrlException
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function undo_like($notice)
{
$data = Activitypub_undo::undo_to_array(
Activitypub_like::like_to_array(
ActivityPubPlugin::actor_uri($this->actor),
$notice->getUrl()
)
);
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
foreach ($this->to_inbox() as $inbox) {
$this->send($data, $inbox);
}
}
/**
* Send a Create notification to remote instances
*
* @param Notice $notice
* @throws EmptyPkeyValueException
* @throws HTTP_Request2_Exception
* @throws InvalidUrlException
* @throws ServerException
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function create_note($notice)
{
$data = Activitypub_create::create_to_array(
$this->actor_uri,
Activitypub_notice::notice_to_array($notice)
);
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
foreach ($this->to_inbox() as $inbox) {
$this->send($data, $inbox);
}
}
/**
* Send a Announce notification to remote instances
*
* @param Notice $notice
* @throws HTTP_Request2_Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function announce($notice)
{
$data = Activitypub_announce::announce_to_array(
ActivityPubPlugin::actor_uri($this->actor),
$notice->getUri()
);
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
foreach ($this->to_inbox() as $inbox) {
$this->send($data, $inbox);
}
}
/**
* Send a Delete notification to remote instances holding the notice
*
* @param Notice $notice
* @throws HTTP_Request2_Exception
* @throws InvalidUrlException
* @throws Exception
* @throws Exception
* @author Diogo Cordeiro <diogo@fc.up.pt>
*/
public function delete($notice)
{
$data = Activitypub_delete::delete_to_array(
ActivityPubPlugin::actor_uri($notice->getProfile()),
$notice->getUrl()
);
$errors = [];
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
foreach ($this->to_inbox() as $inbox) {
$res = $this->send($data, $inbox);
if (!$res->getStatus() == 200) {
$res_body = json_decode($res->getBody(), true);
if (isset($res_body[0]['error'])) {
$errors[] = ($res_body[0]['error']);
continue;
}
$errors[] = ("An unknown error occurred.");
}
}
if (!empty($errors)) {
throw new Exception(json_encode($errors));
}
}
/**
* Clean list of inboxes to deliver messages
*
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @return array To Inbox URLs
*/
private function to_inbox()
{
$to_inboxes = [];
foreach ($this->to as $to_profile) {
$i = $to_profile->get_inbox();
// Prevent delivering to self
if ($i == [common_local_url('apInbox')]) {
continue;
}
$to_inboxes[] = $i;
}
return array_unique($to_inboxes);
}
}

View File

@ -0,0 +1,51 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-06-12 01:23+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
#. TRANS: Plugin description.
#: ActivityPubPlugin.php:212
msgid ""
"Follow people across social networks that implement <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
msgstr ""
#: ActivityPubPlugin.php:254
msgid "Remote Profile"
msgstr ""
#. TRANS: Title. %s is a domain name.
#: ActivityPubPlugin.php:909
#, php-format
msgid "Sent from %s via ActivityPub"
msgstr ""
#. TRANS: Exception.
#: classes/Activitypub_profile.php:355
msgid "Not a valid webfinger address (via cache)."
msgstr ""
#. TRANS: Exception.
#: classes/Activitypub_profile.php:376
msgid "Not a valid webfinger address."
msgstr ""
#. TRANS: Exception. %s is a webfinger address.
#: classes/Activitypub_profile.php:416
#, php-format
msgid "Could not find a valid profile for \"%s\"."
msgstr ""

View File

@ -0,0 +1,54 @@
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
# Diogo Cordeiro <diogo@fc.up.pt>, 2019
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-06-12 01:23+0100\n"
"PO-Revision-Date: 2019-06-12 01:23+0100\n"
"Last-Translator: Diogo Cordeiro <diogo@fc.up.pt>\n"
"Language-Team: English (United Kingdom) (http://www.transifex.com/gnu-social/gnu-social/language/en_GB/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: en_GB\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. TRANS: Plugin description.
#: ActivityPubPlugin.php:212
msgid ""
"Follow people across social networks that implement <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
msgstr ""
"Follow people across social networks that implement <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
#: ActivityPubPlugin.php:254
msgid "Remote Profile"
msgstr "Remote Profile"
#. TRANS: Title. %s is a domain name.
#: ActivityPubPlugin.php:909
#, php-format
msgid "Sent from %s via ActivityPub"
msgstr "Sent from %s via ActivityPub"
#. TRANS: Exception.
#: classes/Activitypub_profile.php:355
msgid "Not a valid webfinger address (via cache)."
msgstr "Not a valid WebFinger address (via cache)."
#. TRANS: Exception.
#: classes/Activitypub_profile.php:376
msgid "Not a valid webfinger address."
msgstr "Not a valid WebFinger address."
#. TRANS: Exception. %s is a webfinger address.
#: classes/Activitypub_profile.php:416
#, php-format
msgid "Could not find a valid profile for \"%s\"."
msgstr "Could not find a valid profile for \"%s\"."

View File

@ -0,0 +1,54 @@
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
# Diogo Cordeiro <diogo@fc.up.pt>, 2019
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-06-12 01:23+0100\n"
"PO-Revision-Date: 2019-06-12 01:23+0100\n"
"Last-Translator: Diogo Cordeiro <diogo@fc.up.pt>\n"
"Language-Team: Portuguese (http://www.transifex.com/gnu-social/gnu-social/language/pt/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: pt\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. TRANS: Plugin description.
#: ActivityPubPlugin.php:212
msgid ""
"Follow people across social networks that implement <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
msgstr ""
"Segue pessoas em redes sociais que implementam <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
#: ActivityPubPlugin.php:254
msgid "Remote Profile"
msgstr "Perfil Remoto"
#. TRANS: Title. %s is a domain name.
#: ActivityPubPlugin.php:909
#, php-format
msgid "Sent from %s via ActivityPub"
msgstr "Enviado por %s via ActivityPub"
#. TRANS: Exception.
#: classes/Activitypub_profile.php:355
msgid "Not a valid webfinger address (via cache)."
msgstr "Endereço WebFinger inválido (via cache)."
#. TRANS: Exception.
#: classes/Activitypub_profile.php:376
msgid "Not a valid webfinger address."
msgstr "Endereço WebFinger inválido."
#. TRANS: Exception. %s is a webfinger address.
#: classes/Activitypub_profile.php:416
#, php-format
msgid "Could not find a valid profile for \"%s\"."
msgstr "Não foi possível encontrar um perfil válido para \"%s\"."

View File

@ -0,0 +1,54 @@
# Translation file for GNU social - the free software social networking platform
# Copyright (C) 2015 - 2019 Free Software Foundation, Inc http://www.fsf.org
# This file is under https://www.gnu.org/licenses/agpl v3 or later
#
# Translators:
# Diogo Cordeiro <diogo@fc.up.pt>, 2019
msgid ""
msgstr ""
"Project-Id-Version: GNU social\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-06-12 01:23+0100\n"
"PO-Revision-Date: 2019-06-12 02:24+0100\n"
"Last-Translator: Diogo Cordeiro <diogo@fc.up.pt>\n"
"Language-Team: Portuguese (Brazil) (http://www.transifex.com/gnu-social/gnu-social/language/pt_BR/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: pt_BR\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. TRANS: Plugin description.
#: ActivityPubPlugin.php:212
msgid ""
"Follow people across social networks that implement <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
msgstr ""
"Segue pessoas em redes sociais que implementam <a href=\"https://"
"activitypub.rocks/\">ActivityPub</a>."
#: ActivityPubPlugin.php:254
msgid "Remote Profile"
msgstr "Perfil Remoto"
#. TRANS: Title. %s is a domain name.
#: ActivityPubPlugin.php:909
#, php-format
msgid "Sent from %s via ActivityPub"
msgstr "Enviado por %s via ActivityPub"
#. TRANS: Exception.
#: classes/Activitypub_profile.php:355
msgid "Not a valid webfinger address (via cache)."
msgstr "Endereço WebFinger inválido (via cache)."
#. TRANS: Exception.
#: classes/Activitypub_profile.php:376
msgid "Not a valid webfinger address."
msgstr "Endereço WebFinger inválido."
#. TRANS: Exception. %s is a webfinger address.
#: classes/Activitypub_profile.php:416
#, php-format
msgid "Could not find a valid profile for \"%s\"."
msgstr "Não foi possível encontrar um perfil válido para \"%s\"."

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,104 @@
#!/usr/bin/env php
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
define('INSTALLDIR', realpath(__DIR__ . '/../../..'));
$shortoptions = 'u:af';
$longoptions = ['uri=', 'all', 'force'];
$helptext = <<<END_OF_HELP
update_activitypub_profiles.php [options]
Refetch / update ActivityPub RSA keys, profile info and avatars. Useful if you
do something like accidentally delete your avatars directory when
you have no backup.
-u --uri ActivityPub profile URI to update
-a --all update all
END_OF_HELP;
require_once INSTALLDIR.'/scripts/commandline.inc';
$quiet = have_option('q', 'quiet');
if (!$quiet) {
echo "ActivityPub Profiles updater will now start!\n";
echo "Summoning Diogo Cordeiro, Richard Stallman and Chuck Norris to help us with this task!\n";
}
if (have_option('u', 'uri')) {
$uri = get_option_value('u', 'uri');
$discovery = new Activitypub_explorer();
$discovery = $discovery->lookup($uri);
if (empty($discovery)) {
echo "Bad URI\n";
exit(1);
}
$user = $discovery->lookup($uri)[0];
try {
$res = Activitypub_explorer::get_remote_user_activity($uri);
} catch (Exception $e) {
echo $e->getMessage()."\n";
exit(1);
}
if (!$quiet) {
echo "Updated ".Activitypub_profile::update_profile($user, $res)->getBestName()."\n";
}
} elseif (!have_option('a', 'all')) {
show_help();
exit(1);
}
$user = new Activitypub_profile();
$cnt = $user->find();
if (!empty($cnt)) {
if (!$quiet) {
echo "Found {$cnt} ActivityPub profiles:\n";
}
} else {
if (have_option('u', 'uri')) {
if (!$quiet) {
echo "Couldn't find an existing ActivityPub profile with that URI.\n";
}
} else {
if (!$quiet) {
echo "Couldn't find any existing ActivityPub profiles.\n";
}
}
exit(0);
}
while ($user->fetch()) {
try {
$res = Activitypub_explorer::get_remote_user_activity($user->uri);
$updated_profile = Activitypub_profile::update_profile($user, $res);
if (!$quiet) {
echo "Updated ".$updated_profile->getBestName()."\n";
}
} catch (Exception $e) {
// let it go
}
}

View File

@ -0,0 +1,52 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
namespace Tests;
trait CreatesApplication
{
/**
* Creates the application.
*
* @return todo
*/
public static function createApplication()
{
if (!defined('INSTALLDIR')) {
define('INSTALLDIR', __DIR__ . '/../../../');
}
if (!defined('GNUSOCIAL')) {
define('GNUSOCIAL', true);
}
if (!defined('STATUSNET')) {
define('STATUSNET', true); // compatibility
}
require INSTALLDIR . '/lib/common.php';
return true;
}
}

View File

@ -0,0 +1,39 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
namespace Tests;
use PHPUnit\Framework\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function setUp()
{
$this->createApplication();
}
}

View File

@ -0,0 +1,67 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
require 'AcceptHeader.php';
class ContainerTest extends \PHPUnit_Framework_TestCase
{
public function testHeader1()
{
$acceptHeader = new AcceptHeader('audio/*; q=0.2, audio/basic');
$this->assertEquals('audio/basic', $this->_getMedia($acceptHeader[0]));
$this->assertEquals('audio/*; q=0.2', $this->_getMedia($acceptHeader[1]));
}
public function testHeader2()
{
$acceptHeader = new AcceptHeader('text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5');
$this->assertEquals('text/html; level=1', $this->_getMedia($acceptHeader[0]));
$this->assertEquals('text/html; q=0.7', $this->_getMedia($acceptHeader[1]));
$this->assertEquals('*/*; q=0.5', $this->_getMedia($acceptHeader[2]));
$this->assertEquals('text/html; level=2; q=0.4', $this->_getMedia($acceptHeader[3]));
$this->assertEquals('text/*; q=0.3', $this->_getMedia($acceptHeader[4]));
}
public function testHeader3()
{
$acceptHeader = new AcceptHeader('text/*, text/html, text/html;level=1, */*');
$this->assertEquals('text/html; level=1', $this->_getMedia($acceptHeader[0]));
$this->assertEquals('text/html', $this->_getMedia($acceptHeader[1]));
$this->assertEquals('text/*', $this->_getMedia($acceptHeader[2]));
$this->assertEquals('*/*', $this->_getMedia($acceptHeader[3]));
}
private function _getMedia(array $mediaType)
{
$str = $mediaType['type'] . '/' . $mediaType['subtype'];
if (!empty($mediaType['params'])) {
foreach ($mediaType['params'] as $k => $v) {
$str .= '; ' . $k . '=' . $v;
}
}
return $str;
}
}

View File

@ -0,0 +1,183 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
namespace Tests\Unit;
use Tests\TestCase;
class ProfileObjectTest extends TestCase
{
public function testLibraryInstalled()
{
$this->assertTrue(class_exists('\Activitypub_profile'));
}
public function testActivitypubProfile()
{
// Mimic proper ACCEPT header
$_SERVER['HTTP_ACCEPT'] = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams';
/* Test do_insert() */
$aprofile = new \Activitypub_profile();
$aprofile->uri = 'https://testinstance.net/index.php/user/1';
$aprofile->nickname = 'test1';
$aprofile->fullname = 'Test User 1';
$aprofile->bio = 'I am a nice test 1 guy';
$aprofile->inboxuri = "https://testinstance.net/index.php/user/1/inbox.json";
$aprofile->sharedInboxuri = "https://testinstance.net/inbox.json";
$aprofile->do_insert();
/* Test local_profile() */
$profile = $aprofile->local_profile();
/* Test from_profile() and create_from_local_profile() */
$this->assertTrue($this->compare_aprofiles($aprofile, \Activitypub_profile::from_profile($profile)));
/* Create Keys for Test User 1 */
$apRSA = new \Activitypub_rsa();
$apRSA->profile_id = $profile->getID();
\Activitypub_rsa::generate_keys($apRSA->private_key, $apRSA->public_key);
$apRSA->store_keys();
/* Test profile_to_array() */
// Fetch ActivityPub Actor Object representation
$profile_array = \Activitypub_profile::profile_to_array($profile);
// Check type
$this->assertTrue(is_array($profile_array));
// Test with Explorer's Profile Tester
$this->assertTrue(\Activitypub_explorer::validate_remote_response($profile_array));
/* Test get_inbox() */
$this->assertTrue($aprofile->sharedInboxuri == $aprofile->get_inbox());
/* Test getUri() */
$this->assertTrue($aprofile->uri == $aprofile->getUri());
/* Test getUrl() */
$this->assertTrue($profile->getUrl() == $aprofile->getUrl());
/* Test getID() */
$this->assertTrue($profile->getID() == $aprofile->getID());
/* Test fromUri() */
$this->assertTrue($this->compare_aprofiles($aprofile, \Activitypub_profile::fromUri($aprofile->uri)));
/* Remove Remote User Test 1 */
$old_id = $profile->getID();
$apRSA->delete();
$aprofile->delete();
$profile->delete();
// Check if successfuly removed
try {
\Profile::getById($old_id);
$this->assertTrue(false);
} catch (\NoResultException $e) {
$this->assertTrue(true);
}
/* Test ensure_web_finger() */
// TODO: Maybe elaborate on this function's tests
try {
\Activitypub_profile::ensure_web_finger('test1@testinstance.net');
$this->assertTrue(false);
} catch (\Exception $e) {
$this->assertTrue($e->getMessage() == 'Not a valid webfinger address.' ||
$e->getMessage() == 'Not a valid webfinger address (via cache).');
}
}
// Helpers
private function compare_profiles(\Profile $a, \Profile $b)
{
if (($av = $a->getID()) != ($bv = $b->getID())) {
throw new Exception('Compare Profiles 1 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getNickname()) != ($bv = $b->getNickname())) {
throw new Exception('Compare Profiles 2 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getFullname()) != ($bv = $b->getFullname())) {
throw new Exception('Compare Profiles 3 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getUrl()) != ($bv = $b->getUrl())) {
throw new Exception('Compare Profiles 4 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getDescription()) != ($bv = $b->getDescription())) {
throw new Exception('Compare Profiles 5 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getLocation()) != ($bv = $b->getLocation())) {
throw new Exception('Compare Profiles 6 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getNickname()) != ($bv = $b->getNickname())) {
throw new Exception('Compare Profiles 7 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->lat) != ($bv = $b->lat)) {
throw new Exception('Compare Profiles 8 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->lon) != ($bv = $b->lon)) {
throw new Exception('Compare Profiles 9 Fail: $a: '.$av.' is different from $b: '.$bv);
}
return true;
}
private function compare_aprofiles(\Activitypub_profile $a, \Activitypub_profile $b)
{
if (($av = $a->getUri()) != ($bv = $b->getUri())) {
throw new Exception('Compare AProfiles 1 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getUrl()) != ($bv = $b->getUrl())) {
throw new Exception('Compare AProfiles 2 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->getID()) != ($bv = $b->getID())) {
throw new Exception('Compare AProfiles 3 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->profile_id) != ($bv = $b->profile_id)) {
throw new Exception('Compare AProfiles 4 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->inboxuri) != ($bv = $b->inboxuri)) {
throw new Exception('Compare AProfiles 5 Fail: $a: '.$av.' is different from $b: '.$bv);
}
if (($av = $a->sharedInboxuri) != ($bv = $b->sharedInboxuri)) {
throw new Exception('Compare AProfiles 6 Fail: $a: '.$av.' is different from $b: '.$bv);
}
return true;
}
}

View File

@ -0,0 +1,42 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
namespace Tests\Unit;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
}

View File

@ -0,0 +1,165 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social 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.
//
// GNU social 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 GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* ActivityPub implementation for GNU social
*
* @package GNUsocial
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
* @link http://www.gnu.org/software/social/
*/
namespace Tests\Unit;
use Tests\TestCase;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use HttpSignatures\Context;
use HttpSignatures\GuzzleHttpSignatures;
class HTTPSignatureTest extends TestCase
{
/**
* @var Context
*/
private $context;
/**
* @var Client
*/
private $client;
/**
* @var
*/
private $history = [];
public function testLibraryInstalled()
{
$this->assertTrue(class_exists('\GuzzleHttp\Client'));
$this->assertTrue(class_exists('\HttpSignatures\Context'));
$this->assertTrue(class_exists('\HttpSignatures\GuzzleHttpSignatures'));
}
public function setUp()
{
$this->context = new Context([
'keys' => ['pda' => 'secret'],
'algorithm' => 'hmac-sha256',
'headers' => ['(request-target)', 'date'],
]);
$stack = new HandlerStack();
$stack->setHandler(new MockHandler([
new Response(200, ['Content-Length' => 0]),
]));
$stack->push(GuzzleHttpSignatures::middlewareFromContext($this->context));
$stack->push(Middleware::history($this->history));
$this->client = new Client(['handler' => $stack]);
}
/**
* test signing a message
*/
public function testGuzzleRequestHasExpectedHeaders()
{
$this->client->get('/path?query=123', [
'headers' => ['date' => 'today', 'accept' => 'llamas']
]);
// get last request
$message = end($this->history);
/** @var Request $request */
$request = $message['request'];
/** @var Response $response */
$response = $message['request'];
$expectedString = implode(
',',
[
'keyId="pda"',
'algorithm="hmac-sha256"',
'headers="(request-target) date"',
'signature="SFlytCGpsqb/9qYaKCQklGDvwgmrwfIERFnwt+yqPJw="',
]
);
$this->assertEquals(
[$expectedString],
$request->getHeader('Signature')
);
$this->assertEquals(
['Signature ' . $expectedString],
$request->getHeader('Authorization')
);
}
/**
* test signing a message with a URL that doesn't contain a ?query
*/
public function testGuzzleRequestHasExpectedHeaders2()
{
$this->client->get('/path', [
'headers' => ['date' => 'today', 'accept' => 'llamas']
]);
// get last request
$message = end($this->history);
/** @var Request $request */
$request = $message['request'];
/** @var Response $response */
$response = $message['request'];
$expectedString = implode(
',',
[
'keyId="pda"',
'algorithm="hmac-sha256"',
'headers="(request-target) date"',
'signature="DAtF133khP05pS5Gh8f+zF/UF7mVUojMj7iJZO3Xk4o="',
]
);
$this->assertEquals(
[$expectedString],
$request->getHeader('Signature')
);
$this->assertEquals(
['Signature ' . $expectedString],
$request->getHeader('Authorization')
);
}
public function getVerifyGuzzleRequestVectors()
{
return [
/* path, headers */
['/path?query=123', ['date' => 'today', 'accept' => 'llamas']],
['/path?z=zebra&a=antelope', ['date' => 'today']],
];
}
/**
* @dataProvider getVerifyGuzzleRequestVectors
* @param string $path
* @param array $headers
*/
public function testVerifyGuzzleRequest($path, $headers)
{
$this->client->get($path, ['headers' => $headers]);
// get last request
$message = end($this->history);
/** @var Request $request */
$request = $message['request'];
/** @var Response $response */
$response = $message['request'];
$this->assertTrue($this->context->verifier()->isValid($request));
}
}