From dccb8ed9bd0f07ceba6164e4849285ae2002e806 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Wed, 18 Nov 2026 01:22:00 +0100 Subject: [PATCH] Consolidate HG WordPress plugins --- .gitignore | 3 + LICENSE | 338 +++++++++++++++++++++++++++++++++++++ README.md | 31 ++++ assets/feed.css | 167 ++++++++++++++++++ assets/feed.js | 22 +++ assets/hg-admin-menu.css | 11 ++ hg-socialfeed.php | 53 ++++++ includes/admin.php | 209 +++++++++++++++++++++++ includes/facebook.php | 74 ++++++++ includes/hg-admin-menu.php | 52 ++++++ includes/instagram.php | 91 ++++++++++ includes/shortcode.php | 145 ++++++++++++++++ includes/sources.php | 196 +++++++++++++++++++++ includes/x.php | 53 ++++++ readme.txt | 25 +++ scripts/build.py | 37 ++++ scripts/build.sh | 3 + tests/integration.php | 191 +++++++++++++++++++++ 18 files changed, 1701 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 assets/feed.css create mode 100644 assets/feed.js create mode 100644 assets/hg-admin-menu.css create mode 100644 hg-socialfeed.php create mode 100644 includes/admin.php create mode 100644 includes/facebook.php create mode 100644 includes/hg-admin-menu.php create mode 100644 includes/instagram.php create mode 100644 includes/shortcode.php create mode 100644 includes/sources.php create mode 100644 includes/x.php create mode 100644 readme.txt create mode 100755 scripts/build.py create mode 100755 scripts/build.sh create mode 100644 tests/integration.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..21faee5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +dist/ +__pycache__/ +*.pyc diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9efa6fb --- /dev/null +++ b/LICENSE @@ -0,0 +1,338 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Moe Ghoul, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b330ec0 --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# HG Social Feed + +WordPress-plugin voor recente berichten van Instagram, Facebook en X en voor een losse balk met profieliconen. Vereist WordPress 6.5+, PHP 8.1+, MySQL of MariaDB en een werkende WP-Cron. Per WordPress-site kun je één profiel per platform instellen. + +## WordPress instellen + +Open **HG Plugins → Social Feed**. Vul een gebruikersnaam in voor Instagram of X. Voor Facebook volstaat de paginanaam uit de URL of het numerieke pagina-ID. Dit is genoeg om de profiellinks en iconen te gebruiken. + +Voor automatische berichten zijn aanvullende toegangsgegevens nodig. + +- **Instagram** verwerkt berichten van een professioneel Instagram-account. Voeg het account in het Meta App Dashboard toe onder **API setup with Instagram business login**, geef `instagram_business_basic` en kies **Generate token** naast het account. Gebruik een vers langlevend dashboardtoken. WordPress probeert het token na één dag te verlengen en vervolgens twee weken vóór de nieuwe vervaldatum. [Meta-handleiding voor Instagram](https://developers.facebook.com/documentation/instagram-platform/instagram-api-with-instagram-login/get-started) +- **Facebook** haalt gepubliceerde berichten op van een openbare Facebook-pagina die je beheert. Vul het numerieke pagina-ID in en gebruik een paginatoegangstoken met `pages_read_engagement`. Voor het opvragen van de beheerde pagina's bij Meta kan `pages_show_list` nodig zijn. Stel een nieuw token in zodra Meta de toegang intrekt. Facebook Reels hebben een aparte API en vallen buiten deze koppeling. [Meta-handleiding voor paginaberichten](https://developers.facebook.com/docs/graph-api/reference/page/published_posts) +- **X** vraagt dagelijks maximaal vijf recente openbare berichten op, exclusief antwoorden en reposts. Vul het app-only Bearer Token uit de X Developer Console in en zet automatisch ophalen expliciet aan. Opslaan en **Nu synchroniseren** kunnen dan ook API-verbruik opleveren. X rekent per opgehaald API-resultaat en beheert de bestedingslimiet in de Developer Console. [Tarieven van X](https://docs.x.com/x-api/getting-started/pricing) + +## Shortcodes + +`[hg_socialfeed]` toont maximaal 24 recentste berichten als gecombineerd overzicht, nieuwste eerst. De eerste acht zijn meteen zichtbaar. **Meer berichten** toont de volgende groep. Pas de groepsgrootte aan met `[hg_socialfeed limit="4"]` of kies bronnen met `[hg_socialfeed sources="instagram,facebook"]`. + +`[hg_sociallinks]` toont alleen links naar de ingestelde profielen als iconenbalk. Gebruik bijvoorbeeld `[hg_sociallinks sources="facebook,x"]` voor een selectie. De iconenbalk heeft geen API-token of externe scripts nodig. + +## Synchronisatie en weergave + +- WordPress haalt Meta-bronnen twee keer per dag op. De website leest de opgeslagen resultaten en maakt zelf geen API-aanroepen. Een bron die tijdelijk onbereikbaar is, kan zijn laatste resultaten nog maximaal 48 uur tonen. Voor X geldt 25 uur. Als er geen resultaten beschikbaar zijn, blijft de profiellink beschikbaar. +- Instagram toont foto's, carrousels en videominiaturen. Facebook toont foto's en tekstberichten. De links openen de oorspronkelijke berichten. De browser laadt afbeeldingen vanaf Meta's CDN met `no-referrer`. +- X wordt weergegeven met het officiële X-embedscript en de privacyoptie `data-dnt`. Alleen een pagina met X-berichten laadt dat script. Bezoekers kunnen bij een geblokkeerd of onbeschikbaar embed het bericht via de link openen. [Embed-documentatie van X](https://docs.x.com/x-for-websites/embedded-posts/overview) +- De plugin bewaart tokens per platform in WordPress buiten autoload. Tokens worden nooit terug getoond. Met **Koppeling verwijderen** verwijder je het opgeslagen token en de opgehaalde berichten en behoud je de profielgegevens. +- Deactiveren stopt de geplande synchronisaties. Versie 0.2.0 gebruikt de bestaande Instagram-opties en de bestaande cronhook. Om terug te gaan naar 0.1.0 kun je de plugin deactiveren, de vorige ZIP installeren en weer activeren. + +## Bouwen en testen + +Bouw de installeerbare ZIP met `python3 scripts/build.py`. Voer de integratietest uit met `wp --skip-plugins=hg_socialfeed eval-file /pad/naar/tests/integration.php` op een testinstallatie met een bestaande WordPress-beheerder. De test simuleert API-antwoorden en houdt testdata in het testproces. diff --git a/assets/feed.css b/assets/feed.css new file mode 100644 index 0000000..6d2c41c --- /dev/null +++ b/assets/feed.css @@ -0,0 +1,167 @@ +.hgsf-feed .hgsf-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: clamp(0.5rem, 2vw, 1rem); + list-style: none; + margin: 0; + padding: 0; +} + +.hgsf-feed .hgsf-grid > li { + margin: 0; + padding: 0; +} + +.hgsf-feed .hgsf-post { + position: relative; + display: block; + aspect-ratio: 1; + border-radius: var(--hgsf-radius, 0.5rem); +} + +.hgsf-feed .hgsf-post img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + border-radius: inherit; + background-color: #f0f2ef; +} + +.hgsf-feed .hgsf-video { + position: absolute; + inset: 0.5rem 0.5rem auto auto; + border-radius: 50%; + background: rgb(0 0 0 / 65%); + color: #fff; + font-size: 0.75rem; + width: 2rem; + height: 2rem; + display: grid; + place-items: center; +} + +.hgsf-feed .hgsf-grid + .hgsf-actions { + margin-top: 1rem; +} + +.hgsf-feed .hgsf-actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 0.75rem 1.25rem; +} + +.hgsf-feed .hgsf-more { + font: inherit; + color: var(--hgsf-accent, inherit); + background: transparent; + border: 1px solid currentColor; + border-radius: var(--hgsf-radius, 0.5rem); + padding: 0.5rem 1rem; + min-height: 44px; + cursor: pointer; +} + +.hgsf-feed .hgsf-profile { + color: var(--hgsf-accent, inherit); + text-underline-offset: 0.2em; + overflow-wrap: anywhere; +} + +.hgsf-feed [hidden] { + display: none; +} + +.hgsf-feed :is(.hgsf-post, .hgsf-more, .hgsf-profile):focus-visible { + outline: 2px solid currentColor; + outline-offset: 3px; +} + +@media (max-width: 47rem) { + .hgsf-feed .hgsf-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +.hgsf-feed .hgsf-platform { + position: absolute; + inset: auto auto 0.5rem 0.5rem; + padding: 0.2rem 0.5rem; + border-radius: 0.25rem; + background: rgb(0 0 0 / 75%); + color: #fff; + font-size: 0.75rem; +} + +.hgsf-feed .hgsf-text-post { + box-sizing: border-box; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 0.65rem; + padding: 0.75rem; + background: var(--hgsf-surface, #f0f2ef); + aspect-ratio: auto; + min-height: 100%; + text-decoration: none; + overflow-wrap: anywhere; +} + +.hgsf-feed .hgsf-text-post:hover { + text-decoration: underline; +} + +.hgsf-feed :is(.hgsf-text-platform, .hgsf-text-date) { + font-size: 0.8rem; +} + +.hgsf-feed .hgsf-x-tile { + grid-column: span 2; + min-width: 0; +} + +.hgsf-feed .hgsf-x-embed { + margin: 0; + padding: 0.75rem; + background: var(--hgsf-surface, #f0f2ef); + border-radius: var(--hgsf-radius, 0.5rem); +} + +.hgsf-feed .hgsf-x-tile iframe { + max-width: 100%; +} + +ul.hgsf-sociallinks { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + list-style: none; + margin: 0; + padding: 0; +} + +.hgsf-sociallinks > li { + margin: 0; + padding: 0; +} + +.hgsf-sociallinks a { + display: grid; + place-items: center; + width: 44px; + height: 44px; + border: 1px solid currentColor; + border-radius: 50%; + color: var(--hgsf-accent, inherit); +} + +.hgsf-sociallinks a:hover { + background: var(--hgsf-surface, #f0f2ef); +} + +.hgsf-sociallinks a:focus-visible { + outline: 2px solid currentColor; + outline-offset: 3px; +} diff --git a/assets/feed.js b/assets/feed.js new file mode 100644 index 0000000..3589484 --- /dev/null +++ b/assets/feed.js @@ -0,0 +1,22 @@ +(() => { + for (const feed of document.querySelectorAll('.hgsf-feed')) { + const button = feed.querySelector('.hgsf-more'); + if (!button) continue; + + const tiles = [...feed.querySelectorAll('.hgsf-grid > li')]; + const batchSize = Number(feed.dataset.hgsfLimit); + let visible = batchSize; + + for (const tile of tiles.slice(visible)) tile.hidden = true; + button.hidden = false; + + button.addEventListener('click', () => { + const nextBatch = tiles.slice(visible, visible + batchSize); + for (const tile of nextBatch) tile.hidden = false; + visible += nextBatch.length; + button.hidden = visible === tiles.length; + const firstTile = nextBatch[0]; + (firstTile.querySelector('a') || firstTile).focus(); + }); + } +})(); diff --git a/assets/hg-admin-menu.css b/assets/hg-admin-menu.css new file mode 100644 index 0000000..0674c09 --- /dev/null +++ b/assets/hg-admin-menu.css @@ -0,0 +1,11 @@ +/* HG navigation only; leave the rest of the WordPress admin color scheme intact. */ +#adminmenu #toplevel_page_hg-plugins>a.menu-top{background:#173b37;color:#d8fff3;box-shadow:inset 3px 0 #56d5bb} +#adminmenu #toplevel_page_hg-plugins .wp-menu-image::before{color:#80e9d1} +#adminmenu #toplevel_page_hg-plugins:hover>a.menu-top,#adminmenu #toplevel_page_hg-plugins>a.menu-top:focus{background:#20574e;color:#fff} +#adminmenu #toplevel_page_hg-plugins.wp-has-current-submenu>a.menu-top,#adminmenu #toplevel_page_hg-plugins.current>a.menu-top{background:#126151;color:#fff} +#adminmenu #toplevel_page_hg-plugins .wp-submenu{background:#16332f} +#adminmenu #toplevel_page_hg-plugins .wp-submenu a{color:#d0e6de} +#adminmenu #toplevel_page_hg-plugins .wp-submenu a:hover,#adminmenu #toplevel_page_hg-plugins .wp-submenu a:focus{color:#fff;background:#24584e} +#adminmenu #toplevel_page_hg-plugins .wp-submenu li.current a{color:#fff;font-weight:600;background:#205147} +#adminmenu #toplevel_page_hg-plugins .wp-submenu .wp-submenu-head{color:#fff;background:#126151} +.hg-suite{max-width:1100px}.hg-suite-header{display:flex;align-items:center;gap:18px;margin:28px 0}.hg-suite-header h1{padding:0;font-size:26px}.hg-suite-header p{margin:7px 0 0;color:#50575e}.hg-suite-mark{display:grid;place-items:center;width:58px;height:58px;background:#126151;color:#fff;border-radius:10px;font-weight:750;font-size:21px;letter-spacing:-1px}.hg-suite-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:22px}.hg-suite-card{background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:26px}.hg-suite-card h2{margin:12px 0;font-size:20px}.hg-suite-card p{color:#50575e;font-size:14px;line-height:1.7;min-height:48px}.hg-suite-version{display:inline-block;padding:4px 9px;border-radius:5px;color:#145c4c;background:#e9f5ee;font-size:12px}.hg-suite-card .button{margin-top:12px}@media(max-width:782px){.hg-suite-grid{grid-template-columns:1fr}.hg-suite-header{gap:14px}.hg-suite-card{padding:22px}} diff --git a/hg-socialfeed.php b/hg-socialfeed.php new file mode 100644 index 0000000..1ff365b --- /dev/null +++ b/hg-socialfeed.php @@ -0,0 +1,53 @@ + hgsf_sync_source('facebook')); +add_action('hgsf_sync_x', static fn () => hgsf_sync_source('x')); + +register_activation_hook(__FILE__, 'hgsf_schedule_events'); +register_deactivation_hook(__FILE__, static function (): void { + foreach (array_keys(HGSF_SOURCES) as $source) { + wp_clear_scheduled_hook('hgsf_sync_' . $source); + } +}); + +add_action('admin_init', static function (): void { + if (get_option('hgsf_cron_version') !== HGSF_VERSION) { + hgsf_schedule_events(); + } +}); +add_shortcode('hg_socialfeed', 'hgsf_shortcode'); +add_shortcode('hg_sociallinks', 'hgsf_sociallinks_shortcode'); + +add_filter('plugin_action_links_' . plugin_basename(__FILE__), static function (array $links): array { + if (current_user_can('manage_options')) { + $links[] = 'Instellingen'; + } + return $links; +}); diff --git a/includes/admin.php b/includes/admin.php new file mode 100644 index 0000000..7b363e6 --- /dev/null +++ b/includes/admin.php @@ -0,0 +1,209 @@ + 'hg-socialfeed', + 'label' => 'Social Feed', + 'title' => 'HG Social Feed', + 'description' => 'Toon berichten en profiellinks van Instagram, Facebook en X.', + 'version' => HGSF_VERSION, + 'callback' => 'hgsf_admin_page', +]); + +function hgsf_admin_page(): void { + if (!current_user_can('manage_options')) { + wp_die('Geen toegang.', '', ['response' => 403]); + } + $notice = match ($_GET['hgsf_notice'] ?? '') { + 'saved' => ['success', 'Instellingen opgeslagen.'], + 'synced' => ['success', 'Berichten opgehaald.'], + 'failed' => ['error', 'Het ophalen is mislukt. Bekijk de status van het platform.'], + 'invalid' => ['error', 'Controleer het profiel en het toegangstoken van het platform.'], + 'busy' => ['error', 'Er loopt al een synchronisatie voor dit platform. Probeer het zo opnieuw.'], + 'disconnected' => ['success', 'Toegangstoken en opgeslagen berichten verwijderd. De profiellink blijft beschikbaar.'], + default => null, + }; + ?> +
+
+ +

HG Social Feed

Beheer de bronnen voor berichten en profieliconen.

+
+ +

+ + +
+ $provider) : + hgsf_admin_source($source, $provider['label']); + endforeach; ?> +
+ +

Plaatsen op de website

+

[hg_socialfeed] toont de recentste berichten en links naar de profielen.

+

[hg_sociallinks] toont alleen de iconenbalk met links naar de ingestelde profielen.

+

Beperk desgewenst de bronnen met sources="instagram,facebook".

+
+ [ + 'Gebruik een langlevend Instagram-toegangstoken uit het Meta App Dashboard.', + 'https://developers.facebook.com/documentation/instagram-platform/instagram-api-with-instagram-login/get-started', + ], + 'facebook' => [ + 'Gebruik een paginatoegangstoken voor een Facebook-pagina die je beheert.', + 'https://developers.facebook.com/docs/graph-api/reference/page/published_posts', + ], + 'x' => [ + 'Gebruik het app-only Bearer Token uit de X Developer Console.', + 'https://docs.x.com/x-api/getting-started/pricing', + ], + }; + $can_sync = $connection['token'] && ($source !== 'x' || $connection['enabled']); + ?> +
+

+
+ + + +

+
+ +

+ +

+
+ +
Optioneel voor de profiellink. Bijvoorbeeld mijnbedrijf uit facebook.com/mijnbedrijf. +

+ +

+
+ +
+ + Documentatie + +

+ +

+ +

+ + + + + + + +

+
+ +

Automatisch ophalen staat uit.

+ +

+ +

+ +

De eerste synchronisatie staat nog open.

+ + +

Het token kon nog niet automatisch worden verlengd. WordPress probeert het bij de volgende synchronisatie opnieuw.

+ +
+ 403]); + } + $source = $_POST['source'] ?? ''; + if (!is_string($source) || !isset(HGSF_SOURCES[$source])) { + wp_die('Ongeldig platform.', '', ['response' => 400]); + } + check_admin_referer('hgsf_settings_' . $source, 'hgsf_nonce_' . $source); + $result = hgsf_with_connection_lock(static fn () => hgsf_save_settings($source, $_POST), $source); + $notice = is_wp_error($result) ? 'busy' : $result; + wp_safe_redirect(add_query_arg(['page' => 'hg-socialfeed', 'hgsf_notice' => $notice], admin_url('admin.php'))); + exit; +} + +function hgsf_save_settings(string $source, array $input): string { + $connection = hgsf_connection($source); + $provider = HGSF_SOURCES[$source]; + $operation = $input['operation'] ?? ''; + if ($operation === 'disconnect') { + $connection['id'] = wp_generate_uuid4(); + $connection['token'] = ''; + $connection['saved_at'] = 0; + $connection['enabled'] = false; + update_option($provider['connection'], $connection, false); + delete_option($provider['snapshot']); + return 'disconnected'; + } + if ($operation === 'sync') { + return is_wp_error(hgsf_update_snapshot($connection, $source)) ? 'failed' : 'synced'; + } + if ($operation !== 'save') { + return 'invalid'; + } + + $username = $input['username'] ?? ''; + $token = $input['token'] ?? ''; + $profile = $source === 'facebook' ? ($input['profile'] ?? '') : ''; + if (!is_string($username) || !is_string($token) || !is_string($profile)) { + return 'invalid'; + } + $username = strtolower(ltrim(trim(wp_unslash($username)), '@')); + $token = trim(wp_unslash($token)); + $profile = trim(wp_unslash($profile)); + $enabled = $source === 'x' && ($input['enabled'] ?? '') === '1'; + $pattern = match ($source) { + 'instagram' => '/^[a-z0-9._]{1,30}$/D', + 'facebook' => '/^[0-9]{1,30}$/D', + 'x' => '/^[a-z0-9_]{1,15}$/D', + }; + if (($username !== '' && !preg_match($pattern, $username)) + || ($profile !== '' && !preg_match('/^[a-z0-9.]{1,75}$/iD', $profile)) + || ($token !== '' && ($username === '' || !hgsf_valid_token($token, $source)))) { + return 'invalid'; + } + + $credentials_changed = $username !== $connection['username'] || $token !== ''; + $enable_changed = $enabled !== $connection['enabled']; + if ($enabled && ($username === '' || ($token === '' && ($credentials_changed || !$connection['token'])))) { + return 'invalid'; + } + + if ($credentials_changed) { + $connection['id'] = wp_generate_uuid4(); + $connection['username'] = $username; + $connection['token'] = $token; + $connection['saved_at'] = time(); + } + $connection['profile'] = $profile; + $connection['enabled'] = $enabled; + update_option($provider['connection'], $connection, false); + if ($credentials_changed || $enable_changed) { + delete_option($provider['snapshot']); + if ($connection['token'] && ($source !== 'x' || $enabled)) { + return is_wp_error(hgsf_update_snapshot($connection, $source)) ? 'failed' : 'synced'; + } + } + return 'saved'; +} + +add_action('admin_post_hgsf_settings', 'hgsf_handle_settings'); diff --git a/includes/facebook.php b/includes/facebook.php new file mode 100644 index 0000000..6f656d1 --- /dev/null +++ b/includes/facebook.php @@ -0,0 +1,74 @@ + is_string($value) && preg_match('/^[a-z0-9_-]+$/iD', $value) === 1 + ); + return 'https://www.facebook.com' . $path . ($query ? '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986) : ''); +} + +function hgsf_fetch_facebook(array $connection): array|WP_Error { + $token = $connection['token']; + $page = hgsf_http_get('facebook', HGSF_FACEBOOK_VERSION . '/me', [ + 'fields' => 'id,is_published', + ], $token); + if (is_wp_error($page)) { + return $page; + } + $page_id = $page['id'] ?? ''; + if ((!is_string($page_id) && !is_int($page_id)) || (string) $page_id !== $connection['username']) { + return new WP_Error('account', 'Het Facebook-paginatoken hoort niet bij het ingestelde pagina-ID.'); + } + if (($page['is_published'] ?? null) !== true) { + return new WP_Error('private', 'De Facebook-pagina is niet openbaar gepubliceerd.'); + } + + $response = hgsf_http_get('facebook', HGSF_FACEBOOK_VERSION . '/' . $connection['username'] . '/published_posts', [ + 'fields' => 'permalink_url,message,full_picture,created_time,is_hidden,is_published,is_expired', + 'limit' => HGSF_POSTS_MAX, + ], $token); + if (is_wp_error($response)) { + return $response; + } + if (!is_array($response['data'] ?? null)) { + return new WP_Error('api', 'Facebook heeft geen leesbare berichtenlijst teruggegeven.'); + } + + $posts = []; + foreach ($response['data'] as $post) { + $link = hgsf_facebook_permalink($post['permalink_url'] ?? null); + if (!$link || !empty($post['is_hidden']) || !empty($post['is_expired']) || ($post['is_published'] ?? true) !== true) { + continue; + } + $image = hgsf_media_url($post['full_picture'] ?? null, '/(?:^|\.)(fbcdn\.net|fbsbx\.com)$/iD'); + $message = $post['message'] ?? ''; + $timestamp = $post['created_time'] ?? ''; + $caption = is_string($message) ? sanitize_text_field($message) : ''; + $posts[$link] = [ + 'link' => $link, + 'image' => $image, + 'caption' => wp_html_excerpt($caption, 180, '…'), + 'type' => $image ? 'IMAGE' : 'TEXT', + 'date' => (is_string($timestamp) ? strtotime($timestamp) : false) ?: 0, + ]; + } + return array_values($posts); +} diff --git a/includes/hg-admin-menu.php b/includes/hg-admin-menu.php new file mode 100644 index 0000000..d8a66af --- /dev/null +++ b/includes/hg-admin-menu.php @@ -0,0 +1,52 @@ + strcasecmp($a['label'], $b['label'])); + foreach (self::$plugins as $slug => $plugin) { + self::$hooks[$slug] = (string) add_submenu_page('hg-plugins', $plugin['title'], $plugin['label'], 'manage_options', $slug, $plugin['callback']); + } + } + + public static function styles(): void { + if (!self::$plugins || !current_user_can('manage_options')) return; + wp_enqueue_style('hg-admin-menu', plugins_url('../assets/hg-admin-menu.css', __FILE__), [], '1.0.0'); + } + + public static function overview(): void { + if (!current_user_can('manage_options')) wp_die('Geen toegang.', '', ['response' => 403]); + ?> +
+

HG Plugins

De Hippogrief-modules op deze website.

+
+ $plugin): ?> +
Versie

Beheren
+ +
+
+ $link, + 'image' => $image, + 'type' => $type, + 'caption' => is_string($caption) ? wp_html_excerpt(sanitize_text_field($caption), 140, '…') : '', + 'date' => (is_string($timestamp) ? strtotime($timestamp) : false) ?: 0, + ]; + } + + return array_values($posts); +} + +function hgsf_sync_instagram(): bool|WP_Error { + return hgsf_sync_source('instagram'); +} + +function hgsf_fetch_instagram(array $connection, array &$snapshot, int $now): array|WP_Error { + $token = $snapshot['refreshed_token'] ?? $connection['token']; + // Meta accepts a renewal once the token is at least one day old. + $refresh_at = $snapshot['refresh_at'] ?? ($connection['saved_at'] + DAY_IN_SECONDS); + if ($now >= $refresh_at) { + $renewed = hgsf_http_get('instagram', 'refresh_access_token', ['grant_type' => 'ig_refresh_token'], $token); + $snapshot['refresh_failed'] = true; + if (!is_wp_error($renewed) && hgsf_valid_token($renewed['access_token'] ?? null) + && (int) ($renewed['expires_in'] ?? 0) > DAY_IN_SECONDS) { + $token = $renewed['access_token']; + $snapshot['refreshed_token'] = $token; + $snapshot['expires_at'] = $now + (int) $renewed['expires_in']; + $snapshot['refresh_at'] = max($now + DAY_IN_SECONDS, $snapshot['expires_at'] - 14 * DAY_IN_SECONDS); + $snapshot['refresh_failed'] = false; + } + } + + $profile = hgsf_http_get('instagram', HGSF_INSTAGRAM_VERSION . '/me', ['fields' => 'user_id,username'], $token); + $result = $profile; + if (!is_wp_error($profile)) { + $account = $profile['data'][0] ?? $profile; + $user_id = $account['user_id'] ?? ''; + $username = $account['username'] ?? ''; + if (!is_string($username) || strcasecmp($username, $connection['username']) !== 0 + || (!is_int($user_id) && !is_string($user_id)) || !ctype_digit((string) $user_id)) { + $result = new WP_Error('account', 'Het toegangstoken hoort niet bij de ingestelde Instagram-gebruikersnaam.'); + } else { + $result = hgsf_http_get('instagram', HGSF_INSTAGRAM_VERSION . '/' . $user_id . '/media', [ + 'fields' => 'id,media_type,media_url,thumbnail_url,permalink,caption,timestamp', + 'limit' => HGSF_POSTS_MAX, + ], $token); + if (!is_wp_error($result) && !is_array($result['data'] ?? null)) { + $result = new WP_Error('api', 'Instagram heeft geen leesbare berichtenlijst teruggegeven.'); + } + } + } + + return is_wp_error($result) ? $result : hgsf_instagram_posts($result['data']); +} diff --git a/includes/shortcode.php b/includes/shortcode.php new file mode 100644 index 0000000..0540e6d --- /dev/null +++ b/includes/shortcode.php @@ -0,0 +1,145 @@ + 8, 'sources' => implode(',', array_keys(HGSF_SOURCES))], (array) $attributes, 'hg_socialfeed'); + $limit = max(1, min(HGSF_POSTS_MAX, (int) $attributes['limit'])); + $posts = []; + $profiles = []; + foreach (hgsf_shortcode_sources($attributes) as $source => $provider) { + $connection = hgsf_connection($source); + $profile_url = hgsf_profile_url($source, $connection); + if ($profile_url) { + $profiles[$source] = $profile_url; + } + foreach (hgsf_cached_posts($connection, $source) as $post) { + $posts[] = ['source' => $source] + $post; + } + } + if (!$profiles) { + return ''; + } + $posts = array_slice(hgsf_sort_posts($posts), 0, HGSF_POSTS_MAX); + + hgsf_feed_styles(); + if (count($posts) > $limit) { + wp_enqueue_script('hg-socialfeed', plugins_url('assets/feed.js', HGSF_PLUGIN_FILE), [], HGSF_VERSION, ['in_footer' => true]); + } + if (in_array('x', array_column($posts, 'source'), true)) { + wp_enqueue_script('hg-socialfeed-x', 'https://platform.twitter.com/widgets.js', [], null, ['in_footer' => true, 'strategy' => 'async']); + } + + $grid_id = wp_unique_id('hgsf-grid-'); + ob_start(); + ?> +
+ +
    + +
  • > + 1); ?> +
  • + +
+ +
+ $limit) : ?> + + + $url) : ?> + Volg ons op + +
+
+ + + 'Bekijk de video', + 'CAROUSEL_ALBUM' => 'Bekijk de foto’s', + default => 'Bekijk het bericht', + }; + $label .= ' op ' . $platform; + $has_image = $post['image'] !== ''; + ?> + aria-label=""> + + + + + + + + + + + + + + + implode(',', array_keys(HGSF_SOURCES))], (array) $attributes, 'hg_sociallinks'); + $links = []; + foreach (hgsf_shortcode_sources($attributes) as $source => $provider) { + $url = hgsf_profile_url($source, hgsf_connection($source)); + if ($url) { + $links[$source] = $url; + } + } + if (!$links) { + return ''; + } + hgsf_feed_styles(); + + ob_start(); + ?> + + + + [ + 'label' => 'Instagram', + 'connection' => 'hgsf_connection', + 'snapshot' => 'hgsf_instagram_snapshot', + 'schedule' => 'twicedaily', + 'fetch' => 'hgsf_fetch_instagram', + ], + 'facebook' => [ + 'label' => 'Facebook', + 'connection' => 'hgsf_facebook_connection', + 'snapshot' => 'hgsf_facebook_snapshot', + 'schedule' => 'twicedaily', + 'fetch' => 'hgsf_fetch_facebook', + ], + 'x' => [ + 'label' => 'X', + 'connection' => 'hgsf_x_connection', + 'snapshot' => 'hgsf_x_snapshot', + 'schedule' => 'daily', + 'fetch' => 'hgsf_fetch_x', + ], +]; + +function hgsf_connection(string $source = 'instagram'): array { + $stored = get_option(HGSF_SOURCES[$source]['connection'], []); + return (is_array($stored) ? $stored : []) + [ + 'id' => '', + 'username' => '', + 'token' => '', + 'saved_at' => 0, + 'enabled' => false, + 'profile' => '', + ]; +} + +function hgsf_snapshot(array $connection, string $source = 'instagram'): array { + $snapshot = get_option(HGSF_SOURCES[$source]['snapshot'], []); + return $connection['id'] && ($snapshot['connection_id'] ?? '') === $connection['id'] ? $snapshot : []; +} + +function hgsf_cached_posts(array $connection, string $source = 'instagram'): array { + if ($source === 'x' && !$connection['enabled']) { + return []; + } + $snapshot = hgsf_snapshot($connection, $source); + $lifetime = $source === 'x' ? DAY_IN_SECONDS + HOUR_IN_SECONDS : HGSF_CACHE_LIFETIME; + return time() - ($snapshot['synced_at'] ?? 0) < $lifetime ? ($snapshot['posts'] ?? []) : []; +} + +function hgsf_profile_url(string $source, array $connection): string { + $username = $connection['username']; + if ($source === 'facebook' && $connection['profile'] !== '') { + $username = $connection['profile']; + } + if ($username === '') { + return ''; + } + return match ($source) { + 'instagram' => 'https://www.instagram.com/' . rawurlencode($username) . '/', + 'facebook' => 'https://www.facebook.com/' . rawurlencode($username), + 'x' => 'https://x.com/' . rawurlencode($username), + }; +} + +function hgsf_with_connection_lock(callable $operation, string $source = 'instagram'): mixed { + global $wpdb; + + // Serialize credential changes with WP-Cron for each source. + $name = 'hgsf_' . md5(DB_NAME . '/' . $wpdb->options . ($source === 'instagram' ? '' : '/' . $source)); + $acquired = $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 0)', $name)); + if ((int) $acquired !== 1) { + return new WP_Error('busy', 'Er loopt al een synchronisatie voor dit platform. Probeer het zo opnieuw.'); + } + + try { + return $operation(); + } finally { + $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $name)); + } +} + +function hgsf_http_get(string $source, string $path, array $query, string $token): array|WP_Error { + $host = match ($source) { + 'instagram' => 'graph.instagram.com', + 'facebook' => 'graph.facebook.com', + 'x' => 'api.x.com', + }; + $headers = ['Accept' => 'application/json']; + if ($source === 'instagram') { + $query['access_token'] = $token; + } else { + $headers['Authorization'] = 'Bearer ' . $token; + } + $url = 'https://' . $host . '/' . $path . '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986); + $response = wp_safe_remote_get($url, [ + 'headers' => $headers, + 'timeout' => 7, + 'redirection' => 0, + 'limit_response_size' => 256 * KB_IN_BYTES, + ]); + $label = HGSF_SOURCES[$source]['label']; + + if (is_wp_error($response)) { + return new WP_Error('unavailable', sprintf('%s is tijdelijk niet bereikbaar.', $label)); + } + $status = (int) wp_remote_retrieve_response_code($response); + $data = json_decode(wp_remote_retrieve_body($response), true, 512, JSON_BIGINT_AS_STRING); + if ($status === 401 || (int) ($data['error']['code'] ?? 0) === 190) { + return new WP_Error('token', sprintf('%s heeft het toegangstoken geweigerd. Controleer of het nog geldig is.', $label)); + } + if ($source === 'x' && $status === 402) { + return new WP_Error('credits', 'Controleer het beschikbare API-tegoed in de X Developer Console.'); + } + if ($status === 429) { + return new WP_Error('rate_limit', sprintf('%s heeft de API-limiet bereikt. WordPress probeert het bij de volgende synchronisatie opnieuw.', $label)); + } + if ($status !== 200 || !is_array($data) || isset($data['error']) || (!isset($data['data']) && !empty($data['errors']))) { + return new WP_Error('api', sprintf('%s heeft het verzoek geweigerd. Controleer de accounttoegang.', $label)); + } + return $data; +} + +function hgsf_valid_token($token, string $source = 'instagram'): bool { + $pattern = $source === 'x' ? '~^[A-Za-z0-9._\~+/%-]+=*$~D' : '~^[A-Za-z0-9._\~+/-]+=*$~D'; + return is_string($token) && strlen($token) <= 2048 && preg_match($pattern, $token) === 1; +} + +function hgsf_media_url($url, string $suffix_pattern): string { + if (!is_string($url)) { + return ''; + } + $url = esc_url_raw($url, ['https']); + $parts = wp_parse_url($url); + if (($parts['scheme'] ?? '') !== 'https' + || isset($parts['user']) || isset($parts['pass']) || isset($parts['port']) + || !preg_match($suffix_pattern, $parts['host'] ?? '')) { + return ''; + } + return $url; +} + +function hgsf_sort_posts(array $posts): array { + usort($posts, static fn (array $a, array $b): int => $b['date'] <=> $a['date']); + return $posts; +} + +function hgsf_sync_source(string $source): bool|WP_Error { + return hgsf_with_connection_lock(static fn () => hgsf_update_snapshot(hgsf_connection($source), $source), $source); +} + +function hgsf_update_snapshot(array $connection, string $source = 'instagram'): bool|WP_Error { + if (!$connection['token'] || ($source === 'x' && !$connection['enabled'])) { + return new WP_Error('disconnected', 'Voor dit platform is synchronisatie niet ingeschakeld.'); + } + + $snapshot = hgsf_snapshot($connection, $source); + $now = time(); + $fetch = HGSF_SOURCES[$source]['fetch']; + $result = $fetch($connection, $snapshot, $now); + + $snapshot['connection_id'] = $connection['id']; + $snapshot['attempted_at'] = $now; + $snapshot['error'] = ''; + if (is_wp_error($result)) { + $snapshot['error'] = $result->get_error_message(); + if (in_array($result->get_error_code(), ['private', 'account'], true)) { + unset($snapshot['posts'], $snapshot['synced_at']); + } + } else { + $snapshot['posts'] = array_slice(hgsf_sort_posts($result), 0, HGSF_POSTS_MAX); + $snapshot['synced_at'] = $now; + } + + update_option(HGSF_SOURCES[$source]['snapshot'], $snapshot, false); + return is_wp_error($result) ? $result : true; +} + +function hgsf_schedule_events(): void { + $ready = true; + foreach (HGSF_SOURCES as $source => $provider) { + $hook = 'hgsf_sync_' . $source; + if (!wp_next_scheduled($hook) && !wp_schedule_event(time() + MINUTE_IN_SECONDS, $provider['schedule'], $hook)) { + $ready = false; + } + } + if ($ready) { + update_option('hgsf_cron_version', HGSF_VERSION, false); + } +} diff --git a/includes/x.php b/includes/x.php new file mode 100644 index 0000000..ce34c20 --- /dev/null +++ b/includes/x.php @@ -0,0 +1,53 @@ + 'protected', + ], $token); + if (is_wp_error($response)) { + return $response; + } + $account = $response['data'] ?? []; + $id = $account['id'] ?? ''; + $username = $account['username'] ?? ''; + if (!is_string($id) || !preg_match('/^[0-9]{1,19}$/D', $id) || !is_string($username) || strcasecmp($username, $handle) !== 0) { + return new WP_Error('account', 'X heeft geen openbaar profiel gevonden voor de ingestelde gebruikersnaam.'); + } + if (($account['protected'] ?? null) !== false) { + return new WP_Error('private', 'Het ingestelde X-profiel is afgeschermd.'); + } + + $response = hgsf_http_get('x', '2/users/' . $id . '/tweets', [ + 'max_results' => 5, + 'exclude' => 'replies,retweets', + 'post.fields' => 'created_at,withheld', + ], $token); + if (is_wp_error($response)) { + return $response; + } + $data = $response['data'] ?? []; + if (!is_array($data) || (!isset($response['data']) && ($response['meta']['result_count'] ?? null) !== 0)) { + return new WP_Error('api', 'X heeft geen leesbare berichtenlijst teruggegeven.'); + } + + $posts = []; + foreach ($data as $post) { + $id = $post['id'] ?? ''; + $created_at = $post['created_at'] ?? ''; + $time = is_string($created_at) ? strtotime($created_at) : false; + if (!is_string($id) || !preg_match('/^[0-9]{1,19}$/D', $id) || !$time || !empty($post['withheld'])) { + continue; + } + $posts[$id] = [ + 'id' => $id, + 'link' => 'https://x.com/' . rawurlencode($handle) . '/status/' . $id, + 'type' => 'EMBED', + 'date' => $time, + ]; + } + return array_values($posts); +} diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..e88a575 --- /dev/null +++ b/readme.txt @@ -0,0 +1,25 @@ +=== HG Social Feed === +Requires at least: 6.5 +Requires PHP: 8.1 +Stable tag: 0.2.0 +License: GPLv2 or later + +Recente berichten en profiellinks van Instagram, Facebook en X. + +== Installation == + +Upload en activeer de plugin. Open HG Plugins → Social Feed om de gewenste profielen en API-koppelingen in te stellen. + += Shortcodes = + +* [hg_socialfeed] toont de recentste berichten van de gekoppelde platforms en links naar de ingestelde profielen. +* [hg_sociallinks] toont een losse iconenbalk met links naar de ingestelde profielen. +* Beide shortcodes ondersteunen sources="instagram,facebook". De feed ondersteunt ook limit="4". + +== Changelog == + += 0.2.0 = +Facebook-paginaberichten, optionele X-synchronisatie, een gecombineerd overzicht met bronselectie en een losse shortcode voor profieliconen. + += 0.1.0 = +Instagram-feed met automatische tokenverlenging, een raster, Meer berichten en een profiellink. diff --git a/scripts/build.py b/scripts/build.py new file mode 100755 index 0000000..4641e83 --- /dev/null +++ b/scripts/build.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Build the WordPress ZIP from explicitly listed release files.""" + +from pathlib import Path +import re +import sys +from zipfile import ZIP_DEFLATED, ZipFile + + +root = Path(__file__).resolve().parents[1] +destination = Path(sys.argv[1]) if len(sys.argv) > 1 else root / "dist" +version = re.search(r"^ \* Version: (\S+)$", (root / "hg-socialfeed.php").read_text(), re.MULTILINE) +if not version: + raise SystemExit("Missing plugin version") + +files = ( + "hg-socialfeed.php", + "README.md", + "readme.txt", + "LICENSE", + "includes/hg-admin-menu.php", + "includes/admin.php", + "includes/sources.php", + "includes/instagram.php", + "includes/facebook.php", + "includes/x.php", + "includes/shortcode.php", + "assets/hg-admin-menu.css", + "assets/feed.css", + "assets/feed.js", +) +destination.mkdir(parents=True, exist_ok=True) +release = destination / f"hg-socialfeed-{version[1]}.zip" +with ZipFile(release, "w", ZIP_DEFLATED) as archive: + for file in files: + archive.write(root / file, Path("hg_socialfeed") / file) +print(release.resolve()) diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..65ff3f0 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec python3 "$(dirname "${BASH_SOURCE[0]}")/build.py" "$@" diff --git a/tests/integration.php b/tests/integration.php new file mode 100644 index 0000000..844e009 --- /dev/null +++ b/tests/integration.php @@ -0,0 +1,191 @@ + ['id' => 'ig', 'username' => 'fixture', 'token' => 'ig-fixture-token', 'saved_at' => time() - 2 * DAY_IN_SECONDS], + 'facebook' => ['id' => 'fb', 'username' => '12345', 'profile' => 'example.page', 'token' => 'fb-fixture-token'], + 'x' => ['id' => 'x', 'username' => 'fixture_x', 'token' => 'x%2Ffixture', 'enabled' => false], +]; +$snapshots = []; +foreach (HGSF_SOURCES as $source => $provider) { + add_filter('pre_option_' . $provider['connection'], static function () use (&$connections, $source): array { + return $connections[$source] ?? []; + }); + add_filter('pre_update_option_' . $provider['connection'], static function ($value, $old) use (&$connections, $source) { + $connections[$source] = $value; + return $old; + }, 10, 2); + add_filter('pre_option_' . $provider['snapshot'], static function () use (&$snapshots, $source): array { + return $snapshots[$source] ?? []; + }); + add_filter('pre_update_option_' . $provider['snapshot'], static function ($value, $old) use (&$snapshots, $source) { + $snapshots[$source] = $value; + return $old; + }, 10, 2); +} + +$media = []; +for ($index = 1; $index <= 10; $index++) { + $media[] = [ + 'media_type' => $index === 10 ? 'VIDEO' : 'IMAGE', + 'media_url' => 'https://scontent-test.cdninstagram.com/image-' . $index . '.jpg', + 'thumbnail_url' => 'https://scontent-test.cdninstagram.com/video.jpg', + 'permalink' => 'https://www.instagram.com/p/fixture_' . $index . '/?igsh=test', + 'caption' => 'Voorbeeld "bericht"', + 'timestamp' => gmdate(DATE_ATOM, strtotime('2026-01-01') + $index * HOUR_IN_SECONDS), + ]; +} +$media[] = array_replace($media[0], ['permalink' => 'https://example.org/p/fixture/']); +$media[] = array_replace($media[0], ['media_url' => 'https://cdninstagram.com.example.org/image.jpg']); + +$mode = 'normal'; +$requests = []; +$mock_http = static function ($pre, array $args, string $url) use (&$mode, &$requests, $media) { + $parts = wp_parse_url($url); + $host = $parts['host']; + $path = $parts['path']; + parse_str($parts['query'], $query); + $requests[] = [$host, $path]; + hgsf_test(in_array($host, ['api.x.com', 'graph.instagram.com', 'graph.facebook.com'], true) && $args['redirection'] === 0, 'Unexpected outbound request.'); + + if ($mode === 'offline') { + return new WP_Error('test_offline', 'Original transport error should stay private.'); + } + if ($host === 'graph.instagram.com') { + if ($path === '/refresh_access_token') { + hgsf_test($query['access_token'] === 'ig-fixture-token' && $query['grant_type'] === 'ig_refresh_token', 'Instagram refresh parameters.'); + $data = ['access_token' => 'new-ig-fixture-token', 'expires_in' => 60 * DAY_IN_SECONDS]; + } elseif (str_ends_with($path, '/me')) { + hgsf_test($query['access_token'] === 'new-ig-fixture-token', 'Instagram reuses the renewed token.'); + $data = ['user_id' => '789', 'username' => $mode === 'wrong_ig' ? 'someone_else' : 'fixture']; + } else { + hgsf_test(str_ends_with($path, '/789/media'), 'Instagram media endpoint.'); + $data = ['data' => $mode === 'empty' ? [] : $media]; + } + } elseif ($host === 'graph.facebook.com') { + hgsf_test($args['headers']['Authorization'] === 'Bearer fb-fixture-token' && !isset($query['access_token']), 'Facebook token must stay out of the URL.'); + if (str_ends_with($path, '/me')) { + $data = ['id' => '12345', 'is_published' => $mode !== 'private_fb']; + } else { + hgsf_test(str_ends_with($path, '/12345/published_posts'), 'Facebook published-posts endpoint.'); + $photo = ['permalink_url' => 'https://www.facebook.com/example.page/posts/pfbid123/?tracking=test', 'message' => 'Foto van Facebook', 'full_picture' => 'https://scontent-test.fbcdn.net/image.jpg', 'created_time' => '2026-01-04T10:00:00Z']; + $text = ['permalink_url' => 'https://m.facebook.com/story.php?story_fbid=888&id=12345&tracking=test', 'message' => 'Bericht zonder foto', 'created_time' => '2026-01-02T10:00:00Z']; + $hidden = ['permalink_url' => 'https://www.facebook.com/example.page/posts/444', 'is_hidden' => true]; + $outside = ['permalink_url' => 'https://www.facebook.com/l.php?u=https://example.org']; + $data = ['data' => [$text, $photo, $hidden, $outside]]; + } + } else { + hgsf_test($args['headers']['Authorization'] === 'Bearer x%2Ffixture' && !isset($query['access_token']), 'X token must stay out of the URL.'); + if ($mode === 'credits') { + return ['response' => ['code' => 402], 'body' => '{"detail":"private diagnostics"}']; + } + if ($path === '/2/users/by/username/fixture_x') { + $data = ['data' => ['id' => '999', 'username' => 'fixture_x', 'protected' => $mode === 'private_x']]; + } else { + hgsf_test($path === '/2/users/999/tweets' && $query['max_results'] === '5' && $query['exclude'] === 'replies,retweets', 'Bounded X timeline request.'); + $data = ['data' => [ + ['id' => '991', 'created_at' => '2026-01-03T10:00:00Z'], + ['id' => '990', 'created_at' => '2026-01-03T09:00:00Z', 'withheld' => ['country_codes' => ['NL']]], + ]]; + } + } + return ['response' => ['code' => 200], 'body' => wp_json_encode($data)]; +}; +add_filter('pre_http_request', $mock_http, 10, 3); + +hgsf_test(is_wp_error(hgsf_sync_source('x')) && !$requests, 'No X API use without opt-in, even with a token.'); +hgsf_test(hgsf_sync_instagram() === true && count($requests) === 3, 'Legacy Instagram configuration and token renewal.'); +hgsf_test(count($snapshots['instagram']['posts']) === 10 && str_ends_with($snapshots['instagram']['posts'][0]['image'], '/video.jpg'), 'Instagram host checks, order and video thumbnail.'); +hgsf_test(hgsf_sync_instagram() === true && count($requests) === 5, 'No repeated token renewal.'); +hgsf_test(hgsf_sync_source('facebook') === true && count($snapshots['facebook']['posts']) === 2, 'Facebook excludes hidden posts and non-post links.'); +$connections['x']['enabled'] = true; +hgsf_test(hgsf_sync_source('x') === true && count($snapshots['x']['posts']) === 1, 'X retrieves recent public posts.'); + +wp_set_current_user(0); +$request_count = count($requests); +$icons = do_shortcode('[hg_sociallinks]'); +hgsf_test(!wp_script_is('hg-socialfeed-x', 'enqueued'), 'Icon bar does not load the X embed script.'); +$html = do_shortcode('[hg_socialfeed limit="4"]'); +$ig_only = do_shortcode('[hg_socialfeed sources="instagram"]'); +hgsf_test(wp_script_is('hg-socialfeed-x', 'enqueued'), 'The mixed feed loads the official X embed script.'); +hgsf_test(count($requests) === $request_count, 'Shortcodes must never call a provider API.'); +hgsf_test(substr_count($html, 'tabindex="-1"') === 13 && str_contains($html, 'Meer berichten'), 'All three feeds and load more.'); +hgsf_test(strpos($html, 'pfbid123') < strpos($html, '/status/991') && strpos($html, '/status/991') < strpos($html, 'story_fbid=888'), 'Combined order uses publication dates.'); +hgsf_test(!str_contains($html, 'tracking=') && !str_contains($html, 'igsh=') && str_contains($html, '"bericht"'), 'Strip tracking and escape captions.'); +hgsf_test(str_contains($html, 'Bericht zonder foto') && str_contains($html, 'data-dnt="true"'), 'Facebook text and official X embed.'); +hgsf_test(!str_contains($ig_only, 'facebook.com') && !str_contains($ig_only, 'x.com'), 'Feed source selection.'); +hgsf_test(substr_count($icons, 'get_error_code() === 'private' && !hgsf_cached_posts(hgsf_connection('facebook'), 'facebook'), 'Unpublished Facebook page clears cached posts.'); +$mode = 'private_x'; +hgsf_test(hgsf_sync_source('x')->get_error_code() === 'private' && !hgsf_cached_posts(hgsf_connection('x'), 'x'), 'Protected X account clears cached posts.'); +$mode = 'credits'; +hgsf_test(hgsf_sync_source('x')->get_error_code() === 'credits', 'Clear X credits error.'); +$mode = 'wrong_ig'; +hgsf_test(hgsf_sync_instagram()->get_error_code() === 'account' && !hgsf_cached_posts(hgsf_connection()), 'Wrong Instagram account clears cached posts.'); +$mode = 'empty'; +hgsf_test(hgsf_sync_instagram() === true && !hgsf_cached_posts(hgsf_connection()), 'Successful empty result remains empty.'); +$mode = 'normal'; +hgsf_test(hgsf_sync_instagram() === true, 'Restore Instagram fixtures for expiration check.'); +$snapshots['instagram']['synced_at'] = time() - HGSF_CACHE_LIFETIME; +hgsf_test(!str_contains(do_shortcode('[hg_socialfeed sources="instagram"]'), 'hgsf-grid'), 'Expired cache falls back to the profile link.'); +$connections['x'] = ['username' => 'fixture_x']; +hgsf_test(str_contains(do_shortcode('[hg_sociallinks sources="x"]'), 'x.com/fixture_x'), 'Icons work with only a profile and no access token.'); + +$die_handler = static fn () => static function ($message, $title, array $args = []) { + throw new RuntimeException((string) ($args['response'] ?? 0)); +}; +add_filter('wp_die_handler', $die_handler); +try { + hgsf_handle_settings(); + hgsf_test(false, 'Anonymous settings request must be rejected.'); +} catch (RuntimeException $error) { + hgsf_test($error->getMessage() === '403', 'Anonymous settings response code.'); +} +$admins = get_users(['role' => 'administrator', 'number' => 1, 'fields' => 'ID']); +hgsf_test(!empty($admins), 'An administrator is required for the nonce test.'); +wp_set_current_user($admins[0]); +require_once ABSPATH . 'wp-admin/includes/template.php'; +ob_start(); +hgsf_admin_page(); +$admin_html = ob_get_clean(); +hgsf_test(substr_count($admin_html, 'type="password"') === 3 && !str_contains($admin_html, '-fixture-token'), 'Admin renders three source settings without revealing tokens.'); +$request_count = count($requests); +hgsf_test(hgsf_save_settings('facebook', ['operation' => 'save', 'username' => '12345', 'profile' => 'updated.page']) === 'saved', 'Updating the Facebook profile link succeeds.'); +hgsf_test($connections['facebook']['token'] === 'fb-fixture-token' && count($requests) === $request_count, 'Updating an icon link preserves the Page token without fetching posts.'); +hgsf_test(str_contains(do_shortcode('[hg_sociallinks sources="facebook"]'), 'facebook.com/updated.page'), 'Updated profile link is reflected in the icon bar.'); +try { + $_POST['source'] = 'facebook'; + $_REQUEST['hgsf_nonce_facebook'] = wp_create_nonce('hgsf_settings_x'); + hgsf_handle_settings(); + hgsf_test(false, 'A different source nonce must be rejected.'); +} catch (RuntimeException $error) { + hgsf_test($error->getMessage() === '403', 'Cross-source nonce response code.'); +} +remove_filter('wp_die_handler', $die_handler); +remove_filter('pre_http_request', $mock_http); + +if (getenv('HGSF_FIXTURE_HTML') === '1') { + fwrite(STDOUT, $html . $icons); +} else { + WP_CLI::success('HG Social Feed integration checks passed.'); +}