├── .distignore ├── .github └── workflows │ ├── deploy.yml │ └── stale.yml ├── .gitignore ├── LICENSE ├── README.md ├── assets ├── block-editor.js ├── share-on-mastodon.css └── share-on-mastodon.js ├── includes ├── class-block-editor.php ├── class-image-handler.php ├── class-mastodon-client.php ├── class-micropub-compat.php ├── class-notices.php ├── class-options-handler.php ├── class-plugin-options.php ├── class-post-handler.php ├── class-share-on-mastodon.php ├── class-syn-links-compat.php ├── database │ └── schema.php └── functions.php ├── languages └── share-on-mastodon.pot ├── phpcs.xml ├── phpunit.xml ├── readme.txt ├── share-on-mastodon.code-workspace └── share-on-mastodon.php /.distignore: -------------------------------------------------------------------------------- 1 | /.wordpress-org 2 | /.git 3 | /.github 4 | /node_modules 5 | /tests 6 | /vendor 7 | 8 | .distignore 9 | .gitignore 10 | .phpunit.result.cache 11 | README.md 12 | bootstrap.php 13 | composer.json 14 | composer.lock 15 | phpcs.xml 16 | phpunit.xml 17 | *.code-workspace 18 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to WordPress.org 2 | on: 3 | push: 4 | tags: 5 | - "*" 6 | jobs: 7 | tag: 8 | name: New tag 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@master 12 | - name: WordPress Plugin Deploy 13 | uses: 10up/action-wordpress-plugin-deploy@stable 14 | env: 15 | SVN_PASSWORD: ${{ secrets.SVN_PASSWORD }} 16 | SVN_USERNAME: ${{ secrets.SVN_USERNAME }} 17 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Close stale issues and PRs 2 | on: 3 | schedule: 4 | - cron: '30 1 * * *' 5 | 6 | jobs: 7 | stale: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/stale@v9 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore all files that start with ~ 2 | ~* 3 | 4 | # ignore OS-generated files 5 | ehthumbs.db 6 | Thumbs.db 7 | 8 | # ignore Editor files 9 | *.sublime-project 10 | *.sublime-workspace 11 | *.komodoproject 12 | 13 | # ignore log files, databases and shell scripts 14 | *.log 15 | *.sql 16 | *.sqlite 17 | *.sh 18 | 19 | # ignore compiled files 20 | *.com 21 | *.class 22 | *.dll 23 | *.exe 24 | *.o 25 | *.so 26 | 27 | # ignore packaged files 28 | *.7z 29 | *.dmg 30 | *.gz 31 | *.iso 32 | *.jar 33 | *.rar 34 | *.tar 35 | *.zip 36 | 37 | svn/ 38 | 39 | vendor/ 40 | .phpunit.result.cache 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Share on Mastodon 2 | Automatically share WordPress posts on [Mastodon](https://joinmastodon.org/). Supports image uploads (and alt text), custom formatting, and so on. 3 | 4 | Compatible with the classic as well as the block editor ("Gutenberg"). 5 | 6 | ## Compatibility With Mobile WordPress Apps 7 | Share on Mastodon supports 3rd-party WordPress apps, too, on the condition that the "Share Always" setting is enabled. (And, for more fine-grained control, there's [a filter hook](https://jan.boddez.net/wordpress/share-on-mastodon#share_on_mastodon_enabled).) 8 | 9 | ### Micropub 10 | Share on Mastodon can also be added as a Micropub syndication target, allowing you to enable (or disable) sharing right from your _Micropub client_. (You'll want to _disable_ "Share Always" for this.) 11 | 12 | ## Installation 13 | Simply download the plugin from https://wordpress.org/plugins/share-on-mastodon/ or install from within your WordPress' admin interface. 14 | 15 | ## Documentation 16 | Complete documentation as well as example code for extending Share on Mastodon can be found on https://jan.boddez.net/wordpress/share-on-mastodon. 17 | -------------------------------------------------------------------------------- /assets/block-editor.js: -------------------------------------------------------------------------------- 1 | ( ( element, components, i18n, data, coreData, plugins, editPost, apiFetch, url, share_on_mastodon_obj ) => { 2 | const el = element.createElement; 3 | const interpolate = element.createInterpolateElement; 4 | const useState = element.useState; 5 | const TextareaControl = components.TextareaControl; 6 | const TextControl = components.TextControl; 7 | const ToggleControl = components.ToggleControl; 8 | const __ = i18n.__; 9 | const sprintf = i18n.sprintf; 10 | const useSelect = data.useSelect; 11 | const registerPlugin = plugins.registerPlugin; 12 | const PluginDocumentSettingPanel = editPost.PluginDocumentSettingPanel; 13 | 14 | // @link https://wordpress.stackexchange.com/questions/362975/admin-notification-after-save-post-when-ajax-saving-in-gutenberg 15 | const doneSaving = () => { 16 | const { isSaving, isAutosaving, status } = useSelect( ( select ) => { 17 | return { 18 | isSaving: select( 'core/editor' ).isSavingPost(), 19 | isAutosaving: select( 'core/editor' ).isAutosavingPost(), 20 | status: select( 'core/editor' ).getEditedPostAttribute( 'status' ), 21 | }; 22 | } ); 23 | 24 | const [ wasSaving, setWasSaving ] = useState( isSaving && ! isAutosaving && 'publish' === status ); // Ignore autosaves, and unpublished posts. 25 | 26 | if ( wasSaving ) { 27 | if ( ! isSaving ) { 28 | setWasSaving( false ); 29 | return true; 30 | } 31 | } else if ( isSaving && ! isAutosaving && 'publish' === status ) { 32 | setWasSaving( true ); 33 | } 34 | 35 | return false; 36 | }; 37 | 38 | const isValidUrl = ( mastoUrl ) => { 39 | try { 40 | const parser = new URL( mastoUrl ); 41 | return true; 42 | } catch ( error ) { 43 | // Invalid URL. 44 | } 45 | 46 | return false; 47 | }; 48 | 49 | const displayUrl = ( mastoUrl ) => { 50 | const parser = new URL( mastoUrl ); 51 | 52 | return sprintf( 53 | '%1$s%2$s%3$s', 54 | parser.protocol + '://' + ( parser.username ? parser.username + ( parser.password ? ':' + parser.password : '' ) + '@' : '' ), 55 | parser.hostname.concat( parser.pathname ).slice( 0, 20 ), 56 | parser.hostname.concat( parser.pathname ).slice( 20 ), 57 | ); 58 | }; 59 | 60 | const updateUrl = ( postId, setMastoUrl, setError ) => { 61 | if ( ! postId ) { 62 | return false; 63 | } 64 | 65 | // Like a time-out. 66 | const controller = new AbortController(); 67 | const timeoutId = setTimeout( () => { 68 | controller.abort(); 69 | }, 6000 ); 70 | 71 | apiFetch( { 72 | path: url.addQueryArgs( '/share-on-mastodon/v1/url', { post_id: postId } ), 73 | signal: controller.signal, // That time-out thingy. 74 | } ).then( ( response ) => { 75 | clearTimeout( timeoutId ); 76 | 77 | if ( response.hasOwnProperty( 'url' ) && isValidUrl( response.url ) ) { 78 | setMastoUrl( response.url ); 79 | } 80 | 81 | setError( response.error ?? '' ); 82 | } ).catch( ( error ) => { 83 | // The request timed out or otherwise failed. Leave as is. 84 | console.debug( '[Share on Mastodon] "Get URL" request failed.' ); 85 | } ); 86 | }; 87 | 88 | const unlinkUrl = ( postId, setMastoUrl ) => { 89 | if ( ! postId ) { 90 | return false; 91 | } 92 | 93 | // Like a time-out. 94 | const controller = new AbortController(); 95 | const timeoutId = setTimeout( () => { 96 | controller.abort(); 97 | }, 6000 ); 98 | 99 | try { 100 | fetch( share_on_mastodon_obj.ajaxurl, { 101 | signal: controller.signal, // That time-out thingy. 102 | method: 'POST', 103 | body: new URLSearchParams( { 104 | action: 'share_on_mastodon_unlink_url', 105 | post_id: postId, 106 | share_on_mastodon_nonce: share_on_mastodon_obj.nonce, 107 | } ), 108 | } ).then( ( response ) => { 109 | clearTimeout( timeoutId ); 110 | setMastoUrl( '' ); // So as to trigger a re-render. 111 | } ).catch( ( error ) => { 112 | // The request timed out or otherwise failed. Leave as is. 113 | throw new Error( 'The "Unlink" request failed.' ) 114 | } ); 115 | } catch ( error ) { 116 | return false; 117 | } 118 | 119 | return true; 120 | }; 121 | 122 | registerPlugin( 'share-on-mastodon-panel', { 123 | render: ( props ) => { 124 | const { postId, postType } = useSelect( ( select ) => { 125 | return { 126 | postId: select( 'core/editor' ).getCurrentPostId(), 127 | postType: select( 'core/editor' ).getCurrentPostType(), 128 | } 129 | } ); 130 | 131 | // To be able to actually save post meta (namely, `_share_on_mastodon` and `_share_on_mastodon_status`). 132 | const [ meta, setMeta ] = coreData.useEntityProp( 'postType', postType, 'meta' ); 133 | 134 | // These are the custom fields we *don't* want to be set by `setMeta()`. 135 | const { record, isResolving } = coreData.useEntityRecord( 'postType', postType, postId ); 136 | const [ mastoUrl, setMastoUrl ] = useState( record?.share_on_mastodon?.url ?? '' ); 137 | const [ error, setError ] = useState( record?.share_on_mastodon?.error ?? '' ); 138 | 139 | if ( doneSaving() && '' === mastoUrl && '1' === meta._share_on_mastodon ) { 140 | // Post was updated, Mastodon URL is (still) empty. 141 | setTimeout( () => { 142 | // After a shortish delay, fetch, and store, the new URL (if any). 143 | updateUrl( postId, setMastoUrl, setError ); 144 | }, 1500 ); 145 | 146 | setTimeout( () => { 147 | // Just in case. I thought of `setInterval()`, but if after 15 seconds it's still not there, it's 148 | // likely not going to happen. Unless of course the "Delay" option is set to something larger, but 149 | // then there's no point in displaying this type of feedback anyway. 150 | updateUrl( postId, setMastoUrl, setError ); 151 | }, 15000 ); 152 | } 153 | 154 | // Wether to also show the `TextareaControl` component. 155 | const customStatusField = share_on_mastodon_obj?.custom_status_field ?? '0'; 156 | const contentWarning = share_on_mastodon_obj?.content_warning ?? '0'; 157 | 158 | return el( PluginDocumentSettingPanel, { 159 | name: 'share-on-mastodon-panel', 160 | title: __( 'Share on Mastodon', 'share-on-mastodon' ), 161 | }, 162 | el( ToggleControl, { 163 | label: __( 'Share on Mastodon', 'share-on-mastodon' ), 164 | checked: '1' === meta._share_on_mastodon, 165 | onChange: ( value ) => { 166 | setMeta( { ...meta, _share_on_mastodon: ( value ? '1' : '0' ) } ); 167 | }, 168 | } ), 169 | '1' === contentWarning 170 | ? [ 171 | el( TextControl, { 172 | label: __( '(Optional) Content Warning', 'share-on-mastodon' ), 173 | value: meta._share_on_mastodon_cw ?? '', 174 | onChange: ( value ) => { 175 | setMeta( { ...meta, _share_on_mastodon_cw: value } ); 176 | }, 177 | } ), 178 | ] 179 | : null, 180 | '1' === customStatusField 181 | ? el( 'div', { style: { marginTop: '1em', marginBottom: '0' } }, 182 | el( TextareaControl, { 183 | label: __( '(Optional) Custom Message', 'share-on-mastodon' ), 184 | value: meta._share_on_mastodon_status ?? '', 185 | onChange: ( value ) => { 186 | setMeta( { ...meta, _share_on_mastodon_status: value } ); 187 | }, 188 | } ), 189 | el ( 'p', { className: 'description' }, 190 | __( 'Customize this post’s Mastodon status.', 'share-on-mastodon' ), 191 | ), 192 | ) 193 | : null, 194 | '' !== mastoUrl && isValidUrl( mastoUrl ) 195 | ? el( 'p', { className: 'description', style: { marginTop: '1em', marginBottom: '0' } }, 196 | interpolate( sprintf( __( 'Shared at %s', 'share-on-mastodon' ), displayUrl( mastoUrl ) ), { 197 | a: el( 'a', { className: 'share-on-mastodon-url', href: encodeURI( mastoUrl ), target: '_blank', rel: 'noreferrer noopener' } ), 198 | b: el( 'span', { className: 'screen-reader-text' } ), 199 | c: el( 'span', { className: 'ellipsis' } ), 200 | } ), 201 | el( 'a', { 202 | className: 'share-on-mastodon-unlink', 203 | href: '#', 204 | onClick: () => { 205 | if ( confirm( __( 'Forget this URL?', 'share-on-mastodon' ) ) ) { 206 | unlinkUrl( postId, setMastoUrl ); 207 | } 208 | }, 209 | }, 210 | __( 'Unlink', 'share-on-mastodon' ) 211 | ) 212 | ) 213 | : null, 214 | '' !== error && '' === mastoUrl 215 | ? el( 'p', { className: 'description', style: { marginTop: '1em', marginBottom: '0' } }, error ) 216 | : null, 217 | ); 218 | }, 219 | } ); 220 | } )( window.wp.element, window.wp.components, window.wp.i18n, window.wp.data, window.wp.coreData, window.wp.plugins, window.wp.editPost, window.wp.apiFetch, window.wp.url, window.share_on_mastodon_obj ); 221 | -------------------------------------------------------------------------------- /assets/share-on-mastodon.css: -------------------------------------------------------------------------------- 1 | #share-on-mastodon .description { 2 | margin: 1em 0 1px; 3 | } 4 | 5 | #share-on-mastodon .url .ellipsis, 6 | .share-on-mastodon-url .ellipsis { 7 | word-break: break-word; 8 | } 9 | 10 | .share-on-mastodon-url, 11 | .share-on-mastodon-url:active, 12 | .share-on-mastodon-url:hover, 13 | .share-on-mastodon-url:focus { 14 | margin-inline-end: 0.33em; 15 | color: #007cba; 16 | } 17 | 18 | #share-on-mastodon .url .ellipsis::after, 19 | .share-on-mastodon-url .ellipsis::after { 20 | word-break: break-word; 21 | content: "\2026"; 22 | } 23 | 24 | #share-on-mastodon .unlink { 25 | color: #a00; 26 | } 27 | 28 | .share-on-mastodon-unlink, 29 | .share-on-mastodon-unlink:active, 30 | .share-on-mastodon-unlink:hover, 31 | .share-on-mastodon-unlink:focus { 32 | color: #cc1818; 33 | } 34 | 35 | .settings_page_share-on-mastodon th label, 36 | .settings_page_share-on-mastodon th .label { 37 | vertical-align: baseline; 38 | } 39 | 40 | .settings_page_share-on-mastodon fieldset { 41 | border: 1px solid #ccc; 42 | box-sizing: border-box; 43 | font-size: 14px; 44 | margin: 2em 0 1em; 45 | max-width: 67%; 46 | padding: 1.25em; 47 | } 48 | 49 | .settings_page_share-on-mastodon .form-group { 50 | align-items: center; 51 | display: flex; 52 | gap: 1.25em; 53 | justify-content: space-between; 54 | } 55 | -------------------------------------------------------------------------------- /assets/share-on-mastodon.js: -------------------------------------------------------------------------------- 1 | document.addEventListener( 'DOMContentLoaded', function() { 2 | document.querySelector( '#share-on-mastodon .unlink' )?.addEventListener( 'click', ( event ) => { 3 | event.preventDefault(); 4 | 5 | if ( ! confirm( share_on_mastodon_obj.message ) ) { 6 | return; 7 | } 8 | 9 | const button = event.target; 10 | const isGutenberg = ( 'undefined' !== typeof wp && 'undefined' !== typeof wp.blocks ); 11 | 12 | // Like a time-out. 13 | const controller = new AbortController(); 14 | const timeoutId = setTimeout( () => { 15 | controller.abort(); 16 | }, 6000 ); 17 | 18 | fetch( share_on_mastodon_obj.ajaxurl, { 19 | signal: controller.signal, // That time-out thingy. 20 | method: 'POST', 21 | body: new URLSearchParams( { 22 | 'action': 'share_on_mastodon_unlink_url', 23 | 'post_id': share_on_mastodon_obj.post_id, 24 | 'share_on_mastodon_nonce': share_on_mastodon_obj.nonce, 25 | 'is_gutenberg': isGutenberg, 26 | } ), 27 | } ).then( ( response ) => { 28 | clearTimeout( timeoutId ); 29 | 30 | const checkbox = document.querySelector( 'input[name="share_on_mastodon"]' ); 31 | if ( checkbox && isGutenberg ) { 32 | // Uncheck only within a block editor context. 33 | checkbox.checked = false; 34 | } 35 | 36 | button.parentNode.remove(); 37 | } ).catch( ( error ) => { 38 | // The request timed out or otherwise failed. 39 | } ); 40 | } ); 41 | 42 | document.querySelector( '.settings_page_share-on-mastodon .button-reset-settings' )?.addEventListener( 'click', ( event ) => { 43 | if ( ! confirm( share_on_mastodon_obj.message ) ) { 44 | event.preventDefault(); 45 | } 46 | } ); 47 | } ); 48 | -------------------------------------------------------------------------------- /includes/class-block-editor.php: -------------------------------------------------------------------------------- 1 | post_type ) && ! in_array( $current_screen->post_type, $options['post_types'], true ) ) ) { 40 | return; 41 | } 42 | 43 | wp_enqueue_script( 44 | 'share-on-mastodon-editor', 45 | plugins_url( '/assets/block-editor.js', __DIR__ ), 46 | array( 47 | 'wp-element', 48 | 'wp-components', 49 | 'wp-i18n', 50 | 'wp-data', 51 | 'wp-core-data', 52 | 'wp-plugins', 53 | 'wp-edit-post', 54 | 'wp-api-fetch', 55 | 'wp-url', 56 | 'share-on-mastodon', 57 | ), 58 | Share_On_Mastodon::PLUGIN_VERSION, 59 | false 60 | ); 61 | } 62 | 63 | /** 64 | * Registers block-related REST API endpoints. 65 | */ 66 | public static function register_api_endpoints() { 67 | register_rest_route( 68 | 'share-on-mastodon/v1', 69 | '/url', 70 | array( 71 | 'methods' => array( 'GET' ), 72 | 'callback' => array( __CLASS__, 'get_meta' ), 73 | 'permission_callback' => function ( $request ) { 74 | $post_id = $request->get_param( 'post_id' ); 75 | 76 | if ( empty( $post_id ) || ! ctype_digit( (string) $post_id ) ) { 77 | return false; 78 | } 79 | 80 | return current_user_can( 'edit_post', $post_id ); 81 | }, 82 | ) 83 | ); 84 | } 85 | 86 | /** 87 | * Exposes Share on Mastodon's metadata to the REST API. 88 | * 89 | * Can be called from either `register_rest_route()` or `register_rest_field()`. 90 | * 91 | * @param \WP_REST_Request|array $request API request (parameters). 92 | * @return array|\WP_Error Response, or error on failure. 93 | */ 94 | public static function get_meta( $request ) { 95 | if ( is_array( $request ) ) { 96 | $post_id = $request['id']; 97 | } else { 98 | $post_id = $request->get_param( 'post_id' ); 99 | } 100 | 101 | if ( empty( $post_id ) || ! ctype_digit( (string) $post_id ) ) { 102 | return new \WP_Error( 'invalid_id', 'Invalid post ID.', array( 'status' => 400 ) ); 103 | } 104 | 105 | $post_id = (int) $post_id; 106 | 107 | $url = get_post_meta( $post_id, '_share_on_mastodon_url', true ); 108 | 109 | return array( 110 | 'url' => get_post_meta( $post_id, '_share_on_mastodon_url', true ), 111 | 'error' => empty( $url ) // Don't bother if we've got a URL. 112 | ? get_post_meta( $post_id, '_share_on_mastodon_error', true ) 113 | : '', 114 | ); 115 | } 116 | 117 | /** 118 | * Registers Share on Mastodon's custom fields for use with the REST API. 119 | */ 120 | public static function register_meta() { 121 | $options = get_options(); 122 | 123 | if ( empty( $options['post_types'] ) ) { 124 | return; 125 | } 126 | 127 | $post_types = (array) $options['post_types']; 128 | 129 | foreach ( $post_types as $post_type ) { 130 | // Expose Share on Mastodon's custom fields to the REST API. Will appear as a separate `share_on_mastodon` 131 | // property. 132 | register_rest_field( 133 | $post_type, 134 | 'share_on_mastodon', 135 | array( 136 | 'get_callback' => array( __CLASS__, 'get_meta' ), 137 | 'update_callback' => null, // These are updated solely in the background. 138 | ) 139 | ); 140 | 141 | if ( use_block_editor_for_post_type( $post_type ) && empty( $options['meta_box'] ) ) { 142 | // Allow these fields to be *set* by the block editor. These will appear as properties of the post's 143 | // `meta` property. 144 | register_post_meta( 145 | $post_type, 146 | '_share_on_mastodon', 147 | array( 148 | 'single' => true, 149 | 'show_in_rest' => true, 150 | 'type' => 'string', 151 | 'auth_callback' => function ( $allowed, $meta_key, $post_id ) { 152 | if ( empty( $post_id ) || ! ctype_digit( (string) $post_id ) ) { 153 | return false; 154 | } 155 | 156 | return current_user_can( 'edit_post', $post_id ); 157 | }, 158 | 'sanitize_callback' => function ( $meta_value ) { 159 | return '1' === $meta_value ? '1' : '0'; 160 | }, 161 | ) 162 | ); 163 | 164 | // No need to register (and thus save) anything we won't be using. 165 | if ( ! empty( $options['custom_status_field'] ) ) { 166 | register_post_meta( 167 | $post_type, 168 | '_share_on_mastodon_status', 169 | array( 170 | 'single' => true, 171 | 'show_in_rest' => true, 172 | 'type' => 'string', 173 | 'default' => ! empty( $options['status_template'] ) ? $options['status_template'] : '', 174 | 'auth_callback' => function ( $allowed, $meta_key, $post_id ) { 175 | if ( empty( $post_id ) || ! ctype_digit( (string) $post_id ) ) { 176 | return false; 177 | } 178 | 179 | return current_user_can( 'edit_post', $post_id ); 180 | }, 181 | 'sanitize_callback' => function ( $status ) { 182 | $status = sanitize_textarea_field( $status ); 183 | $status = preg_replace( '~\R~u', "\r\n", $status ); 184 | return $status; 185 | }, 186 | ) 187 | ); 188 | } 189 | 190 | if ( ! empty( $options['content_warning'] ) ) { 191 | register_post_meta( 192 | $post_type, 193 | '_share_on_mastodon_cw', 194 | array( 195 | 'single' => true, 196 | 'show_in_rest' => true, 197 | 'type' => 'string', 198 | 'default' => '', 199 | 'auth_callback' => function ( $allowed, $meta_key, $post_id ) { 200 | if ( empty( $post_id ) || ! ctype_digit( (string) $post_id ) ) { 201 | return false; 202 | } 203 | 204 | return current_user_can( 'edit_post', $post_id ); 205 | }, 206 | 'sanitize_callback' => function ( $content_warning ) { 207 | return sanitize_text_field( $content_warning ); 208 | }, 209 | ) 210 | ); 211 | } 212 | } 213 | } 214 | } 215 | 216 | /** 217 | * Returns default meta for `_share_on_mastodon`. 218 | * 219 | * @param mixed $value Default value. 220 | * @param int $object_id Object ID. 221 | * @param string $meta_key Meta key. 222 | * @param bool $single Whether to return only the first value. 223 | * @return mixed (Filtered) default value. 224 | */ 225 | public static function get_default_meta( $value, $object_id, $meta_key, $single ) { 226 | if ( '_share_on_mastodon' !== $meta_key ) { 227 | return $value; 228 | } 229 | 230 | $default = '1'; 231 | 232 | if ( is_older_than( HOUR_IN_SECONDS / 2, $object_id ) ) { 233 | $default = '0'; 234 | } 235 | 236 | $options = get_options(); 237 | if ( apply_filters( 'share_on_mastodon_optin', ! empty( $options['optin'] ) ) ) { 238 | // Opt-in. 239 | $default = '0'; 240 | } 241 | 242 | return ! $single 243 | ? array( $default ) 244 | : $default; 245 | } 246 | 247 | /** 248 | * Bypasses saving post meta when doing so would not have any effect. 249 | * 250 | * @param mixed $check Whether to allow updating metadata for the given type. 251 | * @param int $object_id Object ID. 252 | * @param string $meta_key Meta key. 253 | * @param mixed $meta_value Metadata value. 254 | * @return mixed Whether to allow updating metadata for the given type. A _non-null_ value will bypass updating. 255 | */ 256 | public static function maybe_skip_save_meta( $check, $object_id, $meta_key, $meta_value ) { 257 | if ( '_share_on_mastodon_status' === $meta_key && '' === $meta_value && null === get_metadata_raw( 'post', $object_id, $meta_key, true ) ) { 258 | // No current value exists, but the new value would equal the default. No need to save, then. 259 | return true; 260 | } 261 | 262 | if ( '_share_on_mastodon_cw' === $meta_key && '' === $meta_value && null === get_metadata_raw( 'post', $object_id, $meta_key, true ) ) { 263 | // No current value exists, but the new value would equal the default. No need to save, then. 264 | return true; 265 | } 266 | 267 | return $check; 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /includes/class-image-handler.php: -------------------------------------------------------------------------------- 1 | ID ) && apply_filters( 'share_on_mastodon_featured_image', $enable_featured_image, $post ); 26 | 27 | $enable_attached_images = ! isset( $options['attached_images'] ) || $options['attached_images']; 28 | $enable_attached_images = apply_filters( 'share_on_mastodon_attached_images', $enable_attached_images, $post ); 29 | 30 | if ( ! ( $enable_referenced_images || $enable_featured_image || $enable_attached_images ) ) { 31 | // Nothing to do. 32 | return array(); 33 | } 34 | 35 | // Always parse post content for images and alt text. 36 | $referenced_images = static::get_referenced_images( $post ); 37 | 38 | // Alright, let's get started. 39 | $media_ids = array(); 40 | 41 | if ( $enable_featured_image ) { 42 | // Include featured image. 43 | $media_ids[] = get_post_thumbnail_id( $post->ID ); 44 | } 45 | 46 | if ( $enable_referenced_images && ! empty( $referenced_images ) ) { 47 | // Add in-post images. 48 | $media_ids = array_merge( $media_ids, array_keys( $referenced_images ) ); // We're interested only in the IDs, for now. 49 | } 50 | 51 | if ( $enable_attached_images ) { 52 | // Include all attached images. 53 | $attachments = get_attached_media( 'image', $post->ID ); 54 | 55 | if ( ! empty( $attachments ) ) { 56 | foreach ( $attachments as $attachment ) { 57 | $media_ids[] = $attachment->ID; 58 | } 59 | } 60 | } 61 | 62 | // Remove duplicates, and (even though it isn't _really_ needed) reindex. 63 | $media_ids = array_values( array_unique( $media_ids ) ); 64 | // Allow developers to filter the array of media IDs. 65 | $media_ids = (array) apply_filters( 'share_on_mastodon_media', $media_ids, $post ); 66 | 67 | // Convert the array of media IDs into something of the format `array( $id => 'Alt text.' )`. 68 | $media = static::add_alt_text( $media_ids, $referenced_images ); 69 | 70 | debug_log( '[Share on Mastodon] The images selected for crossposting (but not yet limited to 4):' ); 71 | debug_log( $media ); 72 | 73 | debug_log( '[Share on Mastodon] The images as found in the post:' ); 74 | debug_log( $referenced_images ); 75 | 76 | return $media; 77 | } 78 | 79 | /** 80 | * Attempts to find and return in-post images. 81 | * 82 | * @param \WP_Post $post Post object. 83 | * @return array Image array. 84 | */ 85 | protected static function get_referenced_images( $post ) { 86 | $images = array(); 87 | 88 | // Wrap post content in a dummy `div`, as there must (!) be a root-level element at all times. 89 | $html = '
' . mb_convert_encoding( $post->post_content, 'HTML-ENTITIES', get_bloginfo( 'charset' ) ) . '
'; 90 | 91 | $use_errors = libxml_use_internal_errors( true ); 92 | 93 | $doc = new \DOMDocument(); 94 | $doc->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); 95 | $xpath = new \DOMXPath( $doc ); 96 | 97 | foreach ( $xpath->query( '//img' ) as $node ) { 98 | if ( ! $node->hasAttribute( 'src' ) || empty( $node->getAttribute( 'src' ) ) ) { 99 | continue; 100 | } 101 | 102 | $src = $node->getAttribute( 'src' ); 103 | $filename = pathinfo( $src, PATHINFO_FILENAME ); 104 | $original = preg_replace( '~-(?:\d+x\d+|scaled|rotated)$~', '', $filename ); // Strip dimensions, etc., off resized images. 105 | 106 | $url = str_replace( $filename, $original, $src ); 107 | 108 | // Convert URL back to attachment ID. 109 | $image_id = attachment_url_to_postid( $url ); 110 | 111 | if ( 0 === $image_id ) { 112 | // Unknown to WordPress. 113 | continue; 114 | } 115 | 116 | if ( ! isset( $images[ $image_id ] ) || '' === $images[ $image_id ] ) { 117 | // When an image is already present, overwrite it only if its 118 | // "known" alt text is empty. 119 | $images[ $image_id ] = $node->hasAttribute( 'alt' ) ? $node->getAttribute( 'alt' ) : ''; 120 | } 121 | } 122 | 123 | libxml_use_internal_errors( $use_errors ); 124 | 125 | return $images; 126 | } 127 | 128 | /** 129 | * Uploads an attachment and returns a (single) media ID. 130 | * 131 | * @param int $image_id Attachment ID. 132 | * @param string $alt Alt text. 133 | * @param array $options Mastodon (API) settings to use. 134 | * @return string|null Unique media ID, or `null` on failure. 135 | */ 136 | public static function upload_image( $image_id, $alt, $options ) { 137 | if ( wp_attachment_is_image( $image_id ) ) { 138 | // Grab the image's "large" thumbnail. 139 | $image = wp_get_attachment_image_src( $image_id, apply_filters( 'share_on_mastodon_image_size', 'large', $image_id ) ); 140 | } 141 | 142 | $uploads = wp_upload_dir(); 143 | 144 | if ( ! empty( $image[0] ) && 0 === strpos( $image[0], $uploads['baseurl'] ) ) { 145 | // Found a "large" thumbnail that lives on our own site (and not, e.g., a CDN). 146 | $url = $image[0]; 147 | } else { 148 | // Get the original attachment URL. Note that Mastodon has an upload limit of 8 MB. Either way, this should 149 | // return a *local* URL. 150 | $url = wp_get_attachment_url( $image_id ); 151 | } 152 | 153 | $file_path = str_replace( $uploads['baseurl'], $uploads['basedir'], $url ); 154 | 155 | if ( ! is_file( $file_path ) ) { 156 | // File doesn't seem to exist. 157 | debug_log( "[Share on Mastodon] Could not read the image at `$file_path`." ); 158 | return; 159 | } 160 | 161 | $boundary = md5( time() ); 162 | $eol = "\r\n"; 163 | 164 | $body = '--' . $boundary . $eol; 165 | 166 | if ( '' !== $alt ) { 167 | debug_log( "[Share on Mastodon] Found the following alt text for the attachment with ID $image_id: `$alt`." ); 168 | 169 | // Send along an image description, because accessibility. 170 | $body .= 'Content-Disposition: form-data; name="description";' . $eol . $eol; 171 | $body .= $alt . $eol; 172 | $body .= '--' . $boundary . $eol; 173 | } else { 174 | debug_log( "[Share on Mastodon] Did not find alt text for the attachment with ID $image_id." ); 175 | } 176 | 177 | // The actual (binary) image data. 178 | $body .= 'Content-Disposition: form-data; name="file"; filename="' . basename( $file_path ) . '"' . $eol; 179 | $body .= 'Content-Type: ' . static::get_content_type( $file_path ) . $eol . $eol; 180 | $body .= file_get_contents( $file_path ) . $eol; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents 181 | $body .= '--' . $boundary . '--'; // Note the extra two hyphens at the end. 182 | 183 | $response = wp_safe_remote_post( 184 | esc_url_raw( $options['mastodon_host'] . '/api/v1/media' ), 185 | array( 186 | 'headers' => array( 187 | 'Authorization' => 'Bearer ' . $options['mastodon_access_token'], 188 | 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, 189 | ), 190 | 'data_format' => 'body', 191 | 'body' => $body, 192 | 'timeout' => 15, 193 | 'limit_response_size' => 1048576, 194 | ) 195 | ); 196 | 197 | if ( is_wp_error( $response ) ) { 198 | // An error occurred. 199 | debug_log( $response ); 200 | return; 201 | } 202 | 203 | $media = json_decode( $response['body'] ); 204 | 205 | if ( ! empty( $media->id ) ) { 206 | return $media->id; 207 | } 208 | 209 | // Provided debugging's enabled, let's store the (somehow faulty) response. 210 | debug_log( $response ); 211 | } 212 | 213 | /** 214 | * Returns alt text for a certain image. 215 | * 216 | * Looks through `$images` first, and falls back on what's stored in the 217 | * `wp_postmeta` table. 218 | * 219 | * @param array $image_ids IDs of images we want to upload. 220 | * @param array $referenced_images In-post images and their alt attributes, to look through first. 221 | * @return array An array with image IDs as its keys and these images' alt attributes as its values. 222 | */ 223 | protected static function add_alt_text( $image_ids, $referenced_images ) { 224 | $images = array(); 225 | 226 | foreach ( $image_ids as $image_id ) { 227 | if ( isset( $referenced_images[ $image_id ] ) && '' !== $referenced_images[ $image_id ] ) { 228 | // This image was found inside the post, with alt text. 229 | $alt = $referenced_images[ $image_id ]; 230 | } else { 231 | // Fetch alt text from the `wp_postmeta` table. 232 | $alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true ); 233 | 234 | if ( '' === $alt ) { 235 | $alt = wp_get_attachment_caption( $image_id ); // Fallback to caption. Might return `false`. 236 | } 237 | } 238 | 239 | $images[ $image_id ] = is_string( $alt ) 240 | ? html_entity_decode( $alt, ENT_QUOTES | ENT_HTML5, get_bloginfo( 'charset' ) ) // Avoid double-encoded entities. 241 | : ''; 242 | } 243 | 244 | return $images; 245 | } 246 | 247 | /** 248 | * Returns a MIME content type for a certain file. 249 | * 250 | * @param string $file_path File path. 251 | * @return string MIME type. 252 | */ 253 | protected static function get_content_type( $file_path ) { 254 | if ( function_exists( 'mime_content_type' ) ) { 255 | $result = mime_content_type( $file_path ); 256 | 257 | if ( is_string( $result ) ) { 258 | return $result; 259 | } 260 | } 261 | 262 | if ( function_exists( 'finfo_open' ) && function_exists( 'finfo_file' ) ) { 263 | $finfo = finfo_open( FILEINFO_MIME_TYPE ); 264 | $result = finfo_file( $finfo, $file_path ); 265 | 266 | if ( is_string( $result ) ) { 267 | return $result; 268 | } 269 | } 270 | 271 | $ext = pathinfo( $file_path, PATHINFO_EXTENSION ); 272 | if ( ! empty( $ext ) ) { 273 | $mime_types = wp_get_mime_types(); 274 | foreach ( $mime_types as $key => $value ) { 275 | if ( in_array( $ext, explode( '|', $key ), true ) ) { 276 | return $value; 277 | } 278 | } 279 | } 280 | 281 | return 'application/octet-stream'; 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /includes/class-mastodon-client.php: -------------------------------------------------------------------------------- 1 | get_results( $wpdb->prepare( $sql, $where['host'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared 32 | } 33 | 34 | if ( is_int( $where ) ) { 35 | $sql = sprintf( 'SELECT * FROM %s WHERE id = %%d', static::table() ); 36 | 37 | // Return just one row. 38 | return $wpdb->get_row( $wpdb->prepare( $sql, $where ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared 39 | } 40 | 41 | return null; 42 | } 43 | 44 | /** 45 | * Inserts a newly registered app. 46 | * 47 | * @param array $data Associative array representing an API client. 48 | * @return int (Internal) app ID. 49 | */ 50 | public static function insert( $data ) { 51 | global $wpdb; 52 | 53 | $data['created_at'] = current_time( 'mysql', 1 ); 54 | 55 | if ( $wpdb->insert( static::table(), $data ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery 56 | return $wpdb->insert_id; 57 | } 58 | 59 | return 0; 60 | } 61 | 62 | /** 63 | * Updates an existing app. 64 | * 65 | * @param array $data Associative array representing an API client. 66 | * @param array $where Associative array representing a "where" clause. 67 | * @return int|false Number of rows affected, or `false` on failure. 68 | */ 69 | public static function update( $data, $where ) { 70 | global $wpdb; 71 | 72 | $data['modified_at'] = current_time( 'mysql', 1 ); 73 | 74 | return $wpdb->update( static::table(), $data, $where ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 75 | } 76 | 77 | /** 78 | * Deletes an app. 79 | * 80 | * @param int $id App ID. 81 | * @return int|false Number of rows affected, or `false` on failure. 82 | */ 83 | public static function delete( $id ) { 84 | global $wpdb; 85 | 86 | $sql = sprintf( 'DELETE FROM %s WHERE id = %%s', static::table() ); 87 | 88 | return $wpdb->query( $wpdb->prepare( $sql, $id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared 89 | } 90 | 91 | /** 92 | * Returns (prefixed) table name. 93 | * 94 | * @return string Table name. 95 | */ 96 | public static function table() { 97 | global $wpdb; 98 | 99 | return $wpdb->prefix . static::TABLE; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /includes/class-micropub-compat.php: -------------------------------------------------------------------------------- 1 | "{$options['mastodon_host']}/@{$options['mastodon_username']}", 41 | 'name' => "Mastodon ({$options['mastodon_username']})", 42 | ); 43 | 44 | return $syndicate_to; 45 | } 46 | 47 | /** 48 | * Triggers syndication to Mastodon. 49 | * 50 | * @param int $post_id Post ID. 51 | * @param array $synd_requested Selected syndication targets. 52 | */ 53 | public static function syndication( $post_id, $synd_requested ) { 54 | $post = get_post( $post_id ); 55 | $options = apply_filters( 'share_on_mastodon_options', get_options(), ! empty( $post->post_author ) ? $post->post_author : 0 ); 56 | 57 | if ( empty( $options['mastodon_host'] ) ) { 58 | return; 59 | } 60 | 61 | if ( empty( $options['mastodon_username'] ) ) { 62 | return; 63 | } 64 | 65 | if ( in_array( "{$options['mastodon_host']}/@{$options['mastodon_username']}", $synd_requested, true ) ) { 66 | update_post_meta( $post_id, '_share_on_mastodon', '1' ); 67 | delete_post_meta( $post_id, '_share_on_mastodon_error' ); // Clear previous errors, if any. 68 | 69 | // Trigger syndication. 70 | Share_On_Mastodon::get_instance() 71 | ->get_post_handler() 72 | ->toot( $post ); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /includes/class-notices.php: -------------------------------------------------------------------------------- 1 | ID, '_share_on_mastodon_error', true ); 43 | 44 | if ( '' === $error_message ) { 45 | return; 46 | } 47 | ?> 48 |
49 | 50 |

' . esc_html( $error_message ) . '' ); ?>

51 |
52 | ID, '_share_on_mastodon_url', true ); 58 | 59 | if ( '' === $url || ! wp_http_validate_url( $url ) ) { 60 | return; 61 | } 62 | 63 | $url_parts = wp_parse_url( $url ); 64 | 65 | $display_url = '' . $url_parts['scheme'] . '://'; 66 | $display_url .= ( ! empty( $url_parts['user'] ) ? $url_parts['user'] . ( ! empty( $url_parts['pass'] ) ? ':' . $url_parts['pass'] : '' ) . '@' : '' ) . ''; 67 | $display_url .= '' . mb_substr( $url_parts['host'] . $url_parts['path'], 0, 20 ) . '' . mb_substr( $url_parts['host'] . $url_parts['path'], 20 ) . ''; 68 | ?> 69 |
70 | 71 |

' . $display_url . '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

72 |
73 | '1' ), 88 | esc_url_raw( $location ) 89 | ); 90 | } 91 | 92 | /** 93 | * Tells WordPress to display the "error" notice. 94 | * 95 | * @param string $location The destination URL. 96 | * @return string Updated destination URL. 97 | */ 98 | public static function add_error_query_var( $location ) { 99 | remove_filter( 'redirect_post_location', array( __CLASS__, 'add_error_query_var' ) ); 100 | 101 | return add_query_arg( 102 | array( 'share_on_mastodon_success' => '0' ), 103 | esc_url_raw( $location ) 104 | ); 105 | } 106 | 107 | /** 108 | * Adds our query arguments to WordPress' so-called removable query arguments. 109 | * 110 | * @param array $args Array of query variables to remove from a URL. 111 | * @return array Filtered array. 112 | */ 113 | public static function removable_query_args( $args ) { 114 | $args[] = 'share_on_mastodon_success'; 115 | 116 | return $args; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /includes/class-options-handler.php: -------------------------------------------------------------------------------- 1 | array( 17 | 'type' => 'string', 18 | 'default' => '', 19 | ), 20 | 'mastodon_client_id' => array( 21 | 'type' => 'string', 22 | 'default' => '', 23 | ), 24 | 'mastodon_client_secret' => array( 25 | 'type' => 'string', 26 | 'default' => '', 27 | ), 28 | 'mastodon_access_token' => array( 29 | 'type' => 'string', 30 | 'default' => '', 31 | ), 32 | 'mastodon_username' => array( 33 | 'type' => 'string', 34 | 'default' => '', 35 | ), 36 | 'post_types' => array( 37 | 'type' => 'array', 38 | 'default' => array( 'post' ), 39 | 'items' => array( 'type' => 'string' ), 40 | ), 41 | 'featured_images' => array( 42 | 'type' => 'boolean', 43 | 'default' => true, 44 | ), 45 | 'attached_images' => array( 46 | 'type' => 'boolean', 47 | 'default' => true, 48 | ), 49 | 'referenced_images' => array( 50 | 'type' => 'boolean', 51 | 'default' => false, 52 | ), 53 | 'max_images' => array( 54 | 'type' => 'integer', 55 | 'default' => 4, 56 | ), 57 | 'optin' => array( 58 | 'type' => 'boolean', 59 | 'default' => false, 60 | ), 61 | 'share_always' => array( 62 | 'type' => 'boolean', 63 | 'default' => false, 64 | ), 65 | 'delay_sharing' => array( 66 | 'type' => 'integer', 67 | 'default' => 0, 68 | ), 69 | 'micropub_compat' => array( 70 | 'type' => 'boolean', 71 | 'default' => false, 72 | ), 73 | 'syn_links_compat' => array( 74 | 'type' => 'boolean', 75 | 'default' => false, 76 | ), 77 | 'debug_logging' => array( 78 | 'type' => 'boolean', 79 | 'default' => false, 80 | ), 81 | 'custom_status_field' => array( 82 | 'type' => 'boolean', 83 | 'default' => false, 84 | ), 85 | 'status_template' => array( 86 | 'type' => 'string', 87 | 'default' => '%title% %permalink%', 88 | ), 89 | 'meta_box' => array( 90 | 'type' => 'boolean', 91 | 'default' => false, 92 | ), 93 | 'mastodon_app_id' => array( 94 | 'type' => 'integer', 95 | 'default' => 0, 96 | ), 97 | 'content_warning' => array( 98 | 'type' => 'boolean', 99 | 'default' => false, 100 | ), 101 | ); 102 | 103 | /** 104 | * Current options. 105 | * 106 | * @var array $options Current options. 107 | */ 108 | protected $options = array(); 109 | 110 | /** 111 | * Registers a new Mastodon app (client). 112 | */ 113 | protected function register_app() { 114 | // As of v0.19.0, we keep track of known instances, and reuse client IDs and secrets, rather then register as a 115 | // "new" client each and every time. Caveat: To ensure "old" registrations' validity, we use an "app token." 116 | // *Should* an app token ever get revoked, we will re-register after all. 117 | $apps = Mastodon_Client::find( array( 'host' => $this->options['mastodon_host'] ) ); 118 | 119 | if ( ! empty( $apps ) ) { 120 | foreach ( $apps as $app ) { 121 | if ( empty( $app->client_id ) || empty( $app->client_secret ) ) { 122 | // Don't bother. 123 | continue; 124 | } 125 | 126 | // @todo: Aren't we being overly cautious here? Does Mastodon "scrap" old registrations? 127 | if ( $this->verify_client_token( $app ) || $this->request_client_token( $app ) ) { 128 | debug_log( "[Share On Mastodon] Found an existing app (ID: {$app->id}) for host {$this->options['mastodon_host']}." ); 129 | 130 | $this->options['mastodon_app_id'] = (int) $app->id; 131 | $this->options['mastodon_client_id'] = $app->client_id; 132 | $this->options['mastodon_client_secret'] = $app->client_secret; 133 | 134 | $this->save(); 135 | 136 | // All done! 137 | return; 138 | } 139 | } 140 | } 141 | 142 | debug_log( "[Share On Mastodon] Registering a new app for host {$this->options['mastodon_host']}." ); 143 | 144 | // It's possible to register multiple redirect URIs. 145 | $redirect_uris = $this->get_redirect_uris(); 146 | $args = array( 147 | 'client_name' => apply_filters( 'share_on_mastodon_client_name', __( 'Share on Mastodon', 'share-on-mastodon' ) ), 148 | 'scopes' => 'read write:media write:statuses', 149 | 'redirect_uris' => implode( ' ', $redirect_uris ), 150 | 'website' => home_url(), 151 | ); 152 | 153 | $response = wp_safe_remote_post( 154 | esc_url_raw( $this->options['mastodon_host'] . '/api/v1/apps' ), 155 | array( 156 | 'body' => $args, 157 | 'timeout' => 15, 158 | 'limit_response_size' => 1048576, 159 | ) 160 | ); 161 | 162 | if ( is_wp_error( $response ) ) { 163 | debug_log( $response ); 164 | return; 165 | } 166 | 167 | $app = json_decode( $response['body'] ); 168 | 169 | if ( isset( $app->client_id ) && isset( $app->client_secret ) ) { 170 | // After successfully registering our app, store its details. 171 | $app_id = Mastodon_Client::insert( 172 | array_merge( 173 | $args, 174 | array_filter( 175 | array( 176 | 'host' => $this->options['mastodon_host'], 177 | 'client_id' => $app->client_id, 178 | 'client_secret' => $app->client_secret, 179 | 'vapid_key' => isset( $app->vapid_key ) ? $app->vapid_key : null, 180 | ) 181 | ) 182 | ) 183 | ); 184 | 185 | // Store in options table, too. 186 | $this->options['mastodon_app_id'] = (int) $app_id; 187 | $this->options['mastodon_client_id'] = $app->client_id; 188 | $this->options['mastodon_client_secret'] = $app->client_secret; 189 | 190 | // Update in database. 191 | $this->save(); 192 | 193 | // Fetch client token. In case someone were to use this same instance in the future. 194 | $this->request_client_token( $app ); 195 | 196 | return; 197 | } 198 | 199 | // Something went wrong. 200 | debug_log( $response ); 201 | } 202 | 203 | /** 204 | * Requests and stores an app token. 205 | * 206 | * @param object $app Mastodon app. 207 | * @return bool Whether the request was successful. 208 | */ 209 | protected function request_client_token( $app ) { 210 | debug_log( "[Share On Mastodon] Requesting app (ID: {$app->id}) token (for host {$app->host})." ); 211 | 212 | $response = wp_safe_remote_post( 213 | esc_url_raw( $this->options['mastodon_host'] . '/oauth/token' ), 214 | array( 215 | 'body' => array( 216 | 'client_id' => $app->client_id, 217 | 'client_secret' => $app->client_secret, 218 | 'grant_type' => 'client_credentials', 219 | 'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob', // This seems to work. I.e., one doesn't *have* to use a redirect URI for requesting app tokens. 220 | ), 221 | 'timeout' => 15, 222 | 'limit_response_size' => 1048576, 223 | ) 224 | ); 225 | 226 | if ( is_wp_error( $response ) ) { 227 | debug_log( $response ); 228 | return false; 229 | } 230 | 231 | $token = json_decode( $response['body'] ); 232 | 233 | if ( isset( $token->access_token ) ) { 234 | // Note: It surely looks like only one app token is given out, ever. Failing to save it here won't lead to 235 | // an unusable app; it'll only lead to a new registration for the next user that enters this instance, which 236 | // in itself does not invalidate other registrations, so we should be okay here. 237 | Mastodon_Client::update( 238 | array( 'client_token' => $token->access_token ), 239 | array( 'id' => $app->id ) 240 | ); 241 | 242 | return true; 243 | } 244 | 245 | // Something went wrong. 246 | debug_log( $response ); 247 | 248 | return false; 249 | } 250 | 251 | /** 252 | * Verifies app token. 253 | * 254 | * @param object $app Mastodon app. 255 | * @return bool Token validity. 256 | */ 257 | public function verify_client_token( $app ) { 258 | debug_log( "[Share On Mastodon] Verifying app (ID: {$app->id}) token (for host {$app->host})." ); 259 | 260 | if ( empty( $app->host ) ) { 261 | return false; 262 | } 263 | 264 | if ( empty( $app->client_token ) ) { 265 | return false; 266 | } 267 | 268 | // Verify the current client token. 269 | $response = wp_safe_remote_get( 270 | esc_url_raw( $app->host . '/api/v1/apps/verify_credentials' ), 271 | array( 272 | 'headers' => array( 273 | 'Authorization' => 'Bearer ' . $app->client_token, 274 | ), 275 | 'timeout' => 15, 276 | 'limit_response_size' => 1048576, 277 | ) 278 | ); 279 | 280 | if ( is_wp_error( $response ) ) { 281 | debug_log( $response ); 282 | return false; 283 | } 284 | 285 | if ( in_array( wp_remote_retrieve_response_code( $response ), array( 401, 403 ), true ) ) { 286 | // The current client token has somehow become invalid. 287 | return false; 288 | } 289 | 290 | $client = json_decode( $response['body'] ); 291 | 292 | if ( isset( $client->name ) ) { 293 | return true; 294 | } 295 | 296 | // Something went wrong. 297 | debug_log( $response ); 298 | 299 | return false; 300 | } 301 | 302 | /** 303 | * Requests a new user token. 304 | * 305 | * @param string $code Authorization code. 306 | */ 307 | abstract protected function request_user_token( $code ); 308 | 309 | /** 310 | * Revokes WordPress' access to Mastodon. 311 | * 312 | * @return bool Whether access was revoked. 313 | */ 314 | protected function revoke_access() { 315 | if ( empty( $this->options['mastodon_host'] ) ) { 316 | return false; 317 | } 318 | 319 | if ( empty( $this->options['mastodon_access_token'] ) ) { 320 | return false; 321 | } 322 | 323 | if ( empty( $this->options['mastodon_client_id'] ) ) { 324 | return false; 325 | } 326 | 327 | if ( empty( $this->options['mastodon_client_secret'] ) ) { 328 | return false; 329 | } 330 | 331 | // Revoke access. 332 | $response = wp_safe_remote_post( 333 | esc_url_raw( $this->options['mastodon_host'] . '/oauth/revoke' ), 334 | array( 335 | 'body' => array( 336 | 'client_id' => $this->options['mastodon_client_id'], 337 | 'client_secret' => $this->options['mastodon_client_secret'], 338 | 'token' => $this->options['mastodon_access_token'], 339 | ), 340 | 'timeout' => 15, 341 | 'limit_response_size' => 1048576, 342 | ) 343 | ); 344 | 345 | // Delete access token and username, regardless of the outcome. 346 | $this->options['mastodon_access_token'] = ''; 347 | $this->options['mastodon_username'] = ''; 348 | 349 | // Update in database. 350 | $this->save(); 351 | 352 | if ( is_wp_error( $response ) ) { 353 | debug_log( $response ); 354 | return false; 355 | } 356 | 357 | if ( 200 === wp_remote_retrieve_response_code( $response ) ) { 358 | // If we were actually successful. 359 | return true; 360 | } 361 | 362 | // Something went wrong. 363 | debug_log( $response ); 364 | 365 | return false; 366 | } 367 | 368 | /** 369 | * Verifies token status. 370 | * 371 | * @param $int $user_id (Optional) user ID. 372 | */ 373 | public function cron_verify_token( $user_id = 0 ) { 374 | if ( empty( $this->options['mastodon_host'] ) ) { 375 | return; 376 | } 377 | 378 | if ( empty( $this->options['mastodon_access_token'] ) ) { 379 | return; 380 | } 381 | 382 | // Verify the current access token. 383 | $response = wp_safe_remote_get( 384 | esc_url_raw( $this->options['mastodon_host'] . '/api/v1/accounts/verify_credentials' ), 385 | array( 386 | 'headers' => array( 387 | 'Authorization' => 'Bearer ' . $this->options['mastodon_access_token'], 388 | ), 389 | 'timeout' => 15, 390 | 'limit_response_size' => 1048576, 391 | ) 392 | ); 393 | 394 | if ( is_wp_error( $response ) ) { 395 | debug_log( $response ); 396 | return; 397 | } 398 | 399 | if ( in_array( wp_remote_retrieve_response_code( $response ), array( 401, 403 ), true ) ) { 400 | // The current access token has somehow become invalid. Forget it. 401 | $this->options['mastodon_access_token'] = ''; 402 | 403 | // Store in database. 404 | $this->save( $user_id ); 405 | 406 | return; 407 | } 408 | 409 | // Store username. Isn't actually used, yet, but may very well be in the near future. 410 | $account = json_decode( $response['body'] ); 411 | 412 | if ( isset( $account->username ) ) { 413 | debug_log( "[Share on Mastodon] Valid token. Got username `{$account->username}`." ); 414 | 415 | if ( empty( $this->options['mastodon_username'] ) || $account->username !== $this->options['mastodon_username'] ) { 416 | $this->options['mastodon_username'] = $account->username; 417 | 418 | // Update in database. 419 | $this->save( $user_id ); 420 | } 421 | 422 | // All done. 423 | return; 424 | } 425 | 426 | debug_log( $response ); 427 | } 428 | 429 | /** 430 | * Returns current options. 431 | * 432 | * @return array Plugin options. 433 | */ 434 | public function get_options() { 435 | return $this->options; 436 | } 437 | 438 | /** 439 | * Returns default options. 440 | * 441 | * @return array Default options. 442 | */ 443 | public static function get_default_options() { 444 | return array_combine( array_keys( static::SCHEMA ), array_column( static::SCHEMA, 'default' ) ); 445 | } 446 | 447 | /** 448 | * Preps a user-submitted instance URL for validation. 449 | * 450 | * @param string $url Input URL. 451 | * @return string Sanitized URL, or an empty string on failure. 452 | */ 453 | protected function clean_url( $url ) { 454 | $url = untrailingslashit( trim( $url ) ); 455 | 456 | // So, it looks like `wp_parse_url()` always expects a protocol. 457 | if ( 0 === strpos( $url, '//' ) ) { 458 | $url = 'https:' . $url; 459 | } elseif ( 0 !== strpos( $url, 'https://' ) && 0 !== strpos( $url, 'http://' ) ) { 460 | $url = 'https://' . $url; 461 | } 462 | 463 | // Take apart, then reassemble the URL. 464 | $parsed_url = wp_parse_url( $url ); 465 | 466 | if ( empty( $parsed_url['host'] ) ) { 467 | // Invalid URL. 468 | return ''; 469 | } 470 | 471 | if ( ! empty( $parsed_url['scheme'] ) ) { 472 | $url = $parsed_url['scheme'] . ':'; 473 | } else { 474 | $url = 'https:'; 475 | } 476 | 477 | $url .= '//' . $parsed_url['host']; 478 | 479 | if ( ! empty( $parsed_url['port'] ) ) { 480 | $url .= ':' . $parsed_url['port']; 481 | } 482 | 483 | return sanitize_url( $url ); 484 | } 485 | 486 | /** 487 | * Returns all currently valid, or possible, redirect URIs. 488 | * 489 | * @return array Possible redirect URIs. 490 | */ 491 | protected function get_redirect_uris() { 492 | return array( 493 | add_query_arg( array( 'page' => 'share-on-mastodon' ), admin_url( 'options-general.php' ) ), 494 | add_query_arg( array( 'page' => 'share-on-mastodon-pro' ), admin_url( 'users.php' ) ), 495 | add_query_arg( array( 'page' => 'share-on-mastodon-pro' ), admin_url( 'profile.php' ) ), 496 | ); 497 | } 498 | 499 | /** 500 | * Writes the current settings to the database. 501 | * 502 | * @param int $user_id (Optional) user ID. 503 | */ 504 | abstract protected function save( $user_id = 0 ); 505 | } 506 | -------------------------------------------------------------------------------- /includes/class-plugin-options.php: -------------------------------------------------------------------------------- 1 | options = array_merge( 19 | static::get_default_options(), 20 | is_array( $options ) 21 | ? $options 22 | : array() 23 | ); 24 | } 25 | 26 | /** 27 | * Registers hook callbacks. 28 | */ 29 | public function register() { 30 | add_action( 'admin_menu', array( $this, 'create_menu' ) ); 31 | add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); 32 | add_action( 'admin_post_share_on_mastodon_reset_settings', array( $this, 'reset_settings' ) ); 33 | add_action( 'share_on_mastodon_verify_token', array( $this, 'cron_verify_token' ) ); 34 | } 35 | 36 | /** 37 | * Registers the plugin settings page. 38 | */ 39 | public function create_menu() { 40 | add_options_page( 41 | __( 'Share on Mastodon', 'share-on-mastodon' ), 42 | __( 'Share on Mastodon', 'share-on-mastodon' ), 43 | 'manage_options', 44 | 'share-on-mastodon', 45 | array( $this, 'settings_page' ) 46 | ); 47 | add_action( 'admin_init', array( $this, 'add_settings' ) ); 48 | } 49 | 50 | /** 51 | * Registers the actual options. 52 | */ 53 | public function add_settings() { 54 | add_option( 'share_on_mastodon_settings', $this->options ); 55 | 56 | // @todo: Move to `sanitize_settings()`? 57 | $active_tab = $this->get_active_tab(); 58 | 59 | register_setting( 60 | 'share-on-mastodon-settings-group', 61 | 'share_on_mastodon_settings', 62 | array( 'sanitize_callback' => array( $this, "sanitize_{$active_tab}_settings" ) ) 63 | ); 64 | } 65 | 66 | /** 67 | * Handles submitted "setup" options. 68 | * 69 | * @param array $settings Submitted settings. 70 | * @return array (Sanitized) options to be stored. 71 | */ 72 | public function sanitize_setup_settings( $settings ) { 73 | if ( isset( $settings['mastodon_host'] ) ) { 74 | // Clean up and sanitize the user-submitted URL. 75 | $mastodon_host = $this->clean_url( $settings['mastodon_host'] ); 76 | 77 | if ( '' === $mastodon_host ) { 78 | // Removing the instance URL. Might be done to temporarily disable crossposting. Let's not revoke access 79 | // just yet. 80 | $this->options['mastodon_host'] = ''; 81 | } elseif ( wp_http_validate_url( $mastodon_host ) ) { 82 | if ( $mastodon_host !== $this->options['mastodon_host'] ) { 83 | // Updated URL. (Try to) revoke access. Forget token regardless of the outcome. 84 | $this->revoke_access(); 85 | 86 | // Then, save the new URL. 87 | $this->options['mastodon_host'] = esc_url_raw( $mastodon_host ); 88 | 89 | // Forget client ID and secret. A new client ID and secret will be requested next time the page 90 | // loads. 91 | $this->options['mastodon_client_id'] = ''; 92 | $this->options['mastodon_client_secret'] = ''; 93 | } 94 | } else { 95 | // Not a valid URL. Display error message. 96 | add_settings_error( 97 | 'share-on-mastodon-mastodon-host', 98 | 'invalid-url', 99 | esc_html__( 'Please provide a valid URL.', 'share-on-mastodon' ) 100 | ); 101 | } 102 | } 103 | 104 | // Updated settings. 105 | return $this->options; 106 | } 107 | 108 | /** 109 | * Handles submitted "post type" options. 110 | * 111 | * @param array $settings Submitted settings. 112 | * @return array (Sanitized) options to be stored. 113 | */ 114 | public function sanitize_post_types_settings( $settings ) { 115 | $this->options['post_types'] = array(); 116 | 117 | if ( isset( $settings['post_types'] ) && is_array( $settings['post_types'] ) ) { 118 | // Post types considered valid. 119 | $supported_post_types = (array) apply_filters( 'share_on_mastodon_post_types', get_post_types( array( 'public' => true ) ) ); 120 | $supported_post_types = array_diff( $supported_post_types, array( 'attachment' ) ); 121 | 122 | foreach ( $settings['post_types'] as $post_type ) { 123 | if ( in_array( $post_type, $supported_post_types, true ) ) { 124 | // Valid post type. Add to array. 125 | $this->options['post_types'][] = $post_type; 126 | } 127 | } 128 | } 129 | 130 | // Updated settings. 131 | return $this->options; 132 | } 133 | 134 | /** 135 | * Handles submitted "images" options. 136 | * 137 | * @param array $settings Submitted settings. 138 | * @return array (Sanitized) options to be stored. 139 | */ 140 | public function sanitize_images_settings( $settings ) { 141 | $options = array( 142 | 'featured_images' => isset( $settings['featured_images'] ) ? true : false, 143 | 'attached_images' => isset( $settings['attached_images'] ) ? true : false, 144 | 'referenced_images' => isset( $settings['referenced_images'] ) ? true : false, 145 | 'max_images' => isset( $settings['max_images'] ) && ctype_digit( $settings['max_images'] ) 146 | ? min( (int) $settings['max_images'], 4 ) 147 | : 4, 148 | ); 149 | 150 | // Updated settings. 151 | return array_merge( $this->options, $options ); 152 | } 153 | 154 | /** 155 | * Handles submitted "advanced" options. 156 | * 157 | * @param array $settings Submitted settings. 158 | * @return array (Sanitized) options to be stored. 159 | */ 160 | public function sanitize_advanced_settings( $settings ) { 161 | $delay = isset( $settings['delay_sharing'] ) && ctype_digit( $settings['delay_sharing'] ) 162 | ? (int) $settings['delay_sharing'] 163 | : 0; 164 | $delay = min( $delay, HOUR_IN_SECONDS ); // Limit to one hour. 165 | 166 | $options = array( 167 | 'optin' => isset( $settings['optin'] ) ? true : false, 168 | 'share_always' => isset( $settings['share_always'] ) ? true : false, 169 | 'delay_sharing' => $delay, 170 | 'micropub_compat' => isset( $settings['micropub_compat'] ) ? true : false, 171 | 'syn_links_compat' => isset( $settings['syn_links_compat'] ) ? true : false, 172 | 'custom_status_field' => isset( $settings['custom_status_field'] ) ? true : false, 173 | 'status_template' => isset( $settings['status_template'] ) && is_string( $settings['status_template'] ) 174 | ? preg_replace( '~\R~u', "\r\n", sanitize_textarea_field( $settings['status_template'] ) ) 175 | : '', 176 | 'meta_box' => isset( $settings['meta_box'] ) ? true : false, 177 | 'content_warning' => isset( $settings['content_warning'] ) ? true : false, 178 | ); 179 | 180 | // Updated settings. 181 | return array_merge( $this->options, $options ); 182 | } 183 | 184 | /** 185 | * Handles submitted "debugging" options. 186 | * 187 | * @param array $settings Submitted settings. 188 | * @return array (Sanitized) options to be stored. 189 | */ 190 | public function sanitize_debug_settings( $settings ) { 191 | $options = array( 192 | 'debug_logging' => isset( $settings['debug_logging'] ) ? true : false, 193 | ); 194 | 195 | // Updated settings. 196 | return array_merge( $this->options, $options ); 197 | } 198 | 199 | /** 200 | * Echoes the plugin options form. Handles the OAuth flow, too, for now. 201 | */ 202 | public function settings_page() { 203 | $active_tab = $this->get_active_tab(); 204 | ?> 205 |
206 |

207 | 208 | 217 | 218 | 222 |
223 | 227 | 228 | 229 | 230 | 233 | 234 |
231 | 232 |

https://mastodon.online' ); ?>

235 |

236 |
237 | 238 |

239 | options['mastodon_host'] ) ) { 241 | // A valid instance URL was set. 242 | if ( empty( $this->options['mastodon_client_id'] ) || empty( $this->options['mastodon_client_secret'] ) ) { 243 | // No app is currently registered. Let's try to fix that! 244 | $this->register_app(); 245 | } 246 | 247 | if ( ! empty( $this->options['mastodon_client_id'] ) && ! empty( $this->options['mastodon_client_secret'] ) ) { 248 | // An app was successfully registered. 249 | if ( ! empty( $_GET['code'] ) && '' === $this->options['mastodon_access_token'] ) { 250 | // Access token request. 251 | if ( $this->request_user_token( wp_unslash( $_GET['code'] ) ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 252 | ?> 253 |
254 |

255 |
256 | revoke_access(); 263 | } 264 | 265 | if ( empty( $this->options['mastodon_access_token'] ) ) { 266 | // No access token exists. Echo authorization link. 267 | $url = $this->options['mastodon_host'] . '/oauth/authorize?' . http_build_query( 268 | array( 269 | 'response_type' => 'code', 270 | 'client_id' => $this->options['mastodon_client_id'], 271 | 'client_secret' => $this->options['mastodon_client_secret'], 272 | 'redirect_uri' => esc_url_raw( add_query_arg( array( 'page' => 'share-on-mastodon' ), admin_url( 'options-general.php' ) ) ), 273 | 'scope' => ! empty( $this->options['mastodon_app_id'] ) 274 | ? 'write:media write:statuses read' // "New" scopes. 275 | : 'write:media write:statuses read:accounts read:statuses', // For "legacy" apps. 276 | ) 277 | ); 278 | ?> 279 |

280 |

%2$s', esc_url( $url ), esc_html__( 'Authorize Access', 'share-on-mastodon' ) ); ?> 281 | 285 |

286 |

287 | %2$s', 290 | esc_url( 291 | add_query_arg( 292 | array( 293 | 'page' => 'share-on-mastodon', // phpcs:ignore WordPress.Arrays.MultipleStatementAlignment.DoubleArrowNotAligned 294 | 'action' => 'revoke', // phpcs:ignore WordPress.Arrays.MultipleStatementAlignment.LongIndexSpaceBeforeDoubleArrow 295 | '_wpnonce' => wp_create_nonce( 'share-on-mastodon:token:revoke' ), 296 | ), 297 | admin_url( 'options-general.php' ) 298 | ) 299 | ), 300 | esc_html__( 'Revoke Access', 'share-on-mastodon' ) 301 | ); 302 | ?> 303 |

304 | 309 |

310 | 315 |

316 | 325 |
326 | 330 | 331 | 332 | 333 | 348 | 349 |
    334 | true ) ) ); 337 | $supported_post_types = array_diff( $supported_post_types, array( 'attachment' ) ); 338 | 339 | foreach ( $supported_post_types as $post_type ) : 340 | $post_type = get_post_type_object( $post_type ); 341 | ?> 342 |
  • 343 | 346 |
347 |

350 |

351 |
352 | 357 |
358 | 362 | 363 | 364 | 365 | 367 | 368 | 369 | 370 | 372 | 373 | 374 | 375 | 377 | 378 | 379 | 380 | 383 | 384 |
366 |

371 |

376 |

381 | 382 |

%2$s', 'https://wordpress.org/documentation/article/use-image-and-file-attachments/#attachment-to-a-post', esc_html__( 'attached images', 'share-on-mastodon' ) ) ); ?>

385 |

386 |
387 | 392 |
393 | 397 | 398 | 399 | 400 | 402 | 403 | 404 | 405 | 407 | 408 | 409 | 410 | 412 | 413 | 414 | 415 | 418 | 419 | 420 | 421 | 424 | 425 | 426 | 427 | 428 | 430 | 431 | 432 | 433 | 434 | 436 | 437 | 438 | 439 | 440 | 441 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 451 | 452 | 453 |
401 |

406 |

411 |

416 | 417 |

%title%, %excerpt%, %tags%, %permalink%' ); ?>

422 | 423 |

share_on_mastodon_status' ); ?>

429 |

435 |

442 |

450 |

454 |

455 |
456 | 461 |
462 | 466 | 467 | 468 | 469 | 472 | 473 |
470 | 471 |

%2$s', 'https://wordpress.org/documentation/article/debugging-in-wordpress/#example-wp-config-php-for-debugging', esc_html__( 'debug logging constants', 'share-on-mastodon' ) ) ); ?>

474 |

475 |
476 | 477 |
478 | 479 |
480 |

481 | %2$s', 484 | esc_url( 485 | add_query_arg( 486 | array( 487 | 'action' => 'share_on_mastodon_reset_settings', 488 | 'reset' => 'true', 489 | '_wpnonce' => wp_create_nonce( 'share-on-mastodon:settings:reset' ), 490 | ), 491 | admin_url( 'admin-post.php' ) 492 | ) 493 | ), 494 | esc_html__( 'Reset Settings', 'share-on-mastodon' ) 495 | ); 496 | ?> 497 |
498 |
499 | 504 |
505 | esc_attr__( 'Are you sure you want to reset all settings?', 'share-on-mastodon' ) ) // Confirmation message. 526 | ); 527 | } 528 | 529 | /** 530 | * Resets all plugin settings. 531 | */ 532 | public function reset_settings() { 533 | if ( ! current_user_can( 'manage_options' ) ) { 534 | wp_die( esc_html__( 'You have insufficient permissions to access this page.', 'share-on-mastodon' ) ); 535 | } 536 | 537 | if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'share-on-mastodon:settings:reset' ) ) { 538 | // Reset all plugin settings. 539 | $this->options = static::get_default_options(); 540 | $this->save(); 541 | } 542 | 543 | wp_safe_redirect( esc_url_raw( add_query_arg( array( 'page' => 'share-on-mastodon' ), admin_url( 'options-general.php' ) ) ) ); 544 | exit; 545 | } 546 | 547 | /** 548 | * Returns this plugin's options URL with a `tab` query parameter. 549 | * 550 | * @param string $tab Target tab. 551 | * @return string Options page URL. 552 | */ 553 | protected function get_options_url( $tab = 'setup' ) { 554 | return add_query_arg( 555 | array( 556 | 'page' => 'share-on-mastodon', 557 | 'tab' => $tab, 558 | ), 559 | admin_url( 'options-general.php' ) 560 | ); 561 | } 562 | 563 | /** 564 | * Returns the active tab. 565 | * 566 | * @return string Active tab. 567 | */ 568 | protected function get_active_tab() { 569 | $active_tab = apply_filters( 'share_on_mastodon_active_tab', null ); 570 | if ( $active_tab ) { 571 | return $active_tab; 572 | } 573 | 574 | if ( ! empty( $_POST['submit'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing 575 | // @todo: Add a "_wp_http_referer" form field rather than rely on an HTTP header? 576 | $query_string = wp_parse_url( wp_get_referer(), PHP_URL_QUERY ); 577 | 578 | if ( empty( $query_string ) ) { 579 | return 'setup'; 580 | } 581 | 582 | parse_str( $query_string, $query_vars ); 583 | 584 | if ( isset( $query_vars['tab'] ) && in_array( $query_vars['tab'], array( 'setup', 'post_types', 'images', 'advanced', 'debug' ), true ) ) { 585 | return $query_vars['tab']; 586 | } 587 | 588 | return 'setup'; 589 | } 590 | 591 | // phpcs:ignore WordPress.Security.NonceVerification.Recommended 592 | if ( isset( $_GET['tab'] ) && in_array( $_GET['tab'], array( 'setup', 'post_types', 'images', 'advanced', 'debug' ), true ) ) { 593 | return $_GET['tab']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 594 | } 595 | 596 | return 'setup'; 597 | } 598 | 599 | /** 600 | * Requests a new user token. 601 | * 602 | * @param string $code Authorization code. 603 | */ 604 | protected function request_user_token( $code ) { 605 | // Redirect here after authorization. 606 | $redirect_uri = add_query_arg( array( 'page' => 'share-on-mastodon' ), admin_url( 'options-general.php' ) ); 607 | 608 | // Request an access token. 609 | $response = wp_safe_remote_post( 610 | esc_url_raw( $this->options['mastodon_host'] . '/oauth/token' ), 611 | array( 612 | 'body' => array( 613 | 'client_id' => $this->options['mastodon_client_id'], 614 | 'client_secret' => $this->options['mastodon_client_secret'], 615 | 'grant_type' => 'authorization_code', 616 | 'code' => $code, 617 | 'redirect_uri' => esc_url_raw( $redirect_uri ), 618 | ), 619 | 'timeout' => 15, 620 | 'limit_response_size' => 1048576, 621 | ) 622 | ); 623 | 624 | if ( is_wp_error( $response ) ) { 625 | debug_log( $response ); 626 | return false; 627 | } 628 | 629 | $token = json_decode( $response['body'] ); 630 | 631 | if ( isset( $token->access_token ) ) { 632 | // Success. Store access token. 633 | $this->options['mastodon_access_token'] = $token->access_token; 634 | 635 | // Update in database. 636 | $this->save(); 637 | 638 | // @todo: This function **might** delete our token, we should take that into account somehow. 639 | $this->cron_verify_token(); // In order to get and store a username. 640 | 641 | return true; 642 | } 643 | 644 | debug_log( $response ); 645 | 646 | return false; 647 | } 648 | 649 | /** 650 | * Writes the current settings to the database. 651 | * 652 | * @param int $user_id (Optional) user ID. 653 | */ 654 | protected function save( $user_id = 0 ) { 655 | update_option( 'share_on_mastodon_settings', $this->options ); 656 | } 657 | } 658 | -------------------------------------------------------------------------------- /includes/class-post-handler.php: -------------------------------------------------------------------------------- 1 | ID ) ) { 49 | return; 50 | } 51 | 52 | if ( ! isset( $_POST['share_on_mastodon_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['share_on_mastodon_nonce'] ), basename( __FILE__ ) ) ) { 53 | // Nonce missing or invalid. 54 | return; 55 | } 56 | 57 | $options = get_options(); 58 | 59 | // Sanitize custom status, if any. 60 | if ( isset( $_POST['share_on_mastodon_status'] ) ) { 61 | $status = sanitize_textarea_field( wp_unslash( $_POST['share_on_mastodon_status'] ) ); 62 | $status = preg_replace( '~\R~u', "\r\n", $status ); 63 | } 64 | 65 | if ( 66 | ! empty( $status ) && '' !== preg_replace( '~\s~', '', $status ) && 67 | ( empty( $options['status_template'] ) || $status !== $options['status_template'] ) 68 | ) { 69 | // Save only if `$status` is non-empty and, if a template exists, different from said template. 70 | update_post_meta( $post->ID, '_share_on_mastodon_status', $status ); 71 | } else { 72 | // Ignore, or delete a previously stored value. 73 | delete_post_meta( $post->ID, '_share_on_mastodon_status' ); 74 | } 75 | 76 | // Sanitize CW, if any. 77 | if ( isset( $_POST['share_on_mastodon_cw'] ) ) { 78 | $content_warning = sanitize_text_field( wp_unslash( $_POST['share_on_mastodon_cw'] ) ); 79 | } 80 | 81 | if ( ! empty( $content_warning ) && '' !== preg_replace( '~\s~', '', $content_warning ) ) { 82 | // Save only if `$content_warning` is non-empty and. 83 | update_post_meta( $post->ID, '_share_on_mastodon_cw', $content_warning ); 84 | } else { 85 | // Ignore, or delete a previously stored value. 86 | delete_post_meta( $post->ID, '_share_on_mastodon_cw' ); 87 | } 88 | 89 | if ( isset( $_POST['share_on_mastodon'] ) && ! post_password_required( $post ) ) { 90 | // If sharing enabled and post not password-protected. 91 | update_post_meta( $post->ID, '_share_on_mastodon', '1' ); 92 | } else { 93 | delete_post_meta( $post->ID, '_share_on_mastodon_error' ); // Clear previous errors, if any. 94 | update_post_meta( $post->ID, '_share_on_mastodon', '0' ); 95 | } 96 | } 97 | 98 | /** 99 | * Schedules sharing to Mastodon. 100 | * 101 | * @param int|\WP_Post $post Post ID or object. 102 | */ 103 | public function toot( $post ) { 104 | $post = get_post( $post ); 105 | 106 | if ( 0 === strpos( current_action(), 'save_' ) && defined( 'REST_REQUEST' ) && REST_REQUEST ) { 107 | // For REST requests, we use a *later* hook, which runs *after* metadata, if any, has been saved. 108 | debug_log( "[Share on Mastodon] Delaying scheduling to `rest_after_insert_{$post->post_type}`." ); 109 | add_action( "rest_after_insert_{$post->post_type}", array( $this, 'toot' ), 20 ); 110 | 111 | // Don't do anything just yet. 112 | return; 113 | } 114 | 115 | $options = get_options(); 116 | if ( ! empty( $options['meta_box'] && $this->is_gutenberg() && empty( $_REQUEST['meta-box-loader'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended 117 | debug_log( '[Share on Mastodon] First of two expected requests. Quitting.' ); 118 | // This has to be the first of *two* "Gutenberg requests," and we should ignore it. Note: It could be that 119 | // `$this->is_gutenberg()` always returns `false` whenever `$_REQUEST['meta-box-loader']` is present. 120 | // Still, doesn't hurt to check. 121 | return; 122 | } 123 | 124 | // In all other cases, we move on. 125 | if ( wp_is_post_revision( $post ) || wp_is_post_autosave( $post ) ) { 126 | return; 127 | } 128 | 129 | if ( ! $this->setup_completed( $post ) ) { 130 | debug_log( '[Share on Mastodon] Setup incomplete.' ); 131 | return; 132 | } 133 | 134 | if ( ! $this->is_valid( $post ) ) { 135 | return; 136 | } 137 | 138 | if ( ! empty( $options['delay_sharing'] ) ) { 139 | // Since version 0.7.0, there's an option to "schedule" sharing rather than do everything inline. 140 | wp_schedule_single_event( 141 | time() + min( $options['delay_sharing'], 3600 ), // Limit to one hour. 142 | 'share_on_mastodon_post', 143 | array( $post ) 144 | ); 145 | } else { 146 | // Share immediately. 147 | $this->post_to_mastodon( $post ); 148 | } 149 | } 150 | 151 | /** 152 | * Actually shares a post on Mastodon. 153 | * 154 | * Can be called directly or as a (scheduled) `share_on_mastodon_post` 155 | * callback. 156 | * 157 | * @param int|\WP_Post $post Post ID or object. 158 | */ 159 | public function post_to_mastodon( $post ) { 160 | $post = get_post( $post ); 161 | 162 | if ( ! $this->setup_completed( $post ) ) { 163 | return; 164 | } 165 | 166 | if ( ! $this->is_valid( $post ) ) { 167 | debug_log( '[Share on Mastodon] Skipping post.' ); 168 | return; 169 | } 170 | 171 | $options = get_options( $post->post_author ); 172 | 173 | // Fetch custom status message, if any. 174 | $status = get_post_meta( $post->ID, '_share_on_mastodon_status', true ); 175 | // Parse template tags, and sanitize. 176 | $status = $this->parse_status( $status, $post->ID ); 177 | 178 | if ( ( empty( $status ) || '' === preg_replace( '~\s~', '', $status ) ) && ! empty( $options['status_template'] ) ) { 179 | // Use template stored in settings. 180 | $status = $this->parse_status( $options['status_template'], $post->ID ); 181 | } 182 | 183 | if ( empty( $status ) || '' === preg_replace( '~\s~', '', $status ) ) { 184 | // Fall back to post title. 185 | $status = get_the_title( $post->ID ); 186 | } 187 | 188 | $status = wp_strip_all_tags( 189 | html_entity_decode( $status, ENT_QUOTES | ENT_HTML5, get_bloginfo( 'charset' ) ) // Avoid double-encoded HTML entities. 190 | ); 191 | 192 | // Append permalink, but only if it's not already there. 193 | $permalink = esc_url_raw( get_permalink( $post->ID ) ); 194 | 195 | if ( false === strpos( $status, $permalink ) ) { 196 | // Post doesn't mention permalink, yet. Append it. 197 | if ( false === strpos( $status, "\n" ) ) { 198 | $status .= ' ' . $permalink; // Keep it single-line. 199 | } else { 200 | $status .= "\r\n\r\n" . $permalink; 201 | } 202 | } 203 | 204 | // Allow developers to (completely) override `$status`. 205 | $status = apply_filters( 'share_on_mastodon_status', $status, $post ); 206 | $args = apply_filters( 'share_on_mastodon_toot_args', array( 'status' => $status ), $post ); 207 | 208 | if ( apply_filters_deprecated( 'share_on_mastodon_cutoff', array( false ), '0.16.1' ) ) { 209 | // May render hashtags or URLs, or unfiltered HTML, at the very end of a toot unusable. 210 | $args['status'] = mb_substr( $args['status'], 0, 499, get_bloginfo( 'charset' ) ) . '…'; 211 | } 212 | 213 | $content_warning = get_post_meta( $post->ID, '_share_on_mastodon_cw', true ); 214 | $content_warning = (string) apply_filters( 'share_on_mastodon_cw', $content_warning ); 215 | 216 | if ( '' !== $content_warning ) { 217 | // May render hashtags or URLs, or unfiltered HTML, at the very end of a toot unusable. 218 | $args['spoiler_text'] = sanitize_text_field( $content_warning ); 219 | } 220 | 221 | // Encode, build query string. 222 | $query_string = http_build_query( $args ); 223 | 224 | // And now, images. 225 | $media = Image_Handler::get_images( $post ); 226 | 227 | if ( ! empty( $media ) ) { 228 | $max = isset( $options['max_images'] ) 229 | ? $options['max_images'] 230 | : 4; 231 | 232 | $max = (int) apply_filters( 'share_on_mastodon_num_images', $max, $post ); 233 | $count = min( count( $media ), $max ); 234 | 235 | // Limit the no. of images (or other media) to `$count`. 236 | $media = array_slice( $media, 0, $count, true ); 237 | 238 | foreach ( $media as $id => $alt ) { 239 | $media_id = Image_Handler::upload_image( $id, $alt, $options ); 240 | 241 | if ( ! empty( $media_id ) ) { 242 | // The image got uploaded OK. 243 | $query_string .= '&media_ids[]=' . rawurlencode( $media_id ); 244 | } 245 | } 246 | } 247 | 248 | debug_log( '[Share on Mastodon] Posting to Mastodon ...' ); 249 | 250 | $response = wp_safe_remote_post( 251 | esc_url_raw( $options['mastodon_host'] . '/api/v1/statuses' ), 252 | array( 253 | 'headers' => array( 254 | 'Authorization' => 'Bearer ' . $options['mastodon_access_token'], 255 | ), 256 | // Prevent WordPress from applying `http_build_query()`. 257 | 'data_format' => 'body', 258 | 'body' => $query_string, 259 | 'timeout' => 15, 260 | 'limit_response_size' => 1048576, 261 | ) 262 | ); 263 | 264 | if ( is_wp_error( $response ) ) { 265 | // An error occurred. 266 | debug_log( $response ); 267 | return; 268 | } 269 | 270 | $status = json_decode( $response['body'] ); 271 | 272 | if ( ! empty( $status->url ) ) { 273 | debug_log( "[Share on Mastodon] Post shared OK at {$status->url}." ); 274 | 275 | delete_post_meta( $post->ID, '_share_on_mastodon_error' ); 276 | update_post_meta( $post->ID, '_share_on_mastodon_url', esc_url_raw( $status->url ) ); 277 | 278 | if ( 'share_on_mastodon_post' !== current_filter() ) { 279 | // Show a notice only when this function was called directly. 280 | add_filter( 'redirect_post_location', array( Notices::class, 'add_success_query_var' ) ); 281 | } 282 | } elseif ( ! empty( $status->error ) ) { 283 | update_post_meta( $post->ID, '_share_on_mastodon_error', sanitize_text_field( $status->error ) ); 284 | 285 | if ( 'share_on_mastodon_post' !== current_filter() ) { 286 | // Show a notice only when this function was called directly. 287 | add_filter( 'redirect_post_location', array( Notices::class, 'add_error_query_var' ) ); 288 | } 289 | 290 | // Provided debugging's enabled, let's store the (somehow faulty) response. 291 | debug_log( $response ); 292 | } 293 | 294 | debug_log( '[Share on Mastodon] All done!' ); 295 | } 296 | 297 | /** 298 | * Registers a new meta box. 299 | */ 300 | public function add_meta_box() { 301 | $options = get_options(); 302 | 303 | if ( empty( $options['post_types'] ) ) { 304 | // Sharing disabled for all post types. 305 | return; 306 | } 307 | 308 | // This'll hide the meta box for Gutenberg users, who by default get the new sidebar panel. 309 | $args = array( '__back_compat_meta_box' => true ); 310 | if ( ! empty( $options['meta_box'] ) ) { 311 | // And this will bring it back. 312 | $args = null; 313 | } 314 | 315 | add_meta_box( 316 | 'share-on-mastodon', 317 | __( 'Share on Mastodon', 'share-on-mastodon' ), 318 | array( $this, 'render_meta_box' ), 319 | (array) $options['post_types'], 320 | 'side', 321 | 'default', 322 | $args 323 | ); 324 | } 325 | 326 | /** 327 | * Renders meta box. 328 | * 329 | * @param \WP_Post $post Post being edited. 330 | */ 331 | public function render_meta_box( $post ) { 332 | wp_nonce_field( basename( __FILE__ ), 'share_on_mastodon_nonce' ); 333 | 334 | $options = get_options(); 335 | $checked = get_post_meta( $post->ID, '_share_on_mastodon', true ); 336 | 337 | if ( '' === $checked ) { 338 | // If sharing is "opt-in" or the post in question is older than 30 minutes, do _not_ check the checkbox by 339 | // default. 340 | $checked = apply_filters( 'share_on_mastodon_optin', ! empty( $options['optin'] ) ) || is_older_than( HOUR_IN_SECONDS / 2, $post ) ? '0' : '1'; 341 | } 342 | ?> 343 | 347 | ID, '_share_on_mastodon_cw', true ); 351 | ?> 352 |
353 | 354 | 355 |
356 | ID, '_share_on_mastodon_status', true ); 362 | 363 | if ( '' === $custom_status && ! empty( $options['status_template'] ) ) { 364 | // Default to the template as set on the options page. 365 | $custom_status = $options['status_template']; 366 | } 367 | ?> 368 |
369 | 370 | 371 |

372 |
373 | ID, '_share_on_mastodon_url', true ); 377 | 378 | if ( '' !== $url && filter_var( $url, FILTER_VALIDATE_URL ) ) : 379 | $url_parts = wp_parse_url( $url ); 380 | 381 | $display_url = '' . $url_parts['scheme'] . '://'; 382 | $display_url .= ( ! empty( $url_parts['user'] ) ? $url_parts['user'] . ( ! empty( $url_parts['pass'] ) ? ':' . $url_parts['pass'] : '' ) . '@' : '' ) . ''; 383 | $display_url .= '' . mb_substr( $url_parts['host'] . $url_parts['path'], 0, 20 ) . '' . mb_substr( $url_parts['host'] . $url_parts['path'], 20 ) . ''; 384 | ?> 385 |

386 | 387 | ' . $display_url . '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> 388 | 389 | 390 |

391 | ID, '_share_on_mastodon_error', true ); 394 | 395 | if ( '' !== $error_message ) : 396 | ?> 397 |

398 | post_type ) && ! in_array( $current_screen->post_type, $options['post_types'], true ) ) ) { 459 | // Only load JS for actually supported post types. 460 | return; 461 | } 462 | 463 | global $post; 464 | 465 | // Enqueue CSS and JS. 466 | wp_enqueue_style( 'share-on-mastodon', plugins_url( '/assets/share-on-mastodon.css', __DIR__ ), array(), Share_On_Mastodon::PLUGIN_VERSION ); 467 | wp_enqueue_script( 'share-on-mastodon', plugins_url( '/assets/share-on-mastodon.js', __DIR__ ), array(), Share_On_Mastodon::PLUGIN_VERSION, false ); 468 | wp_localize_script( 469 | 'share-on-mastodon', 470 | 'share_on_mastodon_obj', 471 | array( 472 | 'message' => esc_attr__( 'Forget this URL?', 'share-on-mastodon' ), // Confirmation message. 473 | 'post_id' => ! empty( $post->ID ) ? $post->ID : 0, // Pass current post ID to JS. 474 | 'nonce' => wp_create_nonce( basename( __FILE__ ) ), 475 | 'ajaxurl' => esc_url_raw( admin_url( 'admin-ajax.php' ) ), 476 | 'custom_status_field' => ! empty( $options['custom_status_field'] ) ? '1' : '0', 477 | 'content_warning' => ! empty( $options['content_warning'] ) ? '1' : '0', 478 | ) 479 | ); 480 | } 481 | 482 | /** 483 | * Determines if a post should, in fact, be shared. 484 | * 485 | * @param \WP_Post $post Post object. 486 | * @return bool If the post should be shared. 487 | */ 488 | protected function is_valid( $post ) { 489 | if ( 'publish' !== $post->post_status ) { 490 | // Status is something other than `publish`. 491 | debug_log( '[Share on Mastodon] Post not public.' ); 492 | return false; 493 | } 494 | 495 | if ( post_password_required( $post ) ) { 496 | // Post is password-protected. 497 | debug_log( '[Share on Mastodon] Post password-protected.' ); 498 | return false; 499 | } 500 | 501 | $options = get_options( $post->post_author ); 502 | 503 | if ( ! in_array( $post->post_type, (array) $options['post_types'], true ) ) { 504 | // Unsupported post type. 505 | debug_log( '[Share on Mastodon] Unsupported post type.' ); 506 | return false; 507 | } 508 | 509 | if ( '' !== get_post_meta( $post->ID, '_share_on_mastodon_url', true ) ) { 510 | // Was shared before (and not "unlinked"). 511 | debug_log( '[Share on Mastodon] Post shared before.' ); 512 | return false; 513 | } 514 | 515 | if ( is_older_than( DAY_IN_SECONDS / 2, $post ) && '1' !== get_post_meta( $post->ID, '_share_on_mastodon', true ) ) { 516 | // Unless the box was ticked explicitly, we won't share "older" posts. Since v0.13.0, sharing "older" posts 517 | // is "opt-in," always. 518 | debug_log( '[Share on Mastodon] Preventing older post from being shared automatically.' ); 519 | return false; 520 | } 521 | 522 | $is_enabled = false; 523 | 524 | if ( '1' === get_post_meta( $post->ID, '_share_on_mastodon', true ) ) { 525 | // Sharing was enabled for this post. 526 | $is_enabled = true; 527 | } 528 | 529 | // That's not it, though; we have a setting that enables posts to be shared nevertheless. 530 | if ( ! empty( $options['share_always'] ) ) { 531 | $is_enabled = true; 532 | } 533 | 534 | // We let developers override `$is_enabled` through a callback function. 535 | return apply_filters( 'share_on_mastodon_enabled', $is_enabled, $post->ID ); 536 | } 537 | 538 | /** 539 | * Parses `%title%`, etc. template tags. 540 | * 541 | * @param string $status Mastodon status, or template. 542 | * @param int $post_id Post ID. 543 | * @return string Parsed status. 544 | */ 545 | protected function parse_status( $status, $post_id ) { 546 | // Fill out title and tags. 547 | $status = str_replace( '%title%', get_the_title( $post_id ), $status ); 548 | $status = str_replace( '%tags%', $this->get_tags( $post_id ), $status ); 549 | 550 | // Estimate a max length of sorts. 551 | $max_length = mb_strlen( str_replace( array( '%excerpt%', '%permalink%' ), '', $status ) ); 552 | $max_length = max( 0, 450 - $max_length ); // For a possible permalink, and then some. 553 | 554 | $status = str_replace( '%excerpt%', $this->get_excerpt( $post_id, $max_length ), $status ); 555 | 556 | $status = preg_replace( '~(\r\n){2,}~', "\r\n\r\n", $status ); // We should have normalized line endings by now. 557 | $status = sanitize_textarea_field( $status ); // Strips HTML and whatnot. 558 | 559 | // Add the (escaped) URL after the everything else has been sanitized, so as not to garble permalinks with 560 | // multi-byte characters in them. 561 | $status = str_replace( '%permalink%', esc_url_raw( get_permalink( $post_id ) ), $status ); 562 | 563 | return $status; 564 | } 565 | 566 | /** 567 | * Returns a post's excerpt, but limited to approx. 125 characters. 568 | * 569 | * @param int $post_id Post ID. 570 | * @param int $max_length Estimated maximum length. 571 | * @return string (Possibly shortened) excerpt. 572 | */ 573 | protected function get_excerpt( $post_id, $max_length = 125 ) { 574 | if ( 0 === $max_length ) { 575 | // Nothing to do. 576 | return ''; 577 | } 578 | 579 | // Grab the default `excerpt_more`. 580 | $excerpt_more = apply_filters( 'excerpt_more', ' […]' ); 581 | 582 | // The excerpt as generated by WordPress. 583 | $orig = apply_filters( 'the_excerpt', get_the_excerpt( $post_id ) ); 584 | 585 | // Trim off the `excerpt_more` string. 586 | $excerpt = preg_replace( "~$excerpt_more$~", '', $orig ); 587 | 588 | $excerpt = wp_strip_all_tags( $orig ); // Just in case a site owner's allowing HTML in their excerpts or something. 589 | $excerpt = html_entity_decode( $orig, ENT_QUOTES | ENT_HTML5, get_bloginfo( 'charset' ) ); // Prevent special characters from messing things up. 590 | 591 | $shortened = mb_substr( $excerpt, 0, apply_filters( 'share_on_mastodon_excerpt_length', $max_length ) ); 592 | $shortened = trim( $shortened ); 593 | 594 | if ( $shortened === $excerpt ) { 595 | // Might as well done nothing. 596 | return $orig; 597 | } elseif ( ctype_punct( mb_substr( $shortened, -1 ) ) ) { 598 | // Final char is a "punctuation" character. 599 | $shortened .= ' …'; 600 | } else { 601 | $shortened .= '…'; 602 | } 603 | 604 | return $shortened; 605 | } 606 | 607 | /** 608 | * Returns a post's tags as a string of space-separated hashtags. 609 | * 610 | * @param int $post_id Post ID. 611 | * @return string Hashtag string. 612 | */ 613 | protected function get_tags( $post_id ) { 614 | $hashtags = ''; 615 | $tags = get_the_tags( $post_id ); 616 | 617 | if ( $tags && ! is_wp_error( $tags ) ) { 618 | foreach ( $tags as $tag ) { 619 | $tag_name = $tag->name; 620 | 621 | if ( preg_match( '/(\s|-)+/', $tag_name ) ) { 622 | // Try to "CamelCase" multi-word tags. 623 | $tag_name = preg_replace( '~(\s|-)+~', ' ', $tag_name ); 624 | $tag_name = explode( ' ', $tag_name ); 625 | $tag_name = implode( '', array_map( 'ucfirst', $tag_name ) ); 626 | } 627 | 628 | $hashtags .= '#' . $tag_name . ' '; 629 | } 630 | } 631 | 632 | return trim( $hashtags ); 633 | } 634 | 635 | /** 636 | * Checks for a Mastodon instance and auth token. 637 | * 638 | * @param \WP_Post $post Post object. 639 | * @return bool Whether auth access was set up okay. 640 | */ 641 | protected function setup_completed( $post ) { 642 | $options = get_options( $post->post_author ); 643 | 644 | if ( empty( $options['mastodon_host'] ) ) { 645 | return false; 646 | } 647 | 648 | if ( ! wp_http_validate_url( $options['mastodon_host'] ) ) { 649 | return false; 650 | } 651 | 652 | if ( empty( $options['mastodon_access_token'] ) ) { 653 | return false; 654 | } 655 | 656 | return true; 657 | } 658 | 659 | /** 660 | * Checks whether the current request was initiated by the block editor. 661 | * 662 | * @return bool Whether the current request was initiated by the block editor. 663 | */ 664 | protected function is_gutenberg() { 665 | if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) { 666 | // Not a REST request. 667 | return false; 668 | } 669 | 670 | if ( wp_doing_cron() ) { 671 | return false; 672 | } 673 | 674 | $nonce = null; 675 | 676 | if ( isset( $_REQUEST['_wpnonce'] ) ) { 677 | $nonce = $_REQUEST['_wpnonce']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 678 | } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) { 679 | $nonce = $_SERVER['HTTP_X_WP_NONCE']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 680 | } 681 | 682 | if ( null === $nonce ) { 683 | return false; 684 | } 685 | 686 | // Check the nonce. 687 | return wp_verify_nonce( $nonce, 'wp_rest' ); 688 | } 689 | } 690 | -------------------------------------------------------------------------------- /includes/class-share-on-mastodon.php: -------------------------------------------------------------------------------- 1 | plugin_options = new Plugin_Options(); 54 | $this->plugin_options->register(); 55 | 56 | $this->post_handler = new Post_Handler(); 57 | $this->post_handler->register(); 58 | 59 | // Main plugin hooks. 60 | register_deactivation_hook( dirname( __DIR__ ) . '/share-on-mastodon.php', array( $this, 'deactivate' ) ); 61 | 62 | add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) ); 63 | add_action( 'init', array( $this, 'init' ) ); 64 | 65 | $options = get_options(); 66 | 67 | if ( ! empty( $options['micropub_compat'] ) ) { 68 | Micropub_Compat::register(); 69 | } 70 | 71 | if ( ! empty( $options['syn_links_compat'] ) ) { 72 | Syn_Links_Compat::register(); 73 | } 74 | 75 | Block_Editor::register(); 76 | } 77 | 78 | /** 79 | * Ensures cron job is scheduled, and, if needed, kicks off database migrations. 80 | */ 81 | public function init() { 82 | // Schedule a daily cron job. 83 | if ( false === wp_next_scheduled( 'share_on_mastodon_verify_token' ) ) { 84 | wp_schedule_event( time() + DAY_IN_SECONDS, 'daily', 'share_on_mastodon_verify_token' ); 85 | } 86 | 87 | if ( get_option( 'share_on_mastodon_db_version' ) !== self::DB_VERSION ) { 88 | $this->migrate(); 89 | } 90 | } 91 | 92 | /** 93 | * Runs on deactivation. 94 | */ 95 | public function deactivate() { 96 | wp_clear_scheduled_hook( 'share_on_mastodon_verify_token' ); 97 | } 98 | 99 | /** 100 | * Enables localization. 101 | */ 102 | public function load_textdomain() { 103 | load_plugin_textdomain( 'share-on-mastodon', false, basename( dirname( __DIR__ ) ) . '/languages' ); 104 | } 105 | 106 | /** 107 | * Returns `Post_Handler` instance. 108 | * 109 | * @return Post_Handler This plugin's `Post_Handler` instance. 110 | */ 111 | public function get_post_handler() { 112 | return $this->post_handler; 113 | } 114 | 115 | /** 116 | * Returns `Plugin_Options` instance. 117 | * 118 | * @return Plugin_Options This plugin's `Plugin_Options` instance. 119 | */ 120 | public function get_plugin_options() { 121 | return $this->plugin_options; 122 | } 123 | 124 | /** 125 | * Returns `Plugin_Options` instance. 126 | * 127 | * @return Plugin_Options This plugin's `Plugin_Options` instance. 128 | */ 129 | public function get_options_handler() { 130 | _deprecated_function( __METHOD__, '0.19.0', '\Share_On_Mastodon\Share_On_Mastodon::get_plugin_options' ); 131 | 132 | return $this->plugin_options; 133 | } 134 | 135 | /** 136 | * Performs the necessary database migrations, if applicable. 137 | */ 138 | protected function migrate() { 139 | if ( ! function_exists( '\\dbDelta' ) ) { 140 | require_once ABSPATH . 'wp-admin/includes/upgrade.php'; 141 | } 142 | 143 | ob_start(); 144 | include __DIR__ . '/database/schema.php'; 145 | $sql = ob_get_clean(); 146 | 147 | dbDelta( $sql ); 148 | 149 | update_option( 'share_on_mastodon_db_version', self::DB_VERSION, 'no' ); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /includes/class-syn-links-compat.php: -------------------------------------------------------------------------------- 1 | 12 | CREATE TABLE ( 13 | id mediumint(9) UNSIGNED NOT NULL AUTO_INCREMENT, 14 | host varchar(191) NOT NULL, 15 | client_name varchar(191), 16 | website varchar(191), 17 | scopes varchar(191), 18 | redirect_uris text, 19 | client_id varchar(191) NOT NULL, 20 | client_secret varchar(191) NOT NULL, 21 | vapid_key varchar(191), 22 | client_token varchar(191), 23 | created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, 24 | modified_at datetime, 25 | PRIMARY KEY (id) 26 | ) get_charset_collate(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>; 27 | -------------------------------------------------------------------------------- /includes/functions.php: -------------------------------------------------------------------------------- 1 | get_plugin_options() 35 | ->get_options(); 36 | 37 | return apply_filters( 'share_on_mastodon_options', $options, $user_id ); 38 | } 39 | 40 | /** 41 | * Tries to convert an attachment URL into a post ID. 42 | * 43 | * Mostly lifted from core. The main difference is this function will also match URLs whose filename part probably 44 | * should include `-scaled`. 45 | * 46 | * @param string $url The URL to resolve. 47 | * @return int The found post ID, or 0 on failure. 48 | */ 49 | function attachment_url_to_postid( $url ) { 50 | global $wpdb; 51 | 52 | $dir = wp_get_upload_dir(); 53 | $path = $url; 54 | 55 | $site_url = wp_parse_url( $dir['url'] ); 56 | $image_path = wp_parse_url( $path ); 57 | 58 | // Force the protocols to match if needed. 59 | if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) { 60 | $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path ); 61 | } 62 | 63 | if ( str_starts_with( $path, $dir['baseurl'] . '/' ) ) { 64 | $path = substr( $path, strlen( $dir['baseurl'] . '/' ) ); 65 | } 66 | 67 | $filename = pathinfo( $path, PATHINFO_FILENAME ); // The bit before the (last) file extension (if any). 68 | 69 | $sql = $wpdb->prepare( 70 | "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value REGEXP %s", 71 | str_replace( $filename, "$filename(-scaled)*", $path ) // This is really the only change here. 72 | ); 73 | 74 | // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared 75 | $results = $wpdb->get_results( $sql ); 76 | $post_id = null; 77 | 78 | if ( $results ) { 79 | // Use the first available result, but prefer a case-sensitive match, if exists. 80 | $post_id = reset( $results )->post_id; 81 | 82 | if ( count( $results ) > 1 ) { 83 | foreach ( $results as $result ) { 84 | if ( $path === $result->meta_value ) { 85 | $post_id = $result->post_id; 86 | break; 87 | } 88 | } 89 | } 90 | } 91 | 92 | return (int) $post_id; 93 | } 94 | 95 | /** 96 | * Determines whether a post is older than a certain number of seconds. 97 | * 98 | * @param int $seconds Minimum "age," in seconds. 99 | * @param int|\WP_Post $post Post ID or object. Defaults to global `$post`. 100 | * @return bool True if the post exists and is older than `$seconds`, false otherwise. 101 | */ 102 | function is_older_than( $seconds, $post = null ) { 103 | $post_time = get_post_time( 'U', true, $post ); 104 | 105 | if ( false === $post_time ) { 106 | return false; 107 | } 108 | 109 | if ( $post_time >= time() - $seconds ) { 110 | return false; 111 | } 112 | 113 | return true; 114 | } 115 | -------------------------------------------------------------------------------- /languages/share-on-mastodon.pot: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2024 Jan Boddez 2 | # This file is distributed under the GNU General Public License v3. 3 | msgid "" 4 | msgstr "" 5 | "Project-Id-Version: Share on Mastodon 0.19.0\n" 6 | "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/share-on-mastodon\n" 7 | "Last-Translator: FULL NAME \n" 8 | "Language-Team: LANGUAGE \n" 9 | "MIME-Version: 1.0\n" 10 | "Content-Type: text/plain; charset=UTF-8\n" 11 | "Content-Transfer-Encoding: 8bit\n" 12 | "POT-Creation-Date: 2024-07-03T15:44:35+00:00\n" 13 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 14 | "X-Generator: WP-CLI 2.6.0\n" 15 | "X-Domain: share-on-mastodon\n" 16 | 17 | #. Plugin Name of the plugin 18 | #: includes/class-options-handler.php:143 19 | #: includes/class-plugin-options.php:41 20 | #: includes/class-plugin-options.php:42 21 | #: includes/class-plugin-options.php:205 22 | #: includes/class-post-handler.php:284 23 | #: includes/class-post-handler.php:312 24 | #: assets/block-editor.js:160 25 | #: assets/block-editor.js:163 26 | msgid "Share on Mastodon" 27 | msgstr "" 28 | 29 | #. Plugin URI of the plugin 30 | msgid "https://jan.boddez.net/wordpress/share-on-mastodon" 31 | msgstr "" 32 | 33 | #. Description of the plugin 34 | msgid "Easily share WordPress posts on Mastodon." 35 | msgstr "" 36 | 37 | #. Author of the plugin 38 | msgid "Jan Boddez" 39 | msgstr "" 40 | 41 | #. Author URI of the plugin 42 | msgid "https://jan.boddez.net/" 43 | msgstr "" 44 | 45 | #. translators: %s: error message 46 | #: includes/class-notices.php:50 47 | msgid "Share on Mastodon ran into the following error: %s" 48 | msgstr "" 49 | 50 | #. translators: %s: link to Mastodon status 51 | #: includes/class-notices.php:71 52 | msgid "Shared on Mastodon at %s." 53 | msgstr "" 54 | 55 | #: includes/class-plugin-options.php:99 56 | msgid "Please provide a valid URL." 57 | msgstr "" 58 | 59 | #: includes/class-plugin-options.php:208 60 | msgid "Setup" 61 | msgstr "" 62 | 63 | #: includes/class-plugin-options.php:209 64 | msgid "Post Types" 65 | msgstr "" 66 | 67 | #: includes/class-plugin-options.php:210 68 | msgid "Images" 69 | msgstr "" 70 | 71 | #: includes/class-plugin-options.php:211 72 | msgid "Advanced" 73 | msgstr "" 74 | 75 | #: includes/class-plugin-options.php:212 76 | msgid "Debugging" 77 | msgstr "" 78 | 79 | #: includes/class-plugin-options.php:226 80 | msgid "Instance" 81 | msgstr "" 82 | 83 | #. translators: %s: example URL. 84 | #: includes/class-plugin-options.php:229 85 | msgid "Your Mastodon instance’s URL. E.g., %s." 86 | msgstr "" 87 | 88 | #: includes/class-plugin-options.php:235 89 | #: includes/class-plugin-options.php:277 90 | msgid "Authorize Access" 91 | msgstr "" 92 | 93 | #: includes/class-plugin-options.php:251 94 | msgid "Access granted!" 95 | msgstr "" 96 | 97 | #: includes/class-plugin-options.php:276 98 | msgid "Authorize WordPress to read and write to your Mastodon timeline in order to enable syndication." 99 | msgstr "" 100 | 101 | #: includes/class-plugin-options.php:282 102 | msgid "You’ve authorized WordPress to read and write to your Mastodon timeline." 103 | msgstr "" 104 | 105 | #: includes/class-plugin-options.php:297 106 | msgid "Revoke Access" 107 | msgstr "" 108 | 109 | #: includes/class-plugin-options.php:306 110 | msgid "Something went wrong contacting your Mastodon instance. Please reload this page to try again." 111 | msgstr "" 112 | 113 | #: includes/class-plugin-options.php:312 114 | msgid "Please fill out and save your Mastodon instance’s URL first." 115 | msgstr "" 116 | 117 | #: includes/class-plugin-options.php:329 118 | msgid "Supported Post Types" 119 | msgstr "" 120 | 121 | #: includes/class-plugin-options.php:344 122 | msgid "Post types for which sharing to Mastodon is possible. (Sharing can still be disabled on a per-post basis.)" 123 | msgstr "" 124 | 125 | #: includes/class-plugin-options.php:361 126 | msgid "Max. No. of Images" 127 | msgstr "" 128 | 129 | #: includes/class-plugin-options.php:363 130 | msgid "The maximum number of images that will be uploaded. (Mastodon supports up to 4 images.)" 131 | msgstr "" 132 | 133 | #: includes/class-plugin-options.php:366 134 | msgid "Featured Images" 135 | msgstr "" 136 | 137 | #: includes/class-plugin-options.php:367 138 | msgid "Include featured images" 139 | msgstr "" 140 | 141 | #: includes/class-plugin-options.php:368 142 | msgid "Upload featured images." 143 | msgstr "" 144 | 145 | #: includes/class-plugin-options.php:371 146 | msgid "In-Post Images" 147 | msgstr "" 148 | 149 | #: includes/class-plugin-options.php:372 150 | msgid "Include “in-post” images" 151 | msgstr "" 152 | 153 | #: includes/class-plugin-options.php:373 154 | msgid "Upload “in-content” images. (Limited to images in the Media Library.)" 155 | msgstr "" 156 | 157 | #: includes/class-plugin-options.php:376 158 | msgid "Attached Images" 159 | msgstr "" 160 | 161 | #: includes/class-plugin-options.php:377 162 | msgid "Include attached images" 163 | msgstr "" 164 | 165 | #. translators: %s: link to official WordPress documentation. 166 | #: includes/class-plugin-options.php:379 167 | msgid "Upload %s." 168 | msgstr "" 169 | 170 | #. translators: %s: link to official WordPress documentation. 171 | #: includes/class-plugin-options.php:379 172 | msgid "attached images" 173 | msgstr "" 174 | 175 | #: includes/class-plugin-options.php:396 176 | msgid "Delayed Sharing" 177 | msgstr "" 178 | 179 | #: includes/class-plugin-options.php:398 180 | msgid "The number of seconds (0–3600) WordPress should delay sharing after a post is first published. (Setting this to, e.g., “300”—that’s 5 minutes—may resolve issues with image uploads.)" 181 | msgstr "" 182 | 183 | #: includes/class-plugin-options.php:401 184 | msgid "Opt-In" 185 | msgstr "" 186 | 187 | #: includes/class-plugin-options.php:402 188 | msgid "Make sharing opt-in rather than opt-out" 189 | msgstr "" 190 | 191 | #: includes/class-plugin-options.php:403 192 | msgid "Have the “Share on Mastodon” checkbox unchecked by default." 193 | msgstr "" 194 | 195 | #: includes/class-plugin-options.php:406 196 | msgid "Share Always" 197 | msgstr "" 198 | 199 | #: includes/class-plugin-options.php:407 200 | msgid "Always share on Mastodon" 201 | msgstr "" 202 | 203 | #: includes/class-plugin-options.php:408 204 | msgid "“Force” sharing (regardless of the “Share on Mastodon” checkbox’s state), like when posting from a mobile app." 205 | msgstr "" 206 | 207 | #: includes/class-plugin-options.php:411 208 | msgid "Status Template" 209 | msgstr "" 210 | 211 | #. translators: %s: supported template tags 212 | #: includes/class-plugin-options.php:414 213 | msgid "Customize the default status template. Supported “template tags”: %s." 214 | msgstr "" 215 | 216 | #: includes/class-plugin-options.php:417 217 | msgid "Customize Status" 218 | msgstr "" 219 | 220 | #: includes/class-plugin-options.php:418 221 | msgid "Allow customizing Mastodon statuses" 222 | msgstr "" 223 | 224 | #. translators: %s: link to the `share_on_mastodon_status` documentation 225 | #: includes/class-plugin-options.php:420 226 | msgid "Add a custom “Message” field to Share on Mastodon’s “meta box.” (For more fine-grained control, please have a look at the %s filter instead.)" 227 | msgstr "" 228 | 229 | #: includes/class-plugin-options.php:424 230 | msgid "Meta Box" 231 | msgstr "" 232 | 233 | #: includes/class-plugin-options.php:425 234 | msgid "Use “classic” meta box" 235 | msgstr "" 236 | 237 | #: includes/class-plugin-options.php:426 238 | msgid "Replace Share on Mastodon’s “block editor sidebar panel” with a “classic” meta box (even for post types that use the block editor)." 239 | msgstr "" 240 | 241 | #: includes/class-plugin-options.php:431 242 | msgid "Micropub" 243 | msgstr "" 244 | 245 | #: includes/class-plugin-options.php:432 246 | msgid "Add syndication target" 247 | msgstr "" 248 | 249 | #: includes/class-plugin-options.php:433 250 | msgid "Add “Mastodon” as a Micropub syndication target." 251 | msgstr "" 252 | 253 | #: includes/class-plugin-options.php:439 254 | msgid "Syndication Links" 255 | msgstr "" 256 | 257 | #: includes/class-plugin-options.php:440 258 | msgid "Add Mastodon URLs to syndication links" 259 | msgstr "" 260 | 261 | #: includes/class-plugin-options.php:441 262 | msgid "(Experimental) Add Mastodon URLs to Syndication Links’ list of syndication links." 263 | msgstr "" 264 | 265 | #: includes/class-plugin-options.php:459 266 | msgid "Logging" 267 | msgstr "" 268 | 269 | #: includes/class-plugin-options.php:460 270 | msgid "Enable debug logging" 271 | msgstr "" 272 | 273 | #. translators: %s: link to the official WordPress documentation 274 | #: includes/class-plugin-options.php:462 275 | msgid "You’ll also need to set WordPress’ %s." 276 | msgstr "" 277 | 278 | #. translators: %s: link to the official WordPress documentation 279 | #: includes/class-plugin-options.php:462 280 | msgid "debug logging constants" 281 | msgstr "" 282 | 283 | #: includes/class-plugin-options.php:471 284 | msgid "Just in case, this button lets you delete Share on Mastodon’s settings. Note: This will not invalidate previously issued tokens! (You can, however, still invalidate them on your instance’s “Account > Authorized apps” page.)" 285 | msgstr "" 286 | 287 | #: includes/class-plugin-options.php:485 288 | msgid "Reset Settings" 289 | msgstr "" 290 | 291 | #: includes/class-plugin-options.php:495 292 | msgid "Below information is not meant to be shared with anyone but may help when troubleshooting issues." 293 | msgstr "" 294 | 295 | #: includes/class-plugin-options.php:522 296 | msgid "Are you sure you want to reset all settings?" 297 | msgstr "" 298 | 299 | #: includes/class-plugin-options.php:531 300 | msgid "You have insufficient permissions to access this page." 301 | msgstr "" 302 | 303 | #: includes/class-post-handler.php:325 304 | msgid "(Optional) Message" 305 | msgstr "" 306 | 307 | #: includes/class-post-handler.php:327 308 | msgid "Customize this post’s Mastodon status." 309 | msgstr "" 310 | 311 | #. translators: toot URL 312 | #: includes/class-post-handler.php:343 313 | #: assets/block-editor.js:185 314 | msgid "Shared at %s" 315 | msgstr "" 316 | 317 | #. translators: "unlink" link text 318 | #: includes/class-post-handler.php:345 319 | #: assets/block-editor.js:199 320 | msgid "Unlink" 321 | msgstr "" 322 | 323 | #: includes/class-post-handler.php:367 324 | msgid "Missing or invalid nonce." 325 | msgstr "" 326 | 327 | #: includes/class-post-handler.php:373 328 | msgid "Missing or incorrect post ID." 329 | msgstr "" 330 | 331 | #: includes/class-post-handler.php:379 332 | msgid "Insufficient rights." 333 | msgstr "" 334 | 335 | #: includes/class-post-handler.php:428 336 | #: assets/block-editor.js:194 337 | msgid "Forget this URL?" 338 | msgstr "" 339 | 340 | #: assets/block-editor.js:172 341 | msgid "(Optional) Custom Message" 342 | msgstr "" 343 | 344 | #: assets/block-editor.js:179 345 | msgid "Customize this post’s Mastodon status." 346 | msgstr "" 347 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | tests/* 14 | bootstrap\.php$ 15 | 16 | 17 | 18 | *\.php$ 19 | 20 | 21 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | ./tests/ 13 | ./tests/test-sample.php 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | === Share on Mastodon === 2 | Contributors: janboddez 3 | Tags: mastodon, social, fediverse, syndication, posse 4 | Tested up to: 6.6 5 | Stable tag: 0.19.1 6 | License: GNU General Public License v3.0 7 | License URI: https://www.gnu.org/licenses/gpl-3.0.html 8 | 9 | Automatically share WordPress posts on Mastodon. 10 | 11 | == Description == 12 | Automatically share WordPress posts on [Mastodon](https://joinmastodon.org/). 13 | 14 | You choose which post types are shared, and sharing can still be disabled on a per-post basis. 15 | 16 | Supports WordPress' new block editor, image uploads and alt text, "template tags," and comes with a number of filter hooks for developers. 17 | 18 | More details can be found on [this plugin's web page](https://jan.boddez.net/wordpress/share-on-mastodon). 19 | 20 | = Credit = 21 | Share icon by [Heroicons](https://heroicons.dev/), licensed under the terms of the MIT License. Elephant illustration sourced from Mastodon's [Press Kit](https://joinmastodon.org/press-kit.zip). 22 | 23 | == Installation == 24 | Within WordPress' admin interface, visit *Plugins > Add New* and search for "share on mastodon" to locate the plugin. (Alternatively, upload this plugin's ZIP file via the "Upload Plugin" button.) 25 | 26 | After activation, head over to *Settings > Share on Mastodon* to authorize WordPress to post to your Mastodon account. 27 | 28 | More detailed instructions can be found on [this plugin's web page](https://jan.boddez.net/wordpress/share-on-mastodon). 29 | 30 | == Changelog == 31 | = 0.19.1 = 32 | Auto-disable share toggle ("block editor") for older posts. Fix default "share" value. Provide fallback when `mime_content_type()` is undefined. 33 | 34 | = 0.19.0 = 35 | Update `share_on_mastodon_enabled` filter. Improve compatibility with Syndication Links. Rework `Options_Handler`. 36 | 37 | = 0.17.4 = 38 | Also allow pages. 39 | 40 | = 0.17.3 = 41 | Fix max images option. 42 | 43 | = 0.17.2 = 44 | Fix permalinks with emoji in them. Somewhat smarter `%excerpt%` lengths. 45 | 46 | = 0.17.1 = 47 | Various bug fixes. 48 | 49 | = 0.17.0 = 50 | Introduce Gutenberg sidebar panel. 51 | 52 | = 0.16.1 = 53 | Deprecate `share_on_mastodon_cutoff` filter. Minor improvements. 54 | 55 | = 0.16.0 = 56 | Improved alt text discovery. 57 | 58 | = 0.15.0 = 59 | Better custom status messages: template tags, default template. Address odd Gutenberg behavior. 60 | 61 | = 0.14.0 = 62 | A very first implementation of optional custom status messages. 63 | 64 | = 0.13.1 = 65 | Improve Syndication Links compatibility. 66 | 67 | = 0.13.0 = 68 | Prevent accidental sharing of (very) old posts. 69 | 70 | = 0.12.2 = 71 | Custom field fix. 72 | 73 | = 0.12.1 = 74 | Filterable media array. 75 | 76 | = 0.12.0 = 77 | Configurable debug logging. 78 | 79 | = 0.11.0 = 80 | More flexible/robust instance URL handling. Overhauled plugin options. Syndication Links compatibility. 81 | -------------------------------------------------------------------------------- /share-on-mastodon.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "." 5 | } 6 | ], 7 | "settings": { 8 | "files.exclude": { 9 | ".phpunit.result.cache": true, 10 | "svn": true, 11 | "vendor": true, 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /share-on-mastodon.php: -------------------------------------------------------------------------------- 1 | 16 | * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0 17 | * @package Share_On_Mastodon 18 | */ 19 | 20 | namespace Share_On_Mastodon; 21 | 22 | // Prevent direct access. 23 | if ( ! defined( 'ABSPATH' ) ) { 24 | exit; 25 | } 26 | 27 | require __DIR__ . '/includes/class-block-editor.php'; 28 | require __DIR__ . '/includes/class-image-handler.php'; 29 | require __DIR__ . '/includes/class-mastodon-client.php'; 30 | require __DIR__ . '/includes/class-micropub-compat.php'; 31 | require __DIR__ . '/includes/class-notices.php'; 32 | require __DIR__ . '/includes/class-options-handler.php'; 33 | require __DIR__ . '/includes/class-plugin-options.php'; 34 | require __DIR__ . '/includes/class-post-handler.php'; 35 | require __DIR__ . '/includes/class-share-on-mastodon.php'; 36 | require __DIR__ . '/includes/class-syn-links-compat.php'; 37 | require __DIR__ . '/includes/functions.php'; 38 | 39 | Share_On_Mastodon::get_instance() 40 | ->register(); 41 | --------------------------------------------------------------------------------