526 Commits

Author SHA1 Message Date
539104ec33 [PLUGIN][Pinboard] Refactor and cleanup code 2022-04-01 00:17:57 +01:00
74ffd261b8 [PLUGIN][Pinboard] Implement tag handling 2022-04-01 00:16:04 +01:00
ca9945a4be [ENTITY][Actor][COMPONENT][Tag] Add Actor->getNoteTags(?string $note_type) which gets a cached list of NoteTags for notes of type $note_type for the actor 2022-04-01 00:11:01 +01:00
08587b6942 [COMPONENT][Link][Tag] Refactor to make it easier to create links or tags from other places 2022-04-01 00:09:25 +01:00
1664293cf7 [PLUGIN][Pinboard] Change token to user user ID rather than nickname, to avoid complications with it possibly changing 2022-03-31 22:06:37 +01:00
94ab4ce8c4 [PLUGIN][Pinboard] Invalidate token and it's cache when actor information is changed via ActorForms 2022-03-31 03:47:14 +01:00
dd70de20da [PLUGIN][Pinboard] Implement token authentication and settings page, allowing the user to enable, disable, refresh or consult their token 2022-03-31 03:29:31 +01:00
ded9c86054 [CORE][DB] Add DB::refetch, which refetches an entity from the database, so it's managed and definitely up to date (use when wanting to update entities from cache) 2022-03-31 03:29:31 +01:00
20e07c9140 [CORE][DB] Make DB::dql return an object rather than an array if limit 1 is specified 2022-03-31 03:29:31 +01:00
4e2f6545ec [COMPONENT][Person][PLUGIN][WebHooks] Rename person settings section from 'others' to 'api' 2022-03-31 03:29:31 +01:00
f6a8f44420 [COMPONENT][Person][TEMPLATES] Move persosn settings template from core to the component 2022-03-31 03:29:31 +01:00
fd71d6ee7d [PLUGIN][UnboundGroup] Finish implementation 2022-03-29 00:57:41 +01:00
dfc5918c2c [PLUGIN][ActivityPub] Federate out Service information in Activities 2022-03-28 23:54:19 +01:00
83599ef866 [CORE][Modules][Plugin] version should be static 2022-03-28 23:54:18 +01:00
fa82306f6f [COMPONENT][Posting] Blog posts should be Articles by default 2022-03-28 23:54:18 +01:00
10f71e9fed [UI][TEMPLATES] Fix note text template. Use rendered content directly 2022-03-28 23:23:07 +01:00
e2501ee927 [PLUGIN][Pinboard] Implement remaining API endpoints, restructure, fix template 2022-03-28 23:23:07 +01:00
a9665177ea [PLUGIN][Blog] Move to plugins, mistakenly was in components 2022-03-28 20:59:16 +01:00
41861d284c [COMPONENT][Circle] Correct self tags settings text 2022-03-28 20:59:16 +01:00
bd868a2675 [PLUGINS][Pinboard] Add initial implementation of Pinboard API, lacking authentication, tags and feed endpoints 2022-03-28 20:59:16 +01:00
87e35716c1 [UTIL] Add Formatting::explode(array , string ) 2022-03-28 20:59:16 +01:00
dac94f53cd [CORE][Entity] Rename createOrUpdate to 'checkExistingAndCreateOrUpdate', remove update feature from 'create' and add 'createOrUpdate' and fix users 2022-03-28 20:59:15 +01:00
b10c359dec [DEPENDENCIES] Update dependencies 2022-03-28 20:59:15 +01:00
483983790a [CORE][Router] Rename \App\Core\Router\Router to \App\Core\Router and merge \App\Core\Router\RouteLoader with \App\Core\Router 2022-03-28 20:59:15 +01:00
60af9f5e9b [CORE][Queue] Rename App\Core\Queue\Queue to App\Core\Queue 2022-03-28 20:59:15 +01:00
abe35428da [CORE][DB] Rename App\Core\DB\DB to App\Core\DB 2022-03-28 20:59:14 +01:00
ca5520edbf [PLUGIN][WebHooks] Add hook for subscriptions 2022-03-28 20:59:14 +01:00
e3e14c53ef [PLUGIN][ActivityPub] Model/Note->toJson federate the url, even though it's the same as the id 2022-03-28 20:59:14 +01:00
be33c20614 [PLUGIN][ActivityPub] Improve flexibility of Type layer, accomodate more elaborate understanding of Group Announces after FEP-2100 development 2022-03-28 20:58:48 +01:00
7305a725cb [PLUGIN][UnboundGroup] First steps on implementing AP FEP-2100 2022-03-28 20:57:43 +01:00
fd4c3b0e68 [PLUGIN][Embed][Test] Move Test to correct location 2022-03-28 20:53:50 +01:00
16f51e5143 [COMPONENT][Notification] ->getSubscribers() should not be pre-included
Notification bug fix on Subscription component
Correct docblock
2022-03-28 20:53:19 +01:00
ba4230447e [COMPONENT][Group] Add orderBy to query, as otherwise the feed order is wrong 2022-03-28 20:49:28 +01:00
7463044971 [COMPONENT][Circle] Ensure strict typing on getter 2022-03-28 20:48:29 +01:00
7027633ed5 [PLUGIN][WebHooks] Make request method configurable
This way, PUT can be used, which doesn't seem to be the standard, so isn't the default, but which makes sense to me, as it doesn't have a response, which we don't care about anyway
2022-03-24 00:51:00 +00:00
48b42c539c [PLUGINS][WebHooks] Use ActivityPub to serialize the activity, so the object is included 2022-03-24 00:51:00 +00:00
d41a67a9f9 [PLUGIN][WebHooks] Add WebHooks plugin, which allows for sending a POST request to an external resource when a notification or a follow occurs 2022-03-24 00:51:00 +00:00
13f22c911c [COMPONENT][Notification] Feed: Fix typo in query 2022-03-23 16:09:13 +00:00
56b8710b26 [PLUGIN][ActivityPub][Notification] Fix some issues with targetting 2022-03-23 13:23:44 +00:00
e63c310d70 [COMPONENT][Notification] Always pre-add Actor subscribers when notifying 2022-03-23 13:23:44 +00:00
03f449035a [PLUGIN][ActivityPub][Model][Activity] Sometimes we don't have a local, move on with encapsulated 2022-03-23 13:23:44 +00:00
8808195a80 [PLUGIN][ActivityPub][Test] Test @language handling 2022-03-23 13:23:44 +00:00
45344c80d1 [PLUGIN][ActivityPub][Model][Note] Fix @language handling 2022-03-23 13:23:43 +00:00
7eddbd343d [PLUGIN][ActivityPub][Test] Add Like{Note} fixture 2022-03-23 13:23:43 +00:00
259d2da05a [CORE][Controller] Add default handler for when using http methods 2022-03-23 13:23:43 +00:00
2f7fdf6ee4 [PLUGIN][ActivityPub][Test] Activity: Create Page
Fixed a couple of bugs
2022-03-19 22:21:35 +00:00
6955872e05 [PLUGIN][ActivityPub][Model][Activity] toJson: When in activity context, use object's context if available 2022-03-19 22:20:32 +00:00
23e88b30a6 [COMPONENT][Blog] This is not used for replies 2022-03-19 22:18:33 +00:00
60713878f0 [TESTS] Load languages prior to remaining fixtures 2022-03-19 22:18:00 +00:00
06c67b31c2 [PLUGIN][ActivityPub][Model][Note] toJson: Respect source attribute and @language from context 2022-03-19 18:01:25 +00:00
a08b661779 [COMPONENT][Group] Cast integer string to int when getting group from context 2022-03-19 18:01:25 +00:00
0649a5154c [PLUGIN][ActivityPub][Test][Model][Note] fromJson 2022-03-19 18:01:24 +00:00
91fecd77ba [TOOLS][DOCKER] Use a more robust way to check for database availability 2022-03-19 17:20:12 +00:00
e22fe55bbe [TOOLS] Add .well-known/acme-challenge/ root certbot to nginx container, to allow certbot certificate renewals 2022-03-19 07:32:01 +00:00
dd62825169 [PLUGIN][ActivityPub][Model][Note] fromJson: Respect source attribute and @language from context 2022-03-15 17:49:09 +00:00
27706d63f4 [PLUGIN][OAuth] Fix login for OAuth 2022-03-14 21:41:22 +00:00
20f690c532 [TESTS] Fix a couple of issues from last changes 2022-03-14 18:37:39 +00:00
888c3798b7 [COMPONENT][Notification] Make logic more generic and robust
Fixed various bugs

Some important concepts to bear in mind:

* Notification: Associated with activities, won't be reconstructed
together with objects, can be thought of as transient

* Attention: Associated with objects, will be reconstructed with them, can
be thought as persistent

* Notifications and Attentions have no direct implications.

* Mentions are a specific form of attentions in notes, leads to the creation of Attentions.

Finally,

Potential PHP issue detected and reported: https://github.com/php/php-src/issues/8199
`static::method()` from a non static context (such as a class method) calls `__call`, rather than
the expected `__callStatic`. Can be fixed by using `(static fn() => static::method())()`, but the
usage of the magic method is strictly unnecessary in this case.
2022-03-14 11:37:09 +00:00
e1cceac150 [CORE][Form][TESTS] Fix FormTest::handle 2022-03-13 18:53:53 +00:00
63ef9292f3 [DEPENDENCIES] Update dependencies 2022-03-13 18:17:32 +00:00
cbae649991 [PLUGIN][ActivityPub][TESTS] Move ActivityPub test fixtures to new facility 2022-03-13 18:11:11 +00:00
1d8bba3949 [TESTS][MODULES] Move Test Fixtures to tests/fixtures folder and add support for loading fixtures from components and plugins 2022-03-13 18:00:21 +00:00
18864ca9fa [CONTROLLER][Security] Override the _next form field in Security->register to redirect to login page 2022-03-13 16:01:51 +00:00
390c532456 [PLUGIN][ActivityPub][Tests] Create Actor Tests 2022-03-13 16:00:35 +00:00
636cb681d6 [PLUGIN][ActivityPub][Tests] Create a TestCase for the plugin 2022-03-13 15:54:14 +00:00
7d84323df4 [PLUGIN][ActivityPub][Tests] Add some fixtures for GNU social's 2022-03-13 15:53:21 +00:00
2d7850ccfb [PLUGIN][ActivityPub][Tests] Borrow test fixtures from Lemmy 2022-03-13 15:52:48 +00:00
d8108dbc32 [COMPONENT][Posting] Fix request handling issues that resulted from splitting creation and controller 2022-03-13 15:52:48 +00:00
cf05d3dbb0 [ENTITY][TESTS] Fix Note->isVisibleTo with and associated test 2022-03-13 15:03:03 +00:00
eb3c848fc8 [TOOLS][TESTS] Ensure database schema is up to date in tests 2022-03-13 14:22:18 +00:00
5c708af272 [CORE][Form] Remove unweildy return of form errors from Form::handle 2022-03-13 14:19:56 +00:00
8433771465 [TOOLING][TESTS] Allow specifying any phpunit flag when invoking make
Examples:
  make test -- --filter 'method'
  make test -- directory
2022-03-10 01:23:36 +00:00
0ce5eba355 [PLUGINS][Favourite][RepeatNote][DeleteNote][WebMonetization] Make use of 'activitypub_handler' more readable 2022-03-10 00:40:54 +00:00
9a9eed1457 [CORE][Router][Form] Add Router::sanitizeLocalURL and use it in Form::forceRedirect 2022-03-09 20:51:42 +00:00
f540711948 [CORE][GNUsocial] Remove Session parameter, as it's no longer a service. Use session from Request 2022-03-09 20:51:42 +00:00
c870fd44e3 [PLUGIN][Embed] Fix test folder name, so Symfony doesn't attempt to autowire it 2022-03-09 20:51:42 +00:00
c30fcead74 [DEPENDENCIES] Move from Symfony 5.4 to 6 and update all other packages, where applicable 2022-03-09 20:51:42 +00:00
301421ea15 [SECURITY][EVENT] Remove deprecated uses of Symfony Guard. Add LoginSucess and LoginFailure events 2022-03-09 20:51:16 +00:00
4d77f3497d [COMPONENT][Person][TESTS] Fix Controller/PersonSettingsTest 2022-03-09 14:24:50 +00:00
f735e6b31c [TESTS] Fix Util/CommonTest 2022-03-09 14:24:50 +00:00
893d299e29 [UTIL][Common] Respect detect language setting
Minor bug fix
2022-03-09 14:24:50 +00:00
d857baa0f1 [TESTS] Fix Twig/ExtensionTest 2022-03-09 01:43:58 +00:00
0441f030ab [COMPONENT][Group][TESTS] Fix Entity/GroupTest 2022-03-09 01:43:51 +00:00
cac68a6372 [TESTS] Fix Entity/NoteTest 2022-03-09 01:42:11 +00:00
28453c585f [COMPONENT][Attachment][TESTS] Fix Entity/AttachmentThumbnailTest 2022-03-09 01:42:11 +00:00
5c7b079df5 [COMPONENT][Attachment][Controller] Security fix: We were not ensuring that attachment was related to note 2022-03-09 01:42:11 +00:00
47f03d4c9f [COMPONENT][Attachment][TESTS] Fix Entity/AttachmentTest 2022-03-09 01:42:06 +00:00
cc4f967186 [TESTS] Fix Circle SelfTags Setting test 2022-03-09 01:40:35 +00:00
ff06a2656a [COMPONENT][Group][Entity] Useless URI column removed
Add table to Makefile backup
2022-03-09 01:40:34 +00:00
d5fd7da707 [TESTS] Fix Core/RouterTest 2022-03-09 01:40:34 +00:00
1bdeac7076 [TESTS] Fix Core/DB/UpdateListenerTest 2022-03-09 01:40:34 +00:00
e67ed58286 [TESTS] Temporarily Disable Controller/AdminTest: It seems we are repeating values arbitrarily - specially in plugins, and the generated file is just nonsense overall really, wrong sections and stuff 2022-03-09 01:40:34 +00:00
487791d606 [TESTS] Fix Core/ControllerTest 2022-03-09 01:40:33 +00:00
813e66e83e [TESTS] Fix Core/CacheTest 2022-03-09 01:40:33 +00:00
88ace68627 [TESTS] Fix Controller/FeedsTest 2022-03-09 01:40:33 +00:00
416665d830 [COMPONENT][Attachment][TESTS] Fix Controller/AttachmentTest 2022-03-09 01:40:09 +00:00
808a3b219e [TESTS] Specify non-null fields for use of creating actors in tests 2022-03-09 01:37:11 +00:00
df40dd7c66 [TESTS] Add support for loading test suites from plugins and components 2022-03-09 01:37:11 +00:00
afa8443949 [TESTS] Fix some failing tests broken by restructuring and dependency updates 2022-03-09 01:37:11 +00:00
46de2d47e9 [TOOLS] Add explicit return types to fix deprecation warnings raised by PHPUnit 2022-03-09 01:37:10 +00:00
372cf91fbc [TOOLS][TESTS] Split tests into different test suites 2022-03-09 01:37:10 +00:00
9c9e86649a [TESTS] Fix Controller/SecurityTest 2022-03-09 01:37:10 +00:00
a37ce86d05 [TESTS] Fix DataFixtures 2022-03-07 15:26:27 +00:00
9a0c74cb0c [CORE][SECURITY] Replicate 'next' form submission feature on login form 2022-03-07 15:26:27 +00:00
46c91a4b39 [I18N] Fix use of string concatenations in translations 2022-03-07 15:26:26 +00:00
3f14ad0f69 [COMPONENT][Posting][FORM] Refactor Posting form to use a form action with a separate controller and the new Form::forceRedirect 2022-03-07 15:26:26 +00:00
6ddc176faf [CORE][Form] Add facilities for automattically adding a _next field to all forms, which can be customized by the in Form::create and defaults to the current URL. Usage of RedirectedException should mostly be replaced with Form::forceRedirect 2022-03-07 15:26:26 +00:00
d629976322 [UTIL][Notification] Remove deprecated code 2022-03-07 15:26:24 +00:00
1a0c9e720f [COMPONENT][FreeNetwork] Start using queues
[COMPONENT][Notification] Start using queues
[PLUGIN][ActivityPub] Start using queues
2022-03-05 14:23:08 +00:00
6fa5ec3218 [CORE][Queue] Fix some minor issues 2022-03-05 14:22:44 +00:00
626b4263f1 [PLUGIN][ActivityPub][Model][Actor] Fix internal logic for updating
Actors
2022-03-05 14:19:12 +00:00
1daa314c55 [COMPONENT][Posting][FORM] Refactor Posting form to use a form action with a separate controller and the new Form::forceRedirect 2022-03-04 15:16:19 +00:00
7814697f82 [UTIL][EXCEPTION] Forward given status code in RedirectException 2022-03-04 15:15:04 +00:00
7a8d67f1e2 [CORE][Controller] Fix bug where a JSON request could not recieve a redirect response 2022-03-04 15:14:05 +00:00
94449c9153 [CORE][Form] Add facilities for automattically adding a _next field to all forms, which can be customized by the in Form::create and defaults to the current URL. Usage of RedirectedException should mostly be replaced with Form::forceRedirect 2022-03-04 15:12:35 +00:00
7c9b01c516 [UTIL][Common] Add Common::getRequest 2022-03-04 15:09:39 +00:00
6cae6c925d [TOOLS] Keep feed table in delete content Make rule 2022-03-01 18:12:58 +00:00
12fb876a6d [PLUGIN][ActivityPub][Model][Activity] No @context to exclude when object is not embedded. 2022-03-01 18:00:24 +00:00
7ca4330f17 [TEMPLATES] Tweak note complimentary info to not output empty <span>s 2022-03-01 17:58:53 +00:00
802a8d124a [TOOLS] For delete content, restore local_groups and actor_subscriptions 2022-03-01 17:57:39 +00:00
87354c06bf [TEMPLATES] For note complementary info, compare identity by the ID, rather than nickname, which is not unique 2022-03-01 17:39:14 +00:00
5600218924 [TWIG][I18N] Remove unnecessary wrappers for translation functions, use them directly 2022-03-01 17:25:51 +00:00
90f9378bca [TEMPLATES] Use transList and trans function for note complimentary info 2022-03-01 13:46:06 +00:00
070f53c10e [TWIG][I18N] Add transList function, which uses _m_list 2022-03-01 13:46:01 +00:00
f73e9c12ba [CORE][I18n] Add I18n::_m_list, which formats an array of elements into a list. Limited to 5 elements, as that should be enough (tm) and ICU doesn't support this natively 2022-03-01 13:45:40 +00:00
fc203e2e38 [TWIG][TEMPLATES] Rename transchoice to trans and make it more generic 2022-03-01 13:45:11 +00:00
b3374333f3 [TEMPLATES][I18N] Fixup use of trans filter, in favour of trans tags. These are much more flexible and facilitate parameterized translations, rather than using concats. The only appropriate use of the trans filter is when a whole string in a variable needs to be translated (which should probably be avoided anyway) 2022-03-01 13:16:11 +00:00
0b864e85fd [TEMPLATES] Fixup uses of deprecated noteView, in favour of new NoteFactory facility 2022-03-01 11:23:39 +00:00
a9a60bbd92 [COMPONENT][Posting] Clarify use of cache in note replies when posting 2022-03-01 11:19:47 +00:00
4cc4d06b11 [CORE][Cache] Fix bug where empty lists must be stored as a string in Redis (not supported natively), so we can't directly push to it, but the key still exists 2022-03-01 11:07:21 +00:00
f8c1b0f71d [TOOLS] Add Make rule to delete content, but keep actors and sequences 2022-02-28 23:37:16 +00:00
43ae3add43 [TEMPLATE] Update uses of NoteFactory macro, to pass the values seperately, rather than inside a converstation key 2022-02-28 15:48:47 +00:00
d5f90a1206 [ENTITY][Note][CONFIG] Use getListPartialCache for getReplies. Add feeds/cached_replies config entry to control how many replies get cached 2022-02-28 15:47:38 +00:00
85ce6bfd41 [CORE][Cache] Add getListPartialCache, which allows for fetching a list and backing only a portion of it in the cache (useful for feeds and replies to notes, for instance) 2022-02-28 15:47:38 +00:00
46c4bd9099 [COMPONENT][Conversation] Sort conversation correctly 2022-02-28 15:47:38 +00:00
35f3781a32 [COMPONENT][Collection] Add mechanism for specifying the ordering of note and actor queries 2022-02-28 15:47:38 +00:00
45c7888676 [TOOLS] Run CS-Fixer on whole project 2022-02-28 15:47:37 +00:00
255c44bbf0 [ENTITY][LocalUser] Don't use FILTER_SANITIZE_EMAIL, use just want to validate. Up to the user to fix any errors. Use setter, rather than duplicate it's code 2022-02-28 15:47:37 +00:00
5188a473d0 [TOOLS] Fix errors reported by PHPStan 2022-02-28 15:47:37 +00:00
8c15d21591 [TOOLS] Add update-dependencies and update-autocode Make rules 2022-02-28 15:47:37 +00:00
df640f60d2 [DEPENDENCIES] Update dependencies 2022-02-28 15:47:37 +00:00
6e85a4adbb [CONFIG] Change default config to make media files (attachments and their thumbnails) to a subfolder to file, so cleanup scripts can avoid files meant to be persistent (plugin files, certificates) 2022-02-28 15:47:37 +00:00
eccf21edef [TOOLS][PLUGINS][OAuth2] Add mechanism to allow plugins to have an install script. Add script for generating keys for OAuth 2022-02-28 15:47:32 +00:00
9b86794cda [CSS] Details inside another details (accordion widget) will represent their 'open/close feedback arrows' properly now 2022-02-28 13:09:12 +00:00
077975136e [CARDS][Note] Both 'in conversation' and 'in reply to' link to note's conversation. The former anchors it's id, while the latter it's parent id 2022-02-28 12:43:40 +00:00
5495a3c5ec [ENTITY][Note] NoteType now becomes a varchar as predicted 2022-02-27 02:04:48 +00:00
a9b34b75b6 [PLUGIN][TreeNotes] Correct cache issues and iterate functionality
- Replies ordering now correct
- Replies count added
- Posting adds new replies to cache (when concerning replies cache is not empty) and increments replies count
- Configuration to specify number of in-tree replies shown added
- TreeNotes templates was moved from core to plugin
- Button to read more replies was added
2022-02-27 01:46:25 +00:00
2f539d176d [TWIG] Implement transchoice for ICU plural translations 2022-02-27 00:44:23 +00:00
d4c908c194 [CORE][Cache] Implement listPushRight 2022-02-27 00:44:23 +00:00
b630d530f4 [PLUGIN][ActivityPub][Postman] JSON_UNESCAPED_SLASHES
Only record webfinger matches for acct
2022-02-25 13:52:56 +00:00
26a50618b0 [CARDS][Note] Notification targets are now used as target info, instead of previous reply dependant implementation [COMPONENTS][Group] Feed title is applied to GroupFeed view 2022-02-25 13:12:16 +00:00
d5731e6351 [COMPONENT][Notification] Consider attention properly in notes 2022-02-25 13:12:16 +00:00
f5e92de62d [PLUGIN][ActivityPub][Util][Explorer] Simplify fetching Actor by URI 2022-02-25 13:12:14 +00:00
7c80277436 [CSS] Fix header position on >1080p displays 2022-02-24 19:16:41 +00:00
4754593cde [PLUGIN][ActivityPub][Model][Activity] If the object is wrapped in an activity, exclude the @context 2022-02-24 19:07:46 +00:00
d12038a9f8 [CSS] Complete refactor, removing all useless rules, squashing related separate files, and limiting folder depth 2022-02-24 19:05:14 +00:00
af02bc7b32 [PLUGIN][ActivityPub][Model][Note] Replace our directMessage extension with LitePub's 2022-02-23 22:27:32 +00:00
bc3d5245f5 [PLUGIN][ActivityPub][Model][Note] Handle Mentions properly 2022-02-23 22:27:32 +00:00
f3c2e49e3f [PLUGIN][ActivityPub] Correct @context 2022-02-23 22:27:30 +00:00
05b7f2c28b [CORE][DB] Remove doc from deprecated DB::merge and add about DB::refresh 2022-02-23 17:42:20 +00:00
338ea0ea58 [COMPONENTS][Group] Group view template now extends the Collection of Notes view instead of trying to reinvent the wheel [COMPONENTS][Conversation] Replaced deprecated DB::merge with DB::persist 2022-02-23 17:01:41 +00:00
57a07ef74f [COMPONENT][FreeNetwork] Add to Search the query expression 2022-02-21 04:53:12 +00:00
c380cbd846 [COMPONENT][FreeNetwork] Mention and Group tags in notes are handled differently 2022-02-21 04:52:30 +00:00
7678e155d9 [COMPONENT][Search] Ensure title is set when saving as feed 2022-02-21 04:49:08 +00:00
59380ed2ac [COMPONENT][Collection] If invalid term, just perform a regular search for it 2022-02-21 04:48:18 +00:00
1e310aa124 [PLUGIN][ActivityPub][FreeNetwork] DB::findBy won't work if not commited first 2022-02-20 15:01:49 +00:00
José Marques
8b0e9c7890 [UTIL][Form][ActorForms] Fix Full Name validate: Tried to mb_strln on null
If the trim(string) is empty, then store null without further ado
2022-02-20 05:03:55 +00:00
f1caabd296 [CARDS][Note] Note factory template macro created, allows Notes to be represented with completely different macros/blocks, possible to extend types through additional events. Compact Notes have a max height, content can be scrolled by [CSS] Avatars, and Embed attachments now have a max-block-size which acts independently of image orientation 2022-02-20 05:03:54 +00:00
a71c16d654 [COMPONENTS][Posting] Fixed issue where an embed attachment would violate Note's conversation_id not null constraint
Conversation was only assigned after storing Note's attachments
2022-02-20 05:03:41 +00:00
ecfd6b5ad2 [PLUGIN][ActivityPub][Model][Note] Sometimes content is explicitely null 2022-02-20 05:03:40 +00:00
496701ce73 [PLUGIN][ActivityPub][Inbox] Add event for notifications triggered by AP Inbox 2022-02-20 05:03:40 +00:00
e86dbad6d6 [COMPONENT][Notification] Don't explode with understandable duplicate notifications
This is common when a duplicate federation request is received
2022-02-20 05:03:40 +00:00
6f3e760c63 [PLUGIN][ActivityPub][Inbox] Separate handler by method 2022-02-20 05:03:40 +00:00
51cccd0155 [PLUGIN][ActivityPub] Simplify DB usage 2022-02-20 05:03:40 +00:00
9523927b8e [PLUGIN][ActivityPub][Model][Note] There may be no attachments, nor tags, nor to, nor cc 2022-02-19 05:46:48 +00:00
ebbd8bf1e4 [PLUGIN][ActivityPub][HTTPSignatures] Fix wrong assumption that sha512 is used in hs2019 2022-02-19 04:49:50 +00:00
7a59d5a002 [PLUGIN][ActivityPub][HTTPSignatures] Validate draft-cavage-http-signatures-11 2022-02-19 04:49:50 +00:00
52ae5fa690 [PLUGIN][ActivityPub][Inbox] Improve logs 2022-02-19 04:49:50 +00:00
99f7e7cd79 [PLUGIN][ActivityPub][Model][Note] Handle group scope properly 2022-02-19 04:49:50 +00:00
27635d8ec2 [PLUGIN][ActivityPub][Model][Note] Add name property as note title 2022-02-19 04:49:49 +00:00
0a741903a1 [PLUGIN][ActivityPub][Model][Note] Federate content out 2022-02-19 04:49:49 +00:00
8f60fc4685 [PLUGIN][ActivityPub][Model][Note] Federate attentions out 2022-02-19 04:49:49 +00:00
8cf60275e6 [PLUGIN][ActivityPub][Model][Note] Add support to Pages 2022-02-19 04:49:49 +00:00
75837af412 [CSS] Replacing problematic special Unicode glyphs
A browser will use Unicode glyphs from other font families if the glyph in question is not present for the current typeface. This leads to unnerving situations, whereby setting content through pseudo-selectors will cause text to misalign. And no, line-height won't make a difference in this case. This happens because fonts have different heights. Another reason may reside on CSS3 having pseudo selectors but not really having a proper spec for them to begin with.
2022-02-19 04:01:47 +00:00
03a475b642 [TWIG] Form layout is all new, since extending form_div_layout.html.twig was quite limiting
[COMPONENTS][Posting] It is now visible on Actor profiles [COMPONENTS][Search] Overall rework of search results template, there's also additional help text added [CSS] Header no longer translucent, font sizes yet more consistent, replies marker less pronounced, and font hierarchy is now applied in both weight and size
2022-02-19 04:01:47 +00:00
b69f4a46c5 [COMPONENT][Posting] Page should flush with a different notification 2022-02-16 19:35:27 +00:00
b6ed0b4c6c [CORE][Actor] Fix generic profile route 2022-02-16 18:53:08 +00:00
cee2d143c9 [COMPONENT][Posting] Add storeLocalPage
Minor refactoring and bug fixing
2022-02-16 18:53:08 +00:00
2d5fac7a89 [COMPONENT][Notification] Re-introduce the concept of note attention
Minor refactoring and bug fixing
2022-02-16 18:53:08 +00:00
e70acd5c3b [UTIL][HTML] HTML abstraction class was extended with a more specialised Heading class
This little abstraction layer made it a bit easier to add a different title to a Note or Actor Feed Collection template, from whichever controller that uses it. Please, bear in mind, that abstract templates such as those found in Components\Collection, may act in a very 'declarative' way upon using them. This makes it difficult to dynamically choose what type of header is used without undergoing a mining operation in the likes of a pyramid of doom. Hence, this _little_ change.
2022-02-16 18:53:08 +00:00
f66e178dfc [CORE][Actor][Settings] Fix nickname change and refactor Core Form::handle so it's harder to repeat these mistakes again
Minor improvements on actor->getLocal
2022-02-16 18:53:07 +00:00
397b54a207 [PLUGIN][Bundles] Refactor BlogCollections to Bundles 2022-02-16 18:53:07 +00:00
33e1d3eb20 [COMPONENT][Conversation] Use Router::url's _fragment for anchor 2022-02-16 18:53:07 +00:00
54b9ec48b4 [COMPONENT][Collection][FeedController] Fix group scope, we should use the IN context actor to check the group 2022-02-16 18:53:07 +00:00
40590bbd11 [COMPONENT][Group] Restore settings functionality 2022-02-16 18:53:07 +00:00
5b94973079 [COMPONENTS][Posting] Form is no longer added to RightPanel if not on a feed|conversation|groups route 2022-02-16 18:53:07 +00:00
9d9abf8afb [CARDS][Note] Removed incorrect aria attributes, polished Note card 2022-02-16 18:53:06 +00:00
be0a2d27e2 [COMPONENT][Blog] Initial support for in group blogs 2022-02-16 18:53:06 +00:00
bf23ae2dcf [ENTITY][Note] Some notes aren't exactly just a note but rather a Page, or further (like happening or poll), this is only initial support for that
It prolly will become a varchar instead of an enum, so plugins can add their own note types
2022-02-16 18:53:06 +00:00
33e768c298 [COMPONENT][Group][Controller] Separate feed from other group features 2022-02-15 17:13:16 +00:00
3f9c86f0df [COMPONENT][Group] More flexible member roles than only isAdmin
Refactor terminology of canAdmin to match current roles system
2022-02-14 05:02:10 +00:00
bc63c3727a [COMPONENT][GROUP] Allow to create a group as private and prioritise group scope on Posting in that context 2022-02-14 05:02:09 +00:00
090a087832 [COMPONENT][Group] Check nickname on register 2022-02-14 01:21:40 +00:00
262b14a977 [COMPONENT][Collection] Organisation no longer is an actor type but rather a type of Actor Group 2022-02-14 00:41:57 +00:00
10d1a7ed2a [PLUGIN][ActivityPub] Implement Group Inbox POST 2022-02-13 23:15:00 +00:00
3ae8f8213f [GROUP] Notifity group subscribers of new activity concerning the group 2022-02-13 23:15:00 +00:00
66323c5a73 [PLUGIN][ActivityPub] Fix several issues with target and notifications inserted by AP 2022-02-13 23:14:59 +00:00
56c884026f [COMPONENT][Notification] We must record remote notifications because of feeds 2022-02-13 23:14:59 +00:00
62bf788b90 [CORE][Note] Implement private group scope properly 2022-02-13 23:14:59 +00:00
6500e99b69 [COMPONENT][Posting] Respect context actor concerning visibility and In sorting 2022-02-13 23:14:58 +00:00
cda1568db5 [TEMPLATES][Cards][Blocks] Provide both actor uri and url, as well as full mention guidance 2022-02-13 23:14:58 +00:00
1f2638d15a [ROUTES] Remove ActorCircle holdover route 2022-02-11 15:31:47 +00:00
6b4fa8c303 [COMPONENT][Notification] Additional check to avoid unnecessary notifications 2022-02-11 15:31:47 +00:00
17733f32d6 [PLUGIN][ActivityPub] Implement Group Outbox
Fix various minor issues
2022-02-11 10:06:01 +00:00
fb3e900b28 [CORE] Add CONFIG_ prefix to environment whitelist
Fixed minor issues with Commong:config of env not being included and ported to local social yaml

Fixed some regressions introduced with [CORE] Unset sensitive information from the environment
2022-02-11 10:05:58 +00:00
416451a519 [CORE][Actor] Simplify logic so more is reused between different types of actors
Minor bug fixes
2022-02-11 00:27:03 +00:00
1f1524c2b3 [GROUP] Simplify logic by making Actor::Organisation a type of Actor::Group
Some minor bug fixes
2022-02-11 00:26:43 +00:00
35e907f7b2 [CARDS][Note] Note's 'in reply to' information added, overall polish of feeds templates and proper titles added for every single section that makes up a note 2022-02-09 18:49:34 +00:00
79bb258ba6 [CSS] Further dialing of sizes and media queries for a better mobile UX 2022-02-08 17:14:28 +00:00
80dfea6812 [CARDS][Note] Note's actions are now inside the same div as Note's complementary info, overall footprint of replies diminished 2022-02-08 17:01:58 +00:00
f6b19d2a0f [CARDS][Note] Note's actions are now inside the same div as Note's complementary info, overall footprint of replies diminished 2022-02-08 16:13:46 +00:00
67a2387b31 [CARDS][Note] Removed note's complementary info related to the current user everywhere, which was criticized from being redundant 2022-02-08 15:19:33 +00:00
5d0b8930e1 [COMPONENTS][Conversation] Removed redundant complementary information from notes replied to 2022-02-08 14:43:39 +00:00
22741702bf [CSS] Replaced .section-details-subtitle summary, .section-details-title summary outline to a border, since Firefox ESR doesn't apply border-radius to outline 2022-02-08 14:22:52 +00:00
ba131bdb16 [CSS] Background noise is back, default_theme directory hierarchy simplified
[PLUGINS][Oomox] Fixed issue where resetting colours when no entity was present would lead to an error (it expected an entity, but NULL was given)
2022-02-08 14:12:59 +00:00
7b0667109d [CARDS][Note] Note actions are now displayed at the end
Due to space constraint on mobile screens, prior actions placement proved to be a problem. Additionally, note replies are now separated from their parent, allowing more horizontal space to be used if necessary/more reply depth to be presented in a reasonable fashion.
2022-02-08 01:26:25 +00:00
5cd3bc3206 [CSS] Touch devices are now able to scroll horizontally on note author information 2022-02-08 00:30:15 +00:00
79d022e850 [CSS] Fixing note attachments padding, height and allowing their wrap when limited space is available 2022-02-08 00:18:24 +00:00
cb393ca554 [CARDS][Note] Fix note replies from calling note macro as if it was still part of the same template 2022-02-08 00:05:51 +00:00
99593a19ef [CSS] Default theme polish work, more consistent font sizes and improved dark theme colors 2022-02-07 23:54:29 +00:00
9a53f94b77 [TWIG] Replaced getRightPanelBlocks with addRightPanelBlock, provides more control on block placement
[COMPONENTS][RightPanel] Refactored template, improved clarity, and added Posting form related macros

[PLUGINS][NoteTypeFeedFilter] Removed icons from template, added them through CSS to further improve performance
2022-02-07 20:29:14 +00:00
d6666cf209 [CSS] Aligned details marker arrows 2022-02-07 02:46:08 +00:00
b3d582f665 [PLUGINS][AttachmentCollections] Fixed "Error: Expected Doctrine\ORM\Query\Lexer::T_IDENTIFIER, got 'Plugin\AttachmentCollections\Entity\AttachmentCollection'"
[TWIG] Cards are now divided into blocks and macros, additional macros done, attachments page no longer inside cards directory
[CARDS][Navigation] Now using macros to create section, details, and nav elements
2022-02-07 01:54:04 +00:00
2b9f70f89f [PLUGINS][BlogCollections] Entities and base plugin and controller done 2022-02-07 01:52:35 +00:00
e0ceddc2e6 [CSS] Replaced fooobar:not([foo=bar], [foo2=bar2]) rule, as Firefox ESR 78.x doesn't support that specific syntax 2022-02-04 21:12:22 +00:00
81f6d496c6 [PLUGIN][OAuth2] Fix some static issues 2022-02-04 19:56:17 +00:00
4dd976eb22 [ENTITY][Note] Added function getRenderedSplit, return an array of paragraphs/line breaks
[PLUGINS][Favourite] Foreign keys now properly defined on schema

[CARDS][Note] Note text is now hidden by default if too many paragraphs/line breaks are present, BlogCollection plugin will certainly need this feature
2022-02-04 16:07:24 +00:00
Bruno Aleixo
fb76775716 [TOOLS][COMPONENTS][CORE] Ran cs-fixer on all files 2022-01-30 16:41:54 +00:00
Bruno Aleixo
162b01e2c5 [CORE] Unset sensitive information from the environment 2022-01-30 16:39:43 +00:00
afd1211852 [CSS] Using accent-color rule to stylize checkbox 2022-01-28 23:15:01 +00:00
8f8070036c [CSS] Eliminated repeated rules, improved icon alignment, and removed checkbox and radio custom styling
Browser specific quirks made it impossible to stylize checkbox and radio buttons. High DPI, custom default font sizes and/or custom GTK themes make it very difficult to keep it consistent.
2022-01-28 18:21:04 +00:00
2e6f91f34e [FORM][ActorForms] Fullname length is now validated prior to being set 2022-01-27 17:53:02 +00:00
5036b72a71 [ENTITY][Actor] Nickname is lower case transformed when generating 'actor_view_nickname', making sure that actor pages are linked accordingly 2022-01-27 17:19:50 +00:00
a17a514bfd [CONTROLLER][Security] Further sanity checks and validation done on email entry 2022-01-27 17:08:20 +00:00
1576d253a5 [CONTROLLER][UserPanel] Email is now sanitized and validated before calling corresponding setter 2022-01-27 16:59:43 +00:00
64a698d255 [COMPONENTS][Search] Polished search template for a clearer header hierarchy 2022-01-27 02:17:41 +00:00
ab6dabf4f7 [CSS] Fix issue where panels wouldn't scroll independantly 2022-01-27 01:53:30 +00:00
222e1fbb2b [PLUGINS][AttachmentShowRelated] Replacing h2 with span, its supposed to be complementary content, not main 2022-01-27 01:13:18 +00:00
117549bf1e [PLUGINS][Favourite] Remove favourite action properly removes note_favourite Entity now [COMPONENTS][Collection] Simplyfying feed-action-details template section
[COMPONENTS] Documentation work [PLUGINS] Documentation work
2022-01-27 00:54:27 +00:00
adf484f58a [COMPONENTS][Posting] No error to ignore was reported on line 161, removed ignore
[PLUGINS][Directory] Further documentation work

[CORE][Controller] Separating workflows, setting proper return types

[TWIG][Security] Removing unused stylesheet calls
2022-01-26 20:54:55 +00:00
16e7d6cff7 [COMPONENTS] Documenting methods with high cognitive complexity, specifically in Group and Posting components
[PLUGINS][Directory] Updating docs, @params weren't set correctly
2022-01-26 20:01:37 +00:00
6a5312aca9 [CORE][GNUsocial] social.local.yaml is now updated with the proper node name 2022-01-26 18:46:31 +00:00
14bb1b2876 [COMPONENTS][Conversation] Note being replied to now appears before Posting's own form, RightPanel is also open by default on smaller screens when the current route is 'conversation_reply_to' 2022-01-25 19:18:42 +00:00
c7c5fe7979 [PLUGIN][OAuth2] Add 'me' field to token responses 2022-01-25 16:07:39 +00:00
fa0d02a9ac [PLUGIN][OAuth2] Start adding OAuth2 support with client registration
This hardcodes the user, and has some other issues, so it is not yet
complete.

We follow mastodon's spec for automatic client registration, available
at both `/api/v1/apps` and a more reasonable `/oauth/client`. This
accepts a JSON POST with the client info and returns JSON with a
`client_id` and a `client_secret`, to be used with `/oauth/authorize`
and `/oauth/token`. It also, seemingly, requires returning an `id`
with unclear purpose.

The `/oauth/token` endpoint doesn't currently return a `me` field.
2022-01-25 13:35:44 +00:00
4736146b80 [TOOLS] Update autocode, allow for abstract entity classes, derive namespace from file rather than using 'get_declared_classes' 2022-01-25 13:35:44 +00:00
e3bfb1ebc5 [CSS] .note-info text will automatically crop when no space is available, on hover will show contents 2022-01-25 00:02:38 +00:00
ee04571f4d [TWIG] Various fixes related to header elements hierarchy
Widgets shouldn't have a header element from here forward, since their location varies
2022-01-23 19:46:47 +00:00
bf07fa1ade [COMPONENTS][Collection] Added PrependActorsCollection event [COMPONENTS][Group] Added getGroupCreateForm, used in PrependActorsCollection event to build create a new Group form view
[COMPONENTS][LeftPanel] Removed onEndShowStyles event since the corresponding CSS needed is now consolidated into the default_theme itself [COMPONENTS][RightPanel] Deleted components/RightPanel/RightPanel.php, since its only method (onEndShowStyles) wasn't needed anymore
2022-01-23 19:07:39 +00:00
e4a3438d55 [CORE][I18n] Fixing 'file_get_contents(): Argument #1 () must be of type string, Symfony\Component\Finder\SplFileInfo given' error by using Symfony's Finder to iterate through existing files 2022-01-23 19:07:39 +00:00
6b1c6f603e [CORE][ActorLocalRoles] Improve Roles 2022-01-22 18:47:56 +00:00
5f243f68be [DEPENDENCIES] Add symfony/psr-http-message-bridge 2022-01-21 22:05:34 +00:00
68c3204e71 [DEPENDENCIES] Update dependencies 2022-01-21 22:05:34 +00:00
559f6d650b [COMPONENT][Language] Fix template name in language sorting 2022-01-21 22:05:34 +00:00
3d9edd1db8 [COMPONENTS][LeftPanel] Edit feeds page polish, existing links are shown in a grid, saving space
[COMPONENTS][Collection] Fixing details summary class [PLUGINS][WebMonetization] Fixing widget details summary class
2022-01-21 22:05:34 +00:00
402300fe93 [COMPONENTS][Search] Fixing Search form incorrect class names 2022-01-21 22:05:34 +00:00
e2e1b0172d [COMPONENTS][Collection] Actors view template ordering section polished [PLUGINS][RepeatNote] Note to be repeated now uses full note card
[CSS] Simplyfying rules, re-ordering and removing unnecessary and costly 'display: flex' rules
[CARDS][Note] Minimal note macro has info inside the note itself now, since horizontal space is limited
2022-01-21 22:05:33 +00:00
f731850f5c [CSS] .section-widget class and derivatives replaced as .frame-section, since a widget implies a simple element with a specific function 2022-01-21 22:05:33 +00:00
7d546e8901 [CSS] Improved performance, reduced padding [COMPONENTS][LeftPanel] Consolidated CSS into base.css [COMPONENTS][RightPanel] Consolidated CSS into base.css [PLUGINS][WebMonetization] Replaced fieldset with section
Accessibility tests failed if the fieldset had no legend, since it
wasn't really neeeded, it was replaced as another element.
2022-01-21 22:05:33 +00:00
bdeb3bcff5 [PLUGIN][ActivityPub] Federate Actor of types other than Person
Fix some other minor bugs
2022-01-21 22:05:31 +00:00
25b2847201 [TOOLS][AYY1] Improve accesibility testing to save images and compare the differences against a reference (tests/screenshots/ 2022-01-21 21:03:09 +00:00
23d45ffab7 [UTIL][Formatting] Mention prefix was hardcoded, fixed. 2022-01-21 21:03:09 +00:00
b253ce5e70 [DOCS][Design] Add guidelines menu entry 2022-01-21 21:03:09 +00:00
c4f9e58e8d [COMPONENTS][Attachment] Fixed typo on attachmentShowWithNote, where the template called was somehow replaced with a child of it 2022-01-21 21:03:09 +00:00
6ab740d780 [COMPONENT][Search][UI] Fix template, which included the search builder form inside the search form, chaos ensuing 2022-01-21 21:03:09 +00:00
de795b78f9 [DOCKER][DEPENDENCIES] Restructure PHP Dockerfile to install each package in separate layers and add WikiMedia texvc 2022-01-21 21:03:09 +00:00
29d498770c [COMPONENTS][Group] Create a group route added, template polished
[COMPONENTS][Circle] Removed any Group related route from shouldAddToRightPanel event
[CARDS][Profile] Block should now allow inline long nicknames to not
break
2022-01-21 21:03:09 +00:00
d7039b1c5c [COMPONENTS][Group] Create a group route added, template polished
[COMPONENTS][Circle] Removed any Group related route from shouldAddToRightPanel event
[CARDS][Profile] Block should now allow inline long nicknames to not
break
2022-01-21 21:03:08 +00:00
1856af68b3 [PLUGIN][RepeatNote][COMPONENTS][Posting] Review and fix RepeatNote. Handle attachment lives in Posting 2022-01-21 21:03:08 +00:00
9bd1f42843 [TOOLS] Use sudo to remove files 2022-01-21 21:03:08 +00:00
145c88d43f [ENTITY][Note] Only attempt to find mentions if we have content 2022-01-21 21:03:08 +00:00
4717dde12e [TWIG][I18N] Improve base template facilitate translations of the accessibility panel text 2022-01-21 21:03:08 +00:00
c028a601a5 [COMPONENTS][Group] Create a group route added, template polished
[COMPONENTS][Circle] Removed any Group related route from shouldAddToRightPanel event
[CARDS][Profile] Block should now allow inline long nicknames to not
break
2022-01-21 21:03:08 +00:00
692ecf1c99 [TWIG] Improved templates HTML structure, removed unnecessary element nesting, and refactored content sectioning
[COMPONENTS][Search] Refactored widget event as 'PrependRightPanel' (making it able to accomodate more generic blocks)
2022-01-21 21:03:08 +00:00
242fe3fd6e [PLUGINS][PinnedNotes] Replacing arbitary size values with common variables 2022-01-21 21:03:08 +00:00
dbdf1d9b0b [CSS] Fixed footer responsiveness, since its content wouldn't wrap up from insuficient space for all of its content 2022-01-21 21:03:08 +00:00
7daa61500d [COMPONENTS][Collection] Notes collection template now has a default title
[CARDS][Note] Removed note actions from minimal note block
2022-01-21 21:03:07 +00:00
077cbcf424 [TWIG] Improved accessibility menu
[COMPONENTS][RightPanel] Content form row is now preceeded by the content type form row
2022-01-21 21:03:07 +00:00
04431885aa [PLUGIN][PinnedNotes] Fix ActivityPub config 2022-01-21 21:03:07 +00:00
b8a35f9d6d [PLUGIN][WebMonetization] Fix ActivityPub config 2022-01-21 21:03:07 +00:00
184d0246a5 [COMPONENTS][RightPanel] AppendRightPanelBlock event refactored,
replaced with src/Twig/Rintime::getRightPanelBlocks
[COMPONENTS] Re-ordered onAppendRightPanelBlock event calls arguments for improved consistency across events
2022-01-21 21:03:07 +00:00
da7ae5e1f5 [TESTS][A11Y] Login and check all user pages for accessibility 2022-01-21 21:03:07 +00:00
9e4aed84f8 [PLUGIN][LatexNotes] add LaTeX support for notes 2022-01-21 21:03:07 +00:00
db42ade2b6 [PLUGIN][MarkdownNotes] add markdown support for notes 2022-01-21 21:03:07 +00:00
06d11d8337 [PLUGINS[WebMonetization] Basic activityPub support 2022-01-21 21:03:07 +00:00
148dd6db50 [PLUGINS][PinnedNotes] Basic activityPub support 2022-01-21 21:03:06 +00:00
21c7912702 [PLUGIN][Pinned Notes] Allow user to pin his notes 2022-01-21 21:03:06 +00:00
f7cbfbff8c [COMPONENT][Collection] Add event to render html before drawing feed 2022-01-21 21:03:06 +00:00
3f0d996dc9 [COMPONENT][Tag] Fix event handling 2022-01-21 21:03:06 +00:00
9e891ed020 [TOOLS][PHPStan] Ignore errors due to lack of namespace in CodeCeption acceptance tester 2022-01-21 21:03:06 +00:00
6c6c0270c5 [TESTS][CodeCeption] Update acceptance tests to remove accesibility test kludge 2022-01-21 21:03:06 +00:00
a59997b41f [TOOLS][DOCKER][A11Y] Switch to Pa11y CI and don't run it 'integrated' with codeception, since there was no good way to share cookies 2022-01-21 21:03:06 +00:00
d542be1df4 [ACCESSIBILITY] Fix regressions in panel checkboxes and accessibility menu accesskeys
Accessibility menu accesskey regressions introduced with [ACCESSIBILITY][BASE] Accessibility menu was unreachable.
2022-01-13 19:47:41 +00:00
eff9318c1d [UTIL][Formatting] Mention title is not always defined 2022-01-13 18:07:19 +00:00
fa9df9962e [COMPONENTS][Conversation] Route 'conversation_mute' now has the
corresponding conversation view embedded, user is also redirected
properly
[PLUGINS][Favourite] Fixed typo
2022-01-13 17:47:47 +00:00
859bf0c0bf [CONTROLLER][UserPanel] Notification settings panel debug information added for future reference 2022-01-13 16:24:23 +00:00
d29e28b829 [CORE][Entity] Replaced get_called_class() calls with static::class since the former is deprecated 2022-01-13 16:24:12 +00:00
14b03c7137 [UI][UserPanel] Do not try to re-set an unchanged nickname 2022-01-12 17:46:13 +00:00
480f570238 [CORE][SECURITY][HTML] Refactor Security::sanitize to HTML::sanitize
Update composer dependencies, move more general deps from ActivityPub to Core
2022-01-12 17:12:58 +00:00
968b1751fd [CSS] Further styling optimizations, compacting common rules. Removed select dropdown images, since they are no longer required 2022-01-12 16:42:33 +00:00
c8daa82c1d [TWIG] Replaced base.css @import with HTML link imports
According to 'High Performance Web Sites' (ISBN 10: 0596529309), @import has a negative impact on web page performance. Since all imports dependant on base.css will only start downloading after that one is fully gathered.
2022-01-12 16:32:47 +00:00
600a1511cb [TWIG] Removed all instances were 'arrow-down' icon was called in twig templates, replaced it's intended feedback by using :after pseudo-selector within CSS
In user panel render time reduced dramatically, by ~70ms. Said icon was requested by twig >10 times.
2022-01-12 16:07:28 +00:00
59b8bdf99b [PLUGIN][ActivityPub] Provide ActivityStreams 2.0 responses for every Collection
Implemented ActivityPub Outbox
2022-01-11 20:30:25 +00:00
f3a7e8f04d [TOOLS] Remove CodeCeption files from composer autoload-dev, since they're not available before installing, and ignore errors in PHPStan 2022-01-10 23:14:43 +00:00
65504b72bb [TOOLS] Setup pa11y to run on pages after codeception 2022-01-10 23:09:39 +00:00
José Marques
d713429d88 [CORE][Nickname] Properly set nickname for existing accounts 2022-01-10 11:33:13 +00:00
1056bc661f [COMPONENT][FreeNetwork] Restore Galaxy feed 2022-01-10 10:29:55 +00:00
f40eb3955f [TOOLS] Update makefile to add an acceptance and accesibility testing target 2022-01-09 14:45:33 +00:00
b2b445d21e [TOOLS][DOCKER] Add pa11y and nginx container to tooling toolchain 2022-01-09 14:44:56 +00:00
528f6df240 [TOOLS][PHPStan] Ignore autogenerated Codeception classes 2022-01-09 14:44:08 +00:00
894c78bf99 [TOOLS] Keep git in docker image, since we use patched composer packages, temporarily 2022-01-09 14:43:33 +00:00
38baa192d8 [DEPENDENCIES][TOOL] Add codeception and bootstrap it for acceptance and accessibility testing 2022-01-09 14:42:16 +00:00
a697399a6f [PLUGIN][DeleteNote][Favourite][ProfileColor][RepeatNote][WebMonetization] Refactor, cleanup and cache results 2022-01-09 12:29:34 +00:00
cdf1d67d0f [CORE][Cache] Workaround to redis not allowing empty lists 2022-01-09 12:29:34 +00:00
06ece5b72e [COMPONENT][Collection] Only run queries if the criteria is not empty 2022-01-09 12:29:34 +00:00
da6d3bd351 [COMPONENT][Collection] Use current locale 2022-01-09 12:29:34 +00:00
c835fc6aca [COMPONENT][Collection][Feed][Attachment][Feed][Language][Tag] Refactor and consolidate Search and Feed query mechanisms into Collection. Remame 'onSearch' events to 'onCollectionQuery' 2022-01-09 12:29:34 +00:00
57604b3851 [PLUGIN][NoteTypeFilter] Always show filtering options 2022-01-09 12:29:34 +00:00
b1abd81aca [DEPENDENCIES] Update dependencies 2022-01-08 00:11:12 +00:00
5cfed3d536 [TWIG] Display errors in templates that display forms with form_start 2022-01-08 00:11:08 +00:00
0758d6145b [COMPONENT][Collection][CONTROLLER][Collection] Use null-safe calls to attempt to get a language 2022-01-08 00:07:32 +00:00
d17f276419 [COMPONENTS][Conversation] Added missing foreign keys to ConversationMute Entity
Fixed 'is_muted' variable check logic that impeded the Conversation from being muted
2022-01-07 21:14:51 +00:00
fc57b3290e [COMPONENTS][Search] Polished results page HTML view 2022-01-07 21:14:51 +00:00
1438433859 [PLUGINS][NoteTypeFeedFilter] Polish feed actions HTML, adding proper anchor titles and better user feedback when a filter in applied
[COMPONENTS][Collection] Notes feed template HTML polish to accomodate changes needed for NoteTypeFeedFilter
2022-01-07 21:14:51 +00:00
cb1dc4c10f [PLUGIN][WebMonetization] Adding Web Monetization plugin which allows for donations using the Web Monetizations protocol 2022-01-07 14:55:35 -03:00
9cf8970603 [TEMPLATES][Base] AppendToHead event added to base template 2022-01-07 14:53:55 -03:00
c3d58c350e [COMPONENTS][Collections] Iterating documentation 2022-01-07 09:23:37 -03:00
e056920de4 [COMPONENT][Subscription] Fix Notifications 2022-01-06 12:13:11 +00:00
0c245fcb6e [COMPONENTS][Subscription] Subscribe Actor action implemented
[TWIG] AddProfileAction event added
[CARDS][Profile] Refactor and restyling to accomodate Actor actions
2022-01-06 12:13:10 +00:00
0d1ab2c9cf [SECURITY][Register] New users should have their current browser language set as first language preference 2022-01-05 04:19:35 +00:00
3f8fab0021 [PLUGIN][Favourite] Fix routes 2022-01-05 04:19:35 +00:00
cd6ce3542e [COMPONENT][Circle] Move circles to a component, various bug fixes
Mention links are now correct
2022-01-05 04:19:22 +00:00
627d92b290 [COMPONENT][Tag] Improve Note Tag Handling and start extracting Circles logic out of the plugin, various bug fixes 2022-01-05 01:30:02 +00:00
ee007befa4 [COMPONENT][Posting] DB::Flush after Notification and fix minor issues with In targets 2022-01-05 01:30:01 +00:00
9df9c6a19c [COMPONENT][Collection] Make MetaCollectionPlugin a trait and abstract collection delete and name update 2022-01-05 01:30:00 +00:00
754135743e [COMPONENT][Subscription] Move respective routes to component 2022-01-05 01:29:27 +00:00
5a0bbfc795 [UTIL][Common][I18N] Use actor's preferred language for _m and utility to retrieve current language even when no actor is logged in 2022-01-05 01:29:26 +00:00
6247dd4c1a [COMPONENT][RightPanel] Display form errors 2022-01-04 18:58:32 +00:00
de8eab2cf8 [CORE][FORM][FormTypeNonceExtension] Add a nonce to all forms with a CSRF token 2022-01-04 18:58:32 +00:00
b7e4f79ccc [CORE][Cache] Add Cache::incr which increments a value at , atomically, in the case of Redis 2022-01-04 18:58:32 +00:00
a5b5362be2 [DOCS][Designer] General guidelines for styling initiated
Added wireframes of default page, dividing page into 4 distinct general
areas.

Added CSS classes reference table.
2022-01-04 00:02:21 +00:00
d444ea7963 [COMPONENT][Conversation] Refactor and fix Conversation component 2022-01-03 21:20:27 +00:00
a729a8eddb [COMPONENT][Collection] Pass current actor and their top language to query, if not otherwise specified 2022-01-03 21:20:26 +00:00
a8a8cc4046 [COMPONENT][Posting] Plumb in reply_to and redirecto to GET from 2022-01-03 21:20:26 +00:00
7d38c927e1 [ENTITY][Note][CACHE] Consolidate cache keys to helper function and add ensureCanInteract 2022-01-03 21:20:26 +00:00
135bf8bc68 [COMPONENTS][Conversation] Documented respective Controller
[PLUGINS][TreeNotes] Documentation added, feedFormatTree explained in detail
2022-01-03 19:26:17 +00:00
5a31258190 [COMPONENTS][Conversation] Further documentation work, expected arguments explained in more detail 2022-01-03 19:26:17 +00:00
f5fc7b6cd1 [CORE][Controller] Add facility for either returning null or throwing, from Controller->{int,string,bool} 2022-01-03 18:02:33 +00:00
141c5f6785 [COMPONENT][Collection][CONTROLLER][Collection] Add utility method to call Feed::query in Collection, which handles getting and passing the page 2022-01-03 18:02:33 +00:00
07b65584ff [COMPONENTS][Posting] Replaced is_int() with is_numeric(), casting target to int when using Actor getter
From php-stan: is int with string evaluates to false

Thus, the change was made in order to behave as intended
2022-01-03 17:58:48 +00:00
4ae160b0f8 [PLUGINS][AttachmentShowRelated] Fix onEndShowStyles condition to add proper stylesheet to array 2022-01-03 17:51:19 +00:00
a622b175bc [DEPENDENCIES] Update dependencies 2022-01-03 16:38:51 +00:00
9ea230d12b [COMPONENT][Subscription] Implement subscription handlers 2022-01-03 02:23:06 +00:00
fe087b2217 [PLUGIN][ActivityPub] Accept Undo Follow 2022-01-03 02:23:06 +00:00
a9ea49d34c [TOOLS][DOC] Add documentation to functions flagged by doc-check 2022-01-03 02:23:06 +00:00
9e0a2dd4a0 [TOOLS] Fix errors found by PHPStan 2022-01-03 02:23:06 +00:00
8fa04bb47d [EVENT][AddFeedActions] Add bool param which denotes whether the feed is empty. [PLUGIN][NoteTypeFeedFilter] Don't show filters if the feed is empty 2022-01-03 02:23:06 +00:00
d5a6fa924b [COMPONENT][Conversation][ENTITY][ConversationMute] Rename Conversation{Block,Mute} 2022-01-03 02:23:05 +00:00
ba0b0629b7 [TOOLS] Fix deprecations in php-doc-check by providing my own implementation 2022-01-03 02:18:44 +00:00
27276ba379 [CONFIG] Rename streams/notes_per_page to feeds/entries_per_page 2022-01-03 02:18:44 +00:00
ea5a4df1a4 [UI][PLUGIN][Directory] Add UI for Directory listing ordering. This uses a GET parameter, which subits the field in order_by and the operator in order_op. Using order_by=filed^ is still supported 2022-01-03 02:18:44 +00:00
6cfb69d64b [COMPONENT][Subscription] Start component 2022-01-03 02:18:44 +00:00
5fa8056899 [COMPONENT][Collection] Refactoring: Further work in abstracting collections 2022-01-03 02:18:43 +00:00
def5f36c25 [PLUGIN][ActivityPub][Inbox] Accept Follow Activity
Improve how Core Activity is handled in general
2022-01-02 23:50:16 +00:00
afb7ae0f75 [CORE][Util][Exception] Add log context to BugFoundException 2022-01-02 23:50:15 +00:00
064288e33b [CSS] Applying correct border-radius to note-info and adding a greater margin on note-complementary, in case its the last of type 2022-01-02 23:50:15 +00:00
c7ea56d571 [CSS] Fixing checkboxes from displaying background cropped 2022-01-02 23:50:15 +00:00
17b46b9aeb [CSS] Fixed radio button, it didnt change its own background upon being checked, making it invisible 2022-01-02 23:50:15 +00:00
28424402ec [CONTROLLER][CollectionController] Refactored methods names and form
titles
[PLUGINS][AttachmentCollections] Renamed respective Controller to
differentiate it between The Controller and itself, renamed templates
and removed unnecessary HTML from templates
2022-01-02 23:50:15 +00:00
7ad39fdc83 [PLUGINS][Repeat] Added onNoteDeleteRelated event
Using DB::merge to increment attachment lives when repeating a note,
since it's getting deprecated in the future, an alternative needs to
replace it here
2022-01-02 23:50:15 +00:00
d5080890ac [PLUGINS][Favourite] Added onNoteDeleteRelated event
All favourite entities are now removed from note_favourite table when the respective note
is deleted. Documented the favourNote and unfavourNote methods
2022-01-02 23:50:15 +00:00
f42e91d2bc [CORE][Controller] Allow plugins to override redirect responses 2022-01-02 23:50:14 +00:00
362fc6c7dd [CORE][Controller] Set some safe default headers for every response 2022-01-02 23:50:14 +00:00
046731a05a [COMPONENT][Avatar] Save title if possible, delete correctly, no early flushes
[PLUGIN][ActivityPub] Minor bug fixes in Actor translation
2022-01-02 23:50:14 +00:00
d27e8610d6 [CORE][DB] DB:removeBy Accept class name instead of table. 2022-01-02 23:50:14 +00:00
b7574500f8 [COMPONENT][FreeNetwork] Set discovery cors enabled by default 2022-01-01 23:57:28 +00:00
6ea45df3b8 [COMPONENT][FreeNetwork] Set JRD as the default mimetype for .well-know/host-meta 2022-01-01 23:57:28 +00:00
d6cd33019d [UI][PLUGIN][Directory] Add sort options to UI 2022-01-01 22:18:18 +00:00
5662210a2d [UI][PLUGIN][Directory] Use a single template for all results 2022-01-01 22:18:18 +00:00
b1fbf7d6ef [PLUGIN][Directory] Add option to order by subscribers 2022-01-01 22:18:18 +00:00
9f11d270f4 [PLUGIN][Directory] Fix opposite sort order 2022-01-01 22:18:18 +00:00
e7940a21ee [PLUGINS][TreeNotes] Feed only shows each note and its respective direct
replies, conversation shows whole tree

[COMPONENTS][Feed] Added request to FormatNoteList event

Every single Note that was provided to FeedController::postProcess is
shown. This means, that even though the Feed is formatted to show only a
Note and its respective direct replies, those same replies are shown
individually again (and they get the chance to show their own direct
replies).

The Note list provided to FormatNoteList is reversed, and for every
index, the respective Note replies are filtered out of the original list.
The replies are then added as leafs of the current Note and added to the tree.
2022-01-01 21:42:47 +00:00
f6311debbf [PLUGIN][Directory] Refactor directory controller, so it's hopefully clearer what's happening 2022-01-01 20:50:04 +00:00
175c98b043 [PLUGIN][Directory] Add options to sort by nickname, created, modified and activity, ascending or descending 2022-01-01 20:49:17 +00:00
acc84d757c [CORE][Controller] Make Controller->{int,bool,string} functions return null if the GET parameter doesn't exist 2022-01-01 20:03:40 +00:00
fc76a00908 [PLUGIN][Directory] Rename actor to people, as it's what's actually interacted with 2022-01-01 20:02:32 +00:00
1f01923aa1 [COMPONENT][Conversation] Implement Conversation muting 2022-01-01 10:32:07 +00:00
1a99762699 [COMPONENT][Posting][Notification] Move group inbox message creation to Notification component 2022-01-01 10:32:07 +00:00
f346cd8167 [COMPONENT][Language][Tag] Update usage of Functional::cartesian_product 2021-12-31 21:03:25 +00:00
7aa90954eb [UTIL][Functional] Update Functional::cartesian_product to pass an array of collections first and a separator after 2021-12-31 21:03:25 +00:00
0050371de7 [PLUGIN][NoteTypeFeedFilter][MediaFeed][COMPONENT][Feed] Rename MediaFeed to NoteTypeFeedFilter and add support for filtering by more types, moving functionality from Feed component 2021-12-31 21:03:25 +00:00
b7872ba4ee [CORE][Controller][FeedController] Use controller instance for filtering, making FeedControler->postProcess function non-static 2021-12-31 21:03:17 +00:00
ba078b7b76 [ENTITY][Note] Caching note replies query
[COMPONENTS][Conversation] Reply route will now present a more suitable title
2021-12-31 17:54:06 +00:00
d7b46735ac [CARDS][Note] Removing unnecessary elements on replies block, and fixing gaps between note-info and the note border itself 2021-12-31 17:02:18 +00:00
6dd31926ad [COMPONENTS][Conversation] reply_add route nows shows the given Note entire conversation, the Note itself is highlighted in the conversation 2021-12-30 18:34:47 +00:00
34cc010136 [CARDS][Note] Separating complementary info as its own block 2021-12-30 18:34:47 +00:00
9a6bdf74dc [COMPONENT][Feed] Add way of filtering the notes on an arbitrary feed with a types GET parameter, that accepts {,!}<[media,text,link,tags]...> 2021-12-30 18:28:57 +00:00
0ae24f6088 [CORE][Controller][FeedController] Use controller instance for filtering, making FeedControler->postProcess function non-static 2021-12-30 18:28:57 +00:00
5f4968ac05 [ENTITY][Note][CACHE] Store lists as lists in the cache 2021-12-30 18:28:57 +00:00
2e0bfc0bcd [TOOLS] Run CS-Fixer on all files 2021-12-30 18:28:57 +00:00
2dbc35fcc3 [DEPENDENCIES] Update dependencies 2021-12-30 18:28:57 +00:00
8831276489 [TOOLS] Fix errors reported by PHPStan 2021-12-30 18:28:57 +00:00
5229d4cd8c [COMPONENT][Notification] Remove nickname GET parameter 2021-12-30 18:28:56 +00:00
cbb70a5054 [COMPONENT][Feed] Refactor Feed component 2021-12-30 18:28:56 +00:00
f16df759a9 [Components][Posting] Posting section title set accordingly if in 'reply_add' route 2021-12-30 16:18:16 +00:00
2c31f2e440 [PLUGIN][Actor Circles] Actor Circles plugin, allow user to create a custom feed of actors 2021-12-30 12:18:16 -03:00
85e31c684d [MODULES][Collection] Fixing mistakes 2021-12-30 12:16:29 -03:00
bdd8cbf36d [COMPONENT][Right Panel] Send request to AppendRightPanelBlock event 2021-12-30 12:14:41 -03:00
d7f70d288d [MODULES][Collection] Abstracting Collections 2021-12-29 21:56:45 -03:00
49d247aec2 [COMPONENTS][Feed] Styling for the empty feed page added 2021-12-29 19:31:28 +00:00
f28ed5e359 [CSS] .note-complementary-info now smaller in general 2021-12-29 19:02:06 +00:00
6b82708968 [CARDS][Note] AppendCardNote event overhaul
[PLUGINS][Favourite] Added complementary information on user action

[COMPONENTS][Conversation] Fixed AppendCardNote issue where cached query
would only act on Notes with depth > 1
2021-12-29 18:47:12 +00:00
836560f55f [CARDS][Note] AppendCardNote event overhaul
[PLUGINS][Favourite] Added complementary information on user action

[COMPONENTS][Conversation] Fixed AppendCardNote issue where cached query
would only act on Notes with depth > 1
2021-12-29 18:35:12 +00:00
0caec6ab9e [COMPONENT][ACTOR CIRCLE] fixing template text 2021-12-29 14:13:25 -03:00
01d5e84a08 [COMPONENT][ACTOR CIRCLE] mention self tag circle with @#self_tag 2021-12-29 14:13:25 -03:00
f9bc1c790f [PLUGIN][AttachmentCollections] Dark mode 2021-12-29 10:52:04 -03:00
25120c6630 [PLUGIN][AttachmentCollections] Responsive pages 2021-12-29 10:52:04 -03:00
137723e59a [PLUGIN][ActivityPub][Favourite][Repeat][Delete] Document event handlers 2021-12-28 22:57:49 +00:00
8274e93ed5 [PLUGINS][DeleteNote] Added documentation, stating the scope of what deleting a Note means 2021-12-28 22:43:04 +00:00
ce3c6a7f23 [PLUGINS][RepeatNote] Added documentation (not for ActivityPub related functions) 2021-12-28 21:51:27 +00:00
846ec37cd9 [COMPONENT][Notification] Add event to decide whether local actors should be bothered 2021-12-28 18:45:18 +00:00
4d8e39bf69 [PLUGIN][RepeatNote] Do not notify about clone note
Fix redirecion after action
Fix typo in activitypub handler
2021-12-28 18:30:27 +00:00
182c6265a3 [PLUGINS][RepeatNote] Add onFilterNoteList event
Filters repeats out of Conversations, and replaces a repeat with the original Note on Actor feed

Added isNoteRepeat to plugin's entity, which returns true if a given
Note is a repeat of another Note
2021-12-28 17:37:01 +00:00
1d1d169a5c [PLUGIN][ActivityPub] Support federation of Tombstones 2021-12-28 17:10:20 +00:00
9cda64f275 [COMPONENT][Notification] Use _m() in reason 2021-12-28 16:36:52 +00:00
3e83387e98 [PLUGIN][DeleteNote] Support ActivityPub 2021-12-28 16:22:38 +00:00
9585472679 [ENTITY][Actor] Basic check if can admin for remote actors 2021-12-28 15:38:41 +00:00
b7c82b9dcb [PLUGIN][DeleteNote] Ensure permissions properly 2021-12-28 15:38:39 +00:00
5c2b46a71d [COMPONENT][Link] Wrap delete operations in transactions 2021-12-28 06:56:05 +00:00
46d121ef7b [COMPONENT][Attachment] Wrap delete operations in transactions and correct sequence of deletation 2021-12-28 06:56:05 +00:00
bf4a0008ef [ENTITY][Note] GNU social uses Tombstones for deleted notes instead of fully removing them.
Various corrections.
2021-12-28 06:56:05 +00:00
bb4149e092 [PLUGIN][AttachmentCollections] Restore functionality
Some minor corrections
2021-12-28 04:43:13 +00:00
a03429ba03 [PLUGIN][DeleteNote] Delete Note action implemented
Replaces Note content with a tombstone, removes any attachment relations and decrements their lives (possibly even removing the attachment), and creates the respective activity
2021-12-27 22:33:36 +00:00
f5b06e2c7e [UTIL][Formatting] Fix group mentions 2021-12-27 21:38:20 +00:00
c40e38c5ba [TOOLS] Fix errors found by PHPStan 2021-12-27 20:37:16 +00:00
d74a9ad373 [ENTITY][Subscription] Add Subscription::cacheKeys 2021-12-27 20:37:16 +00:00
76440961ca [CORE][DB] Add option to findOneBy to return null rather than throw 2021-12-27 20:37:16 +00:00
8796885fa0 [COMPONENT][Tag] Remove '.' from tag regex 2021-12-27 20:37:16 +00:00
5c10448080 [COMPONENT][Group] Add group subscribe button 2021-12-27 20:37:16 +00:00
559ec3df39 [TWIG] Fix login template 2021-12-27 19:09:32 +00:00
20d89f0f24 [COMPONENTS][Avatar] Make sure dimension values are integers
[CARDS][Note] Fix assumed avatar dimension values
2021-12-27 19:08:55 +00:00
19975b8d8d [COMPONENTS][Avatar] Make sure dimension values are integers
[CARDS][Note] Fix assumed avatar dimension values
2021-12-27 19:08:51 +00:00
65a3d738ca [PLUGIN][AttachmentCollections] Make it look good 2021-12-27 15:38:47 -03:00
7ddfe92773 fix: redirect 2021-12-27 15:35:09 -03:00
e932ff43d0 [PLUGIN][AttachmentCollections] changes path name to be the same as the one introduced in c4dacd7626 2021-12-27 15:31:19 -03:00
672df5165c [PLUGIN][AttachmentCollections] Fixing forms submission 2021-12-27 15:25:20 -03:00
72a19d7eac [COMPONENT][Posting] Fix error around mentions of actors that don't exist 2021-12-27 17:35:33 +00:00
b84315c95b [TOOLS] Fix errors reported by PHPStan at level 4 2021-12-27 17:35:33 +00:00
edd996d281 [DEPENDENCIES] Update dependencies, including PHPStan to dev version 2021-12-27 17:35:33 +00:00
cf2f87fc1d [AUTOGENERATED] Update autogenerated code 2021-12-27 17:35:33 +00:00
c9d05d71f5 [COMPONENT][Group] Fix group creation, Refactor related entities to inside the component
Other minor bug fixes and improvements
2021-12-27 17:28:03 +00:00
d03572e366 [PLUGIN][Directory] Make it list groups 2021-12-27 17:10:58 +00:00
de148c1f78 [COMPONENT][Avatar][Controller] Implement multiple dimensions 2021-12-27 05:08:29 +00:00
2a902d6a7e [ASSETS][css][sections] rename profile-avatar to avatar 2021-12-27 05:08:29 +00:00
195618801b [TEMPLATES][Cards][Note] Fix some issues with note minimal 2021-12-27 05:08:29 +00:00
80afc0fa6c [TEMPLATES][Cards][Profile] Provide both actor uri and url, as well as full mention guidance 2021-12-27 05:08:27 +00:00
eb761609aa [ENTITY][Note] If note is a reply to, notify reply's actor 2021-12-27 04:56:00 +00:00
c4dacd7626 [COMPONENT][Attachment] Vinculate note information with attachment controllers
Various minor bug fixes
2021-12-27 04:56:00 +00:00
fd44bc3ac5 [CARDS][Note] Minimize calls between different tables
For instance, the actor_url was set using note.getActor().getUrl() instead of using the actor from the start (since actor was needed in other setters as well).
2021-12-27 03:06:35 +00:00
65676d3980 [CARDS][Note] Fix attachment page from retrieving image dimensions
Attachments may use only a specific block, not the full note macro itself. Since this is the case, the actor needs to be retrieved for the minimal macro note.
2021-12-27 03:06:35 +00:00
ea42ba9f26 [CARDS][Profile] Fix bio
Was using 'hasBio()' instead of 'getBio()'
2021-12-27 03:06:35 +00:00
a1a6f5f4fd [TOOLS] Add warning to update code in bin/generate_entity_fields 2021-12-27 03:06:35 +00:00
93276ce8d0 [AUTOGENERATED] Update autogenerated code 2021-12-27 03:06:30 +00:00
0df423e84b [TOOLS] Update bin/generate_entity_fields so it defaults nullable variables to null and handles null in varchars 2021-12-27 03:03:57 +00:00
7eff22d548 [TOOLS] Fix errors reported by updated PHPStan 2021-12-27 03:03:57 +00:00
52e2231661 [DEPENDENCIES] Update PHPStan and other dependencies 2021-12-27 03:03:57 +00:00
9d3c01312f [CARDS][Note] Fix assumed avatar dimension values 2021-12-27 03:03:53 +00:00
ce23660dba [PLUGIN][ImageEncoder] Only show thumbnails if they exist 2021-12-27 03:02:21 +00:00
58715f1733 [PLUGIN][ImageEncoder] If vips doesn't support, don't throw exception, just let other plugin try 2021-12-27 03:02:20 +00:00
838510ced2 [CARDS][Navigation] Replaced footer to nav
Since the footer is inside a section, it couldn't be a footer element
2021-12-27 03:02:20 +00:00
b30198413c [PLUGINS][Oomox] Add rel to response headers 2021-12-26 21:26:04 +00:00
7402e749cb [COMPONENTS][Feed] Removed unnecessary ARIA 2021-12-26 21:19:33 +00:00
18cfcc0796 [ICONS] Removed XML processing instructions in svg files 2021-12-26 21:19:06 +00:00
045ff6fb68 [PLUGINS][XMPPNotifications] Fix typo 2021-12-26 21:19:06 +00:00
fec1861b80 [CONTROLLER][Note] Respect note scope 2021-12-26 21:19:06 +00:00
d891089945 [PLUGIN][StoreRemoteMedia] Let the user decide the max file size to download 2021-12-26 21:19:04 +00:00
0c421116a6 [ENTITY][Note] Relive isVisibleTo method 2021-12-26 19:50:21 +00:00
78cc9c4659 [PLUGINS][Repeat] Repeat now added has a reply and conversation of original note 2021-12-26 19:16:57 +00:00
e10a38a3e2 [CSS] Align page header on ultrawide screens 2021-12-26 19:16:57 +00:00
feb2631f00 [CARDS][Note] Add permalink to extra note actions 2021-12-26 19:16:57 +00:00
a1d9909379 [CORE][VisibilityScope] Use enum type instead of Bitmap 2021-12-26 19:16:56 +00:00
6f0d9add08 [DEPENDENCIES] Run composer after php version bump from 8.0 to 8.1 2021-12-26 19:16:17 +00:00
6883e51fc8 [DOCKER] Force docker php to use proper PHP executable 2021-12-26 19:16:16 +00:00
3d9141f4ce [COMPONENT][Tag] Allow searching for actor circles with {actor,people}-{circle,list}:#tag 2021-12-26 19:16:16 +00:00
4df80be095 [ENTITY][Actor] Set default null values 2021-12-26 19:16:16 +00:00
d37f38a1ea [ENTITY][Note] A note by default isn't a reply 2021-12-26 19:16:16 +00:00
dd268ba8db [CARDS][Profile] Use Actor::hasBio() instead of getter 2021-12-26 19:16:16 +00:00
8e7c94fe1d [COMPONENT][Attachment] Entity should have default refCount value, every attachment starts with 1 life 2021-12-26 19:16:16 +00:00
94e216a943 [COMPONENT][Conversation] remove early flush in utility function 2021-12-26 19:16:16 +00:00
fdf506b9f9 [CARDS][Note] Fix structure to break content in a controlled manner
[CSS] Responsive feed styling work

Note info content will now break as expected, useless space trimmed down to accomodate smaller screens.
2021-12-26 19:16:16 +00:00
726613cd96 [ENTITY][ActorCircle][COMPONENT][Tag] Add fields to ActorCircle and add or remove target to actor circle when they add or remove a selftag 2021-12-26 19:16:15 +00:00
000ec680e6 [CORE][TOOL] Minor fixes and run cs-fixer 2021-12-26 19:16:15 +00:00
97243151fa [TOOL] CS-fixer does not accept a list of files, so we need to run it on each file individually 2021-12-26 19:16:15 +00:00
c79b1e4c94 [AUTOGENERATED] Update auto generated code 2021-12-26 19:16:15 +00:00
68076d73dd [TOOLS] Update bin/generate_entity_fields so it automatically truncates values in setters 2021-12-26 19:16:15 +00:00
29bb11e8bc [TOOLS] Don't fail commit when checking tools fail 2021-12-26 19:16:15 +00:00
ec28f23025 [TOOLS] Run CS-fixer on all files 2021-12-26 19:16:15 +00:00
5e42723624 [ENTITY][Note] Include reply_to's targets in child's 2021-12-26 19:16:14 +00:00
f5f7fc6056 [PLUGIN][Favourite][Repeat] Add notification target getter 2021-12-26 19:16:14 +00:00
625618b4e0 [PLUGIN][Favourite][Repeat] Fix incorrect use of RedirectException 2021-12-26 19:16:14 +00:00
91f8c86efa [PLUGIN][ActivityPub] Support and federate scopes 2021-12-26 19:16:12 +00:00
21f585ef7e [COMPONENT][Language] Do not exclude notes without language from the feeds 2021-12-26 16:48:36 +00:00
9d5e149dec [COMPONENT][Feed] Correct ordering 2021-12-26 16:48:35 +00:00
19502050e0 [TOOLS] Add remove-file and minor corrections to nuke everything 2021-12-26 16:48:35 +00:00
3e13765f62 [CORE][SCOPE] Implement basic visibility in feeds 2021-12-26 16:48:34 +00:00
d4bc1d097d [ENTITY][NoteTag][COMPONENT][Language] Add language to NoteTag and minor corrections 2021-12-26 06:22:30 +00:00
78fddaf86a [PLUGIN][ActivityPub] Notify mentions in tags 2021-12-26 06:22:28 +00:00
9d0b39e680 [PLUGIN][ActivityPub] Support tags in notes 2021-12-25 18:04:31 +00:00
36483a6ecd [COMPONENT][Link] Ignore html anchors that include mention class 2021-12-25 18:04:30 +00:00
0d5e545a6e [TWIG] Replaced unused markup classes 2021-12-25 17:59:49 +00:00
3275a989db [CSS] Style paging info 2021-12-25 17:48:07 +00:00
ab640b110b [COMPONENTS][Feed] Remove 'feed' from header
When not logged in, the word would be repeated
2021-12-25 17:47:12 +00:00
7891461d36 [PLUGINS][AttachmentCollections] Fix template
[PLUGINS][AttachmentShowRelated] Fix template

[CSS] Fix section-subtitle-details children padding issues

[COMPONENTS][Posting] Remove unnecessary colon

Overall polish of existing plugins templates
2021-12-25 17:31:16 +00:00
ce3b677833 [CONFIG][Twig] Replaced form theme to a custom one
[CARDS][Forms] Added custom social form theme

[CSS] Replaced/added new classes to be used with forms

Base form theme created, can be extended to create complex blocks to be
called by twig when rendering a specific form.
2021-12-25 16:19:46 +00:00
8651bd44c2 [PLUGINS][ProfileColor] Fix callable argument when retrieving cache data 2021-12-25 15:31:24 +00:00
6ada5e60d2 [TOOLS] Make PHP-CS-Fixer and PHP-Doc-check run inside the tooling container 2021-12-25 15:20:21 +00:00
601 changed files with 24989 additions and 11498 deletions

View File

@@ -3,4 +3,4 @@ KERNEL_CLASS='App\Kernel'
APP_SECRET='$ecretf0rt3st' APP_SECRET='$ecretf0rt3st'
SYMFONY_DEPRECATIONS_HELPER=999999 SYMFONY_DEPRECATIONS_HELPER=999999
PANTHER_APP_ENV=panther PANTHER_APP_ENV=panther
DATABASE_URL=postgresql://postgres:password@db:5432/social DATABASE_URL=postgresql://postgres:password@db:5432/test

View File

@@ -37,27 +37,86 @@ database-force-schema-update:
docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) sh -c "/var/www/social/bin/console doctrine:schema:update --dump-sql --force" docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) sh -c "/var/www/social/bin/console doctrine:schema:update --dump-sql --force"
tooling-docker: .PHONY tooling-docker: .PHONY
@cd docker/tooling && docker-compose up -d > /dev/null 2>&1 @cd docker/tooling && docker-compose up -d --build > /dev/null 2>&1
accessibility: .PHONY
@cd docker/accessibility && docker-compose up
test: tooling-docker
docker exec $(call translate-container-name,tooling_php_1) /var/tooling/coverage.sh $(call args,'')
doc-check:
bin/php-doc-check src components plugins
phpstan: tooling-docker
bin/phpstan
stop-tooling: .PHONY stop-tooling: .PHONY
cd docker/tooling && docker-compose down cd docker/tooling && docker-compose down
tooling-php-shell: tooling-docker
docker exec -it $(call translate-container-name,tooling_php_1) sh
test-accesibility: tooling-docker
cd docker/tooling && docker-compose run pa11y /accessibility.sh
test: tooling-docker
docker exec $(call translate-container-name,tooling_php_1) /var/tooling/coverage.sh $(call args,'')
cs-fixer: tooling-docker
@bin/php-cs-fixer $${CS_FIXER_FILE}
doc-check: tooling-docker
bin/php-doc-check
phpstan: tooling-docker
bin/phpstan
remove-var: remove-var:
rm -rf var/* rm -rf var/*
remove-file:
sudo rm -rf file/*
flush-redis-cache: flush-redis-cache:
docker exec -it $(call translate-container-name,$(strip $(DIR))_redis_1) sh -c 'redis-cli flushall' docker exec -it $(call translate-container-name,$(strip $(DIR))_redis_1) sh -c 'redis-cli flushall'
force-nuke-everything: remove-var flush-redis-cache database-force-nuke install-plugins:
docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) /var/www/social/bin/install_plugins.sh
update-dependencies:
docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) sh -c 'cd /var/www/social && composer update'
update-autocode:
docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) sh -c 'cd /var/www/social && bin/update_autocode'
backup-actors:
docker exec -it $(call translate-container-name,$(strip $(DIR))_db_1) \
sh -c 'su postgres -c "mkdir -p /tmp/backup"' && \
docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) \
sh -c "cd /var/www/social && bin/console doctrine:query:sql \"\
copy actor to '/tmp/backup/actor.csv';\
copy local_user to '/tmp/backup/local_user.csv';\
copy local_group to '/tmp/backup/local_group.csv';\
\
copy activitypub_actor to '/tmp/backup/ap_actor.csv';\
copy activitypub_rsa to '/tmp/backup/ap_rsa.csv';\
\
copy actor_subscription to '/tmp/backup/actor_subscription.csv';\
copy group_member to '/tmp/backup/group_member.csv';\
\
copy feed to '/tmp/backup/feed.csv';\
copy (SELECT 'ALTER SEQUENCE ' || c.relname || ' RESTART WITH ' || nextval(c.relname::regclass) || ';'\
FROM pg_class c WHERE c.relkind = 'S') to '/tmp/backup/sequences';\"" && \
mkdir -p /tmp/social-sql-backup && \
docker cp $(call translate-container-name,$(strip $(DIR))_db_1):/tmp/backup/. /tmp/social-sql-backup
restore-actors:
docker cp /tmp/social-sql-backup/. $(call translate-container-name,$(strip $(DIR))_db_1):/tmp/backup
docker exec -it $(call translate-container-name,$(strip $(DIR))_db_1) sh -c 'chown postgres /tmp/backup' && \
docker exec -it $(call translate-container-name,$(strip $(DIR))_php_1) \
sh -c "cd /var/www/social && bin/console doctrine:query:sql \"\
copy actor from '/tmp/backup/actor.csv';\
copy local_user from '/tmp/backup/local_user.csv';\
copy local_group from '/tmp/backup/local_group.csv';\
\
copy activitypub_actor from '/tmp/backup/ap_actor.csv';\
copy activitypub_rsa from '/tmp/backup/ap_rsa.csv';\
\
copy actor_subscription from '/tmp/backup/actor_subscription.csv';\
copy group_member from '/tmp/backup/group_member.csv';\
\
copy feed from '/tmp/backup/feed.csv';\
`cat /tmp/social-sql-backup/sequences`\""
force-nuke-everything: down remove-var remove-file up flush-redis-cache database-force-nuke install-plugins
force-delete-content: backup-actors force-nuke-everything restore-actors

4
bin/configure vendored
View File

@@ -352,8 +352,8 @@ SOCIAL_DBMS=${DBMS}
SOCIAL_DB=${DB_NAME} SOCIAL_DB=${DB_NAME}
SOCIAL_USER=${DB_USER} SOCIAL_USER=${DB_USER}
SOCIAL_PASSWORD=${DB_PASSWORD} SOCIAL_PASSWORD=${DB_PASSWORD}
SOCIAL_DOMAIN=${DOMAIN} CONFIG_DOMAIN=${DOMAIN}
SOCIAL_NODE_NAME=${NODE_NAME} CONFIG_NODE_NAME=${NODE_NAME}
SOCIAL_ADMIN_EMAIL=${EMAIL} SOCIAL_ADMIN_EMAIL=${EMAIL}
SOCIAL_SITE_PROFILE=${PROFILE} SOCIAL_SITE_PROFILE=${PROFILE}
MAILER_DSN=${MAILER_DSN} MAILER_DSN=${MAILER_DSN}

11
bin/install_plugins.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/bin/sh
for plugin in plugins/*; do
install="${plugin}/bin/install.sh"
if [ -x "${install}" ]; then
( # subshell, to clear options/environment
set -x
"${install}"
)
fi
done

View File

@@ -1 +0,0 @@
../vendor/bin/php-cs-fixer

9
bin/php-cs-fixer Executable file
View File

@@ -0,0 +1,9 @@
#!/bin/sh
. bin/translate_container_name.sh
if [ "$#" -eq 0 ] || [ -z "$*" ]; then
docker exec "$(translate_container_name tooling_php_1)" /var/www/social/vendor/bin/php-cs-fixer -n --config=".php-cs-fixer.php" fix
else
docker exec "$(translate_container_name tooling_php_1)" sh -c "/var/www/social/vendor/bin/php-cs-fixer -q -n --config=\".php-cs-fixer.php\" fix --path-mode=intersection -- $*"
fi

View File

@@ -1 +0,0 @@
../vendor/bin/php-doc-check

5
bin/php-doc-check Executable file
View File

@@ -0,0 +1,5 @@
#!/bin/sh
. bin/translate_container_name.sh
docker exec -it "$(translate_container_name tooling_php_1)" /var/www/social/vendor/bin/php-doc-check src components plugins

View File

@@ -1,11 +1,5 @@
#!/bin/sh #!/bin/sh
translate_container_name () { . bin/translate_container_name.sh
if docker container inspect "$1" > /dev/null 2>&1; then
echo "$1"
else
echo "$1" | sed 'y/_/-/'
fi
}
docker exec "$(translate_container_name tooling_php_1)" /var/tooling/phpstan.sh "$@" docker exec "$(translate_container_name tooling_php_1)" /var/tooling/phpstan.sh "$@"

View File

@@ -2,7 +2,7 @@
root="$(git rev-parse --show-toplevel)" root="$(git rev-parse --show-toplevel)"
# get the list of changed files # get the list of changed files that didn't get only partially added
staged_files="$(git status --porcelain | sed -rn "s/^[^ ][ ] (.*)/\1/p")" staged_files="$(git status --porcelain | sed -rn "s/^[^ ][ ] (.*)/\1/p")"
if (! (: "${SKIP_ALL?}") 2>/dev/null) && (! (: "${SKIP_CS_FIX?}") 2>/dev/null); then if (! (: "${SKIP_ALL?}") 2>/dev/null) && (! (: "${SKIP_CS_FIX?}") 2>/dev/null); then
@@ -11,17 +11,16 @@ if (! (: "${SKIP_ALL?}") 2>/dev/null) && (! (: "${SKIP_CS_FIX?}") 2>/dev/null);
# work only with existing files # work only with existing files
if [ -f "${staged}" ] && expr "${staged}" : '^.*\.php$' > /dev/null; then if [ -f "${staged}" ] && expr "${staged}" : '^.*\.php$' > /dev/null; then
# use php-cs-fixer and get flag of correction # use php-cs-fixer and get flag of correction
if "${root}/bin/php-cs-fixer" -q --config="${root}/.php-cs-fixer.php" fix "${staged}"; then CS_FIXER_FILE="${staged}" make cs-fixer
git add "${staged}" # execute git add directly git add "${staged}"
fi
fi fi
done done
fi fi
if (! (: "${SKIP_ALL?}") 2>/dev/null) && (! (: "${SKIP_DOC_CHECK?}") 2>/dev/null); then if (! (: "${SKIP_ALL?}") 2>/dev/null) && (! (: "${SKIP_DOC_CHECK?}") 2>/dev/null); then
echo "Running php-doc-checker" if echo "${staged_files}" | grep -F ".php" > /dev/null 2>&1; then
if echo "${staged_files}" | grep -F ".php"; then echo "Running php-doc-checker"
"${root}/bin/php-doc-check" src plugins components make doc-check < /dev/tty
fi fi
fi fi

View File

@@ -0,0 +1,9 @@
#!/bin/sh
translate_container_name () {
if docker container inspect "$1" > /dev/null 2>&1; then
echo "$1"
else
echo "$1" | sed 'y/_/-/'
fi
}

View File

@@ -1,4 +1,4 @@
#!/usr/local/bin/php #!/usr/bin/env php
<?php <?php
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
@@ -20,25 +20,23 @@ const types = [
'text' => 'string', 'text' => 'string',
'varchar' => 'string', 'varchar' => 'string',
'phone_number' => 'PhoneNumber', 'phone_number' => 'PhoneNumber',
'float' => 'float', // TODO REMOVE THIS
]; ];
$files = array_merge(glob(ROOT . '/src/Entity/*.php'), $files = array_merge(glob(ROOT . '/src/Entity/*.php'),
array_merge(glob(ROOT . '/components/*/Entity/*.php'), array_merge(glob(ROOT . '/components/*/Entity/*.php'),
glob(ROOT . '/plugins/*/Entity/*.php'))); glob(ROOT . '/plugins/*/Entity/*.php')));
$classes = []; $nullable_no_defaults_warning = [];
foreach ($files as $file) { foreach ($files as $file) {
require_once $file; require_once $file;
$declared = get_declared_classes(); $class = str_replace(['/', 'src', 'components', 'plugins'], ['\\', 'App', 'Component', 'Plugin'], substr($file, strlen(ROOT) + 1, -4));
foreach ($declared as $dc) {
if (preg_match('/(App|(Component|Plugin)\\\\[^\\\\]+)\\\\Entity/', $dc) && !in_array($dc, $classes)) { if (!method_exists($class, 'schemaDef')) {
$class = $dc; continue;
$classes[] = $class;
break;
}
} }
$no_ns_class = preg_replace('/.*?\\\\/', '', $class); $no_ns_class = preg_replace('/.*?\\\\/', '', $class);
@@ -47,16 +45,32 @@ foreach ($files as $file) {
$fields_code = []; $fields_code = [];
$methods_code = []; $methods_code = [];
foreach ($fields as $field) { foreach ($fields as $field) {
$nullable = !@$schema['fields'][$field]['not null'] ? '?' : ''; $field_schema = $schema['fields'][$field];
$type = types[$schema['fields'][$field]['type']]; $nullable = ($field_schema['not null'] ?? false) ? '' : '?';
$type = types[$field_schema['type']];
$type = $type !== '' ? $nullable . $type : $type; $type = $type !== '' ? $nullable . $type : $type;
$method_name = str_replace([' ', 'actor'], ['', 'Actor'], ucwords(str_replace('_', ' ', $field))); $method_name = str_replace([' ', 'actor'], ['', 'Actor'], ucwords(str_replace('_', ' ', $field)));
$default = @$schema['fields'][$field]['default']; $length = $field_schema['length'] ?? null;
if (isset($default) && $nullable != '?' && $type != '\DateTimeInterface') { $field_setter = "\${$field}";
if (is_string($default)) { if (\is_int($length)) {
if ($nullable === '?') {
$field_setter = "\is_null(\${$field}) ? null : \mb_substr(\${$field}, 0, $length)";
} else {
$field_setter = "\mb_substr(\${$field}, 0, $length)";
}
}
if (($nullable === '?' || \array_key_exists('default', $field_schema)) && $type != '\DateTimeInterface') {
if (!\array_key_exists('default', $field_schema)) {
$nullable_no_defaults_warning[] = "{$class}::{$field}";
}
$default = $field_schema['default'] ?? null;
if (\is_string($default)) {
$default = "'{$default}'"; $default = "'{$default}'";
} elseif ($type == 'bool') { } elseif (\is_null($default)) {
$default = "null";
} elseif ($type === 'bool' || $type === '?bool') {
$default = $default ? 'true' : 'false'; $default = $default ? 'true' : 'false';
} }
@@ -66,13 +80,13 @@ foreach ($files as $file) {
} }
$methods_code[] = " public function set{$method_name}({$type} \${$field}): self" . $methods_code[] = " public function set{$method_name}({$type} \${$field}): self" .
"\n {\n \$this->{$field} = \${$field};\n return \$this;\n }" . "\n\n" . "\n {\n \$this->{$field} = {$field_setter};\n return \$this;\n }" . "\n\n" .
" public function get{$method_name}()" . ($type !== '' ? ": {$type}" : '') . " public function get{$method_name}()" . ($type !== '' ? ": {$type}" : '') .
"\n {\n return \$this->{$field};\n }" . "\n"; "\n {\n return \$this->{$field};\n }" . "\n";
} }
$fields_code = implode("\n", $fields_code); $fields_code = implode("\n", $fields_code);
$methods_code = implode("\n", $methods_code) . "\n"; $methods_code = implode("\n", $methods_code);
$begin = '// {{{ Autocode'; $begin = '// {{{ Autocode';
$end = '// }}} Autocode'; $end = '// }}} Autocode';
@@ -91,7 +105,13 @@ foreach ($files as $file) {
} }
$in_file = file_get_contents($file); $in_file = file_get_contents($file);
$out_file = preg_replace("/\\s*{$begin}[^\\/]*{$end}/m", $code, $in_file); $out_file = preg_replace("%\\s*{$begin}.*{$end}%smu", $code, $in_file);
file_put_contents($file, $out_file); file_put_contents($file, $out_file);
} }
if (!empty($nullable_no_defaults_warning)) {
echo "Warning: The following don't have a default value, but we're assigning it `null`. Doctrine might not like this, so update it\n";
foreach ($nullable_no_defaults_warning as $n) {
echo " {$n}\n";
}
}

View File

@@ -22,9 +22,10 @@ declare(strict_types = 1);
namespace Component\Attachment; namespace Component\Attachment;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Entity\Actor; use App\Entity\Actor;
use App\Entity\Note; use App\Entity\Note;
use App\Util\Formatting; use App\Util\Formatting;
@@ -36,12 +37,12 @@ use Doctrine\ORM\QueryBuilder;
class Attachment extends Component class Attachment extends Component
{ {
public function onAddRoute(RouteLoader $r): bool public function onAddRoute(Router $r): bool
{ {
$r->connect('attachment_show', '/object/attachment/{id<\d+>}', [C\Attachment::class, 'attachment_show']); $r->connect('note_attachment_show', '/object/note/{note_id<\d+>}/attachment/{attachment_id<\d+>}', [C\Attachment::class, 'attachmentShowWithNote']);
$r->connect('attachment_view', '/object/attachment/{id<\d+>}/view', [C\Attachment::class, 'attachment_view']); $r->connect('note_attachment_view', '/object/note/{note_id<\d+>}/attachment/{attachment_id<\d+>}/view', [C\Attachment::class, 'attachmentViewWithNote']);
$r->connect('attachment_download', '/object/attachment/{id<\d+>}/download', [C\Attachment::class, 'attachment_download']); $r->connect('note_attachment_download', '/object/note/{note_id<\d+>}/attachment/{attachment_id<\d+>}/download', [C\Attachment::class, 'attachmentDownloadWithNote']);
$r->connect('attachment_thumbnail', '/object/attachment/{id<\d+>}/thumbnail/{size<big|medium|small>}', [C\Attachment::class, 'attachment_thumbnail']); $r->connect('note_attachment_thumbnail', '/object/note/{note_id<\d+>}/attachment/{attachment_id<\d+>}/thumbnail/{size<big|medium|small>}', [C\Attachment::class, 'attachmentThumbnailWithNote']);
return Event::next; return Event::next;
} }
@@ -56,26 +57,34 @@ class Attachment extends Component
return Event::stop; return Event::stop;
} }
public function onNoteDeleteRelated(Note &$note): bool public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
{ {
Cache::delete("note-attachments-{$note->getId()}"); Cache::delete("note-attachments-{$note->getId()}");
E\AttachmentToNote::removeWhereNoteId($note->getId());
foreach ($note->getAttachments() as $attachment) { foreach ($note->getAttachments() as $attachment) {
$attachment->kill(); $attachment->kill();
} }
DB::wrapInTransaction(fn () => E\AttachmentToNote::removeWhereNoteId($note->getId()));
Cache::delete("note-attachments-{$note->getId()}");
return Event::next; return Event::next;
} }
public function onSearchQueryAddJoins(QueryBuilder &$note_qb, QueryBuilder &$actor_qb): bool public function onCollectionQueryAddJoins(QueryBuilder &$note_qb, QueryBuilder &$actor_qb): bool
{ {
$note_qb->leftJoin(E\AttachmentToNote::class, 'attachment_to_note', Expr\Join::WITH, 'note.id = attachment_to_note.note_id'); if (!\in_array('attachment_to_note', $note_qb->getAllAliases())) {
$note_qb->leftJoin(
join: E\AttachmentToNote::class,
alias: 'attachment_to_note',
conditionType: Expr\Join::WITH,
condition: 'note.id = attachment_to_note.note_id',
);
}
return Event::next; return Event::next;
} }
/** /**
* Populate $note_expr with the criteria for looking for notes with attachments * Populate $note_expr with the criteria for looking for notes with attachments
*/ */
public function onSearchCreateExpression(ExpressionBuilder $eb, string $term, ?string $language, ?Actor $actor, &$note_expr, &$actor_expr) public function onCollectionQueryCreateExpression(ExpressionBuilder $eb, string $term, ?string $locale, ?Actor $actor, &$note_expr, &$actor_expr): bool
{ {
$include_term = str_contains($term, ':') ? explode(':', $term)[1] : $term; $include_term = str_contains($term, ':') ? explode(':', $term)[1] : $term;
if (Formatting::startsWith($term, ['note-types:', 'notes-incude:', 'note-filter:'])) { if (Formatting::startsWith($term, ['note-types:', 'notes-incude:', 'note-filter:'])) {

View File

@@ -24,18 +24,18 @@ declare(strict_types = 1);
namespace Component\Attachment\Controller; namespace Component\Attachment\Controller;
use App\Core\Controller; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Log; use App\Entity\Note;
use App\Core\Router\Router;
use Component\Attachment\Entity\AttachmentThumbnail;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
use App\Util\Exception\NoSuchFileException; use App\Util\Exception\NoSuchFileException;
use App\Util\Exception\NotFoundException; use App\Util\Exception\NotFoundException;
use App\Util\Exception\ServerException; use App\Util\Exception\ServerException;
use Component\Attachment\Entity\AttachmentThumbnail;
use Component\Attachment\Entity\AttachmentToNote;
use Symfony\Component\HttpFoundation\HeaderUtils; use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -46,22 +46,28 @@ class Attachment extends Controller
/** /**
* Generic function that handles getting a representation for an attachment * Generic function that handles getting a representation for an attachment
*/ */
private function attachment(int $id, callable $handle) private function attachment(int $attachment_id, Note|int $note, callable $handle)
{ {
if ($id <= 0) { // This should never happen coming from the router, but let's bail if it does $attachment = DB::findOneBy('attachment', ['id' => $attachment_id]);
// @codeCoverageIgnoreStart $note = \is_int($note) ? Note::getById($note) : $note;
Log::critical("Attachment controller called with {$id}, which should not be possible");
// Before anything, two very important things!
// first: ensure this attachment is associated with this note
if (DB::count(AttachmentToNote::class, ['attachment_id' => $attachment->getId(), 'note_id' => $note->getId()]) <= 0) {
throw new ClientException(_m('No such attachment.'), 404); throw new ClientException(_m('No such attachment.'), 404);
// @codeCoverageIgnoreEnd }
} else { // second: ensure proper scope
$res = null; if (!$note->isVisibleTo(Common::actor())) {
if (Event::handle('AttachmentFileInfo', [$id, &$res]) != Event::stop) { throw new ClientException(_m('You don\'t have permissions to view this attachment.'), 401);
// If no one else claims this attachment, use the default representation }
try {
$res = GSFile::getAttachmentFileInfo($id); $res = null;
} catch (NoSuchFileException $e) { if (Event::handle('AttachmentFileInfo', [$attachment, $note, &$res]) !== Event::stop) {
// Continue below // If no one else claims this attachment, use the default representation
} try {
$res = GSFile::getAttachmentFileInfo($attachment_id);
} catch (NoSuchFileException $e) {
// Continue below
} }
} }
@@ -73,6 +79,9 @@ class Attachment extends Controller
throw new ServerException('This attachment is not stored locally.'); throw new ServerException('This attachment is not stored locally.');
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} else { } else {
$res['attachment'] = $attachment;
$res['note'] = $note;
$res['title'] = $attachment->getBestTitle($note);
return $handle($res); return $handle($res);
} }
} }
@@ -81,16 +90,17 @@ class Attachment extends Controller
/** /**
* The page where the attachment and it's info is shown * The page where the attachment and it's info is shown
*/ */
public function attachment_show(Request $request, int $id) public function attachmentShowWithNote(Request $request, int $note_id, int $attachment_id)
{ {
try { try {
$attachment = DB::findOneBy('attachment', ['id' => $id]); return $this->attachment($attachment_id, $note_id, function ($res) use ($note_id, $attachment_id) {
return $this->attachment($id, function ($res) use ($id, $attachment) {
return [ return [
'_template' => '/cards/attachments/show.html.twig', '_template' => 'attachment/view.html.twig',
'download' => Router::url('attachment_download', ['id' => $id]), 'download' => $res['attachment']->getDownloadUrl(note: $note_id),
'attachment' => $attachment, 'title' => $res['title'],
'right_panel_vars' => ['attachment_id' => $id], 'attachment' => $res['attachment'],
'note' => $res['note'],
'right_panel_vars' => ['attachment_id' => $attachment_id, 'note_id' => $note_id],
]; ];
}); });
} catch (NotFoundException) { } catch (NotFoundException) {
@@ -101,27 +111,29 @@ class Attachment extends Controller
/** /**
* Display the attachment inline * Display the attachment inline
*/ */
public function attachment_view(Request $request, int $id) public function attachmentViewWithNote(Request $request, int $note_id, int $attachment_id)
{ {
return $this->attachment( return $this->attachment(
$id, $attachment_id,
$note_id,
fn (array $res) => GSFile::sendFile( fn (array $res) => GSFile::sendFile(
$res['filepath'], $res['filepath'],
$res['mimetype'], $res['mimetype'],
GSFile::ensureFilenameWithProperExtension($res['filename'], $res['mimetype']) ?? $res['filename'], GSFile::ensureFilenameWithProperExtension($res['title'], $res['mimetype']) ?? $res['filename'],
HeaderUtils::DISPOSITION_INLINE, HeaderUtils::DISPOSITION_INLINE,
), ),
); );
} }
public function attachment_download(Request $request, int $id) public function attachmentDownloadWithNote(Request $request, int $note_id, int $attachment_id)
{ {
return $this->attachment( return $this->attachment(
$id, $attachment_id,
$note_id,
fn (array $res) => GSFile::sendFile( fn (array $res) => GSFile::sendFile(
$res['filepath'], $res['filepath'],
$res['mimetype'], $res['mimetype'],
GSFile::ensureFilenameWithProperExtension($res['filename'], $res['mimetype']) ?? $res['filename'], GSFile::ensureFilenameWithProperExtension($res['title'], $res['mimetype']) ?? $res['filename'],
HeaderUtils::DISPOSITION_ATTACHMENT, HeaderUtils::DISPOSITION_ATTACHMENT,
), ),
); );
@@ -130,16 +142,27 @@ class Attachment extends Controller
/** /**
* Controller to produce a thumbnail for a given attachment id * Controller to produce a thumbnail for a given attachment id
* *
* @param int $id Attachment ID * @param int $attachment_id Attachment ID
* *
* @throws \App\Util\Exception\DuplicateFoundException * @throws \App\Util\Exception\DuplicateFoundException
* @throws ClientException * @throws ClientException
* @throws NotFoundException * @throws NotFoundException
* @throws ServerException * @throws ServerException
*/ */
public function attachment_thumbnail(Request $request, int $id, string $size = 'small'): Response public function attachmentThumbnailWithNote(Request $request, int $note_id, int $attachment_id, string $size = 'small'): Response
{ {
$attachment = DB::findOneBy('attachment', ['id' => $id]); $attachment = DB::findOneBy('attachment', ['id' => $attachment_id]);
$note = Note::getById($note_id);
// Before anything, two very important things!
// first: ensure this attachment is associated with this note
if (DB::count(AttachmentToNote::class, ['attachment_id' => $attachment->getId(), 'note_id' => $note->getId()]) <= 0) {
throw new ClientException(_m('No such attachment.'), 404);
}
// second: ensure proper scope
if (!$note->isVisibleTo(Common::actor())) {
throw new ClientException(_m('You don\'t have permissions to view this attachment.'), 401);
}
$crop = Common::config('thumbnail', 'smart_crop'); $crop = Common::config('thumbnail', 'smart_crop');

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -19,7 +21,7 @@
namespace Component\Attachment\Entity; namespace Component\Attachment\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use DateTimeInterface; use DateTimeInterface;
@@ -39,7 +41,7 @@ class ActorToAttachment extends Entity
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $attachment_id; private int $attachment_id;
private int $actor_id; private int $actor_id;
private \DateTimeInterface $modified; private DateTimeInterface $modified;
public function setAttachmentId(int $attachment_id): self public function setAttachmentId(int $attachment_id): self
{ {
@@ -77,10 +79,6 @@ class ActorToAttachment extends Entity
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
/**
* @param int $attachment_id
* @return mixed
*/
public static function removeWhereAttachmentId(int $attachment_id): mixed public static function removeWhereAttachmentId(int $attachment_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -92,11 +90,6 @@ class ActorToAttachment extends Entity
); );
} }
/**
* @param int $actor_id
* @param int $attachment_id
* @return mixed
*/
public static function removeWhere(int $attachment_id, int $actor_id): mixed public static function removeWhere(int $attachment_id, int $actor_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -109,10 +102,6 @@ class ActorToAttachment extends Entity
); );
} }
/**
* @param int $actor_id
* @return mixed
*/
public static function removeWhereActorId(int $actor_id): mixed public static function removeWhereActorId(int $actor_id): mixed
{ {
return DB::dql( return DB::dql(

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
@@ -22,17 +24,18 @@
namespace Component\Attachment\Entity; namespace Component\Attachment\Entity;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
use App\Entity\Note;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Log; use App\Core\Log;
use App\Core\Router\Router; use App\Core\Router;
use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
use App\Util\Exception\DuplicateFoundException; use App\Util\Exception\DuplicateFoundException;
use App\Util\Exception\NoSuchFileException;
use App\Util\Exception\NotFoundException; use App\Util\Exception\NotFoundException;
use App\Util\Exception\ServerException; use App\Util\Exception\ServerException;
use DateTimeInterface; use DateTimeInterface;
@@ -57,13 +60,13 @@ class Attachment extends Entity
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $id; private int $id;
private int $lives = 1; private int $lives = 1;
private ?string $filehash; private ?string $filehash = null;
private ?string $mimetype; private ?string $mimetype = null;
private ?string $filename; private ?string $filename = null;
private ?int $size; private ?int $size = null;
private ?int $width; private ?int $width = null;
private ?int $height; private ?int $height = null;
private DateTimeInterface $modified; private DateTimeInterface $modified;
public function setId(int $id): self public function setId(int $id): self
@@ -77,25 +80,20 @@ class Attachment extends Entity
return $this->id; return $this->id;
} }
/** public function setLives(int $lives): self
* @return int {
*/ $this->lives = $lives;
return $this;
}
public function getLives(): int public function getLives(): int
{ {
return $this->lives; return $this->lives;
} }
/**
* @param int $lives
*/
public function setLives(int $lives): void
{
$this->lives = $lives;
}
public function setFilehash(?string $filehash): self public function setFilehash(?string $filehash): self
{ {
$this->filehash = $filehash; $this->filehash = \is_null($filehash) ? null : mb_substr($filehash, 0, 64);
return $this; return $this;
} }
@@ -106,7 +104,7 @@ class Attachment extends Entity
public function setMimetype(?string $mimetype): self public function setMimetype(?string $mimetype): self
{ {
$this->mimetype = $mimetype; $this->mimetype = \is_null($mimetype) ? null : mb_substr($mimetype, 0, 255);
return $this; return $this;
} }
@@ -117,7 +115,7 @@ class Attachment extends Entity
public function setFilename(?string $filename): self public function setFilename(?string $filename): self
{ {
$this->filename = $filename; $this->filename = \is_null($filename) ? null : mb_substr($filename, 0, 191);
return $this; return $this;
} }
@@ -176,44 +174,36 @@ class Attachment extends Entity
public function getMimetypeMajor(): ?string public function getMimetypeMajor(): ?string
{ {
$mime = $this->getMimetype(); $mime = $this->getMimetype();
return is_null($mime) ? $mime : GSFile::mimetypeMajor($mime); return \is_null($mime) ? $mime : GSFile::mimetypeMajor($mime);
} }
public function getMimetypeMinor(): ?string public function getMimetypeMinor(): ?string
{ {
$mime = $this->getMimetype(); $mime = $this->getMimetype();
return is_null($mime) ? $mime : GSFile::mimetypeMinor($mime); return \is_null($mime) ? $mime : GSFile::mimetypeMinor($mime);
} }
/**
* @return int
*/
public function livesIncrementAndGet(): int public function livesIncrementAndGet(): int
{ {
++$this->lives; ++$this->lives;
return $this->lives; return $this->lives;
} }
/**
* @return int
*/
public function livesDecrementAndGet(): int public function livesDecrementAndGet(): int
{ {
--$this->lives; --$this->lives;
return $this->lives; return $this->lives;
} }
const FILEHASH_ALGO = 'sha256'; public const FILEHASH_ALGO = 'sha256';
/** /**
* Delete a file if safe, removes dependencies, cleanups and flushes * Delete a file if safe, removes dependencies, cleanups and flushes
*
* @return bool
*/ */
public function kill(): bool public function kill(): bool
{ {
if ($this->livesDecrementAndGet() <= 0) { if ($this->livesDecrementAndGet() <= 0) {
return $this->delete(); return DB::wrapInTransaction(fn () => $this->delete());
} }
return true; return true;
} }
@@ -223,7 +213,7 @@ class Attachment extends Entity
*/ */
public function deleteStorage(): bool public function deleteStorage(): bool
{ {
if (!is_null($filepath = $this->getPath())) { if (!\is_null($filepath = $this->getPath())) {
if (file_exists($filepath)) { if (file_exists($filepath)) {
if (@unlink($filepath) === false) { if (@unlink($filepath) === false) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
@@ -234,8 +224,7 @@ class Attachment extends Entity
$this->setFilename(null); $this->setFilename(null);
$this->setSize(null); $this->setSize(null);
// Important not to null neither width nor height // Important not to null neither width nor height
DB::persist($this); DB::wrapInTransaction(fn () => DB::persist($this));
DB::flush();
} }
} else { } else {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
@@ -248,6 +237,8 @@ class Attachment extends Entity
/** /**
* Attachment delete always removes dependencies, cleanups and flushes * Attachment delete always removes dependencies, cleanups and flushes
* WARNING: Wrap this function in a transaction!
*
* @see kill() It's more likely that you want to use that rather than call delete directly * @see kill() It's more likely that you want to use that rather than call delete directly
*/ */
protected function delete(): bool protected function delete(): bool
@@ -261,7 +252,7 @@ class Attachment extends Entity
// Collect files starting with the one associated with this attachment // Collect files starting with the one associated with this attachment
$files = []; $files = [];
if (!is_null($filepath = $this->getPath())) { if (!\is_null($filepath = $this->getPath())) {
$files[] = $filepath; $files[] = $filepath;
} }
@@ -306,25 +297,21 @@ class Attachment extends Entity
/** /**
* TODO: Maybe this isn't the best way of handling titles * TODO: Maybe this isn't the best way of handling titles
* *
* @param null|Note $note
*
* @throws DuplicateFoundException * @throws DuplicateFoundException
* @throws NotFoundException * @throws NotFoundException
* @throws ServerException * @throws ServerException
*
* @return string
*/ */
public function getBestTitle(?Note $note = null): string public function getBestTitle(?Note $note = null): string
{ {
// If we have a note, then the best title is the title itself // If we have a note, then the best title is the title itself
if (!is_null(($note))) { if (!\is_null(($note))) {
$title = Cache::get('attachment-title-' . $this->getId() . '-' . $note->getId(), function () use ($note) { $title = Cache::get('attachment-title-' . $this->getId() . '-' . $note->getId(), function () use ($note) {
try { try {
$attachment_to_note = DB::findOneBy('attachment_to_note', [ $attachment_to_note = DB::findOneBy('attachment_to_note', [
'attachment_id' => $this->getId(), 'attachment_id' => $this->getId(),
'note_id' => $note->getId(), 'note_id' => $note->getId(),
]); ]);
if (!is_null($attachment_to_note->getTitle())) { if (!\is_null($attachment_to_note->getTitle())) {
return $attachment_to_note->getTitle(); return $attachment_to_note->getTitle();
} }
} catch (NotFoundException) { } catch (NotFoundException) {
@@ -332,14 +319,13 @@ class Attachment extends Entity
Event::handle('AttachmentGetBestTitle', [$this, $note, &$title]); Event::handle('AttachmentGetBestTitle', [$this, $note, &$title]);
return $title; return $title;
} }
return null;
}); });
if ($title != null) { if ($title != null) {
return $title; return $title;
} }
} }
// Else // Else
if (!is_null($filename = $this->getFilename())) { if (!\is_null($filename = $this->getFilename())) {
// A filename would do just as well // A filename would do just as well
return $filename; return $filename;
} else { } else {
@@ -353,38 +339,51 @@ class Attachment extends Entity
*/ */
public function getThumbnails() public function getThumbnails()
{ {
return DB::findBy('attachment_thumbnail', ['attachment_id' => $this->id]); return DB::findBy(
AttachmentThumbnail::class,
['attachment_id' => $this->id],
order_by: ['size' => 'ASC', 'mimetype' => 'ASC'],
);
} }
public function getPath() public function getPath()
{ {
$filename = $this->getFilename(); $filename = $this->getFilename();
return is_null($filename) ? null : Common::config('attachments', 'dir') . DIRECTORY_SEPARATOR . $filename; return \is_null($filename) ? null : Common::config('attachments', 'dir') . \DIRECTORY_SEPARATOR . $filename;
} }
public function getUrl(int $type = Router::ABSOLUTE_URL): string public function getUrl(Note|int $note, int $type = Router::ABSOLUTE_URL): string
{ {
return Router::url(id: 'attachment_view', args: ['id' => $this->getId()], type: $type); return Router::url(id: 'note_attachment_view', args: ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId()], type: $type);
}
public function getShowUrl(Note|int $note, int $type = Router::ABSOLUTE_URL): string
{
return Router::url(id: 'note_attachment_show', args: ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId()], type: $type);
}
public function getDownloadUrl(Note|int $note, int $type = Router::ABSOLUTE_URL): string
{
return Router::url(id: 'note_attachment_download', args: ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId()], type: $type);
} }
/** /**
* @param null|string $size
* @param bool $crop
*
* @throws ClientException * @throws ClientException
* @throws NotFoundException * @throws NotFoundException
* @throws ServerException * @throws ServerException
*
* @return AttachmentThumbnail
*/ */
public function getThumbnail(?string $size = null, bool $crop = false): ?AttachmentThumbnail public function getThumbnail(?string $size = null, bool $crop = false): ?AttachmentThumbnail
{ {
return AttachmentThumbnail::getOrCreate(attachment: $this, size: $size, crop: $crop); try {
return AttachmentThumbnail::getOrCreate(attachment: $this, size: $size, crop: $crop);
} catch (NoSuchFileException) {
return null;
}
} }
public function getThumbnailUrl(?string $size = null) public function getThumbnailUrl(Note|int $note, ?string $size = null): string
{ {
return Router::url('attachment_thumbnail', ['id' => $this->getId(), 'size' => $size ?? Common::config('thumbnail', 'default_size')]); return Router::url('note_attachment_thumbnail', ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId(), 'size' => $size ?? Common::config('thumbnail', 'default_size')]);
} }
public static function schemaDef(): array public static function schemaDef(): array
@@ -393,7 +392,7 @@ class Attachment extends Entity
'name' => 'attachment', 'name' => 'attachment',
'fields' => [ 'fields' => [
'id' => ['type' => 'serial', 'not null' => true], 'id' => ['type' => 'serial', 'not null' => true],
'lives' => ['type' => 'int', 'not null' => true, 'description' => 'RefCount'], 'lives' => ['type' => 'int', 'default' => 1, 'not null' => true, 'description' => 'RefCount, starts with 1'],
'filehash' => ['type' => 'varchar', 'length' => 64, 'description' => 'sha256 of the file contents, if the file is stored locally'], 'filehash' => ['type' => 'varchar', 'length' => 64, 'description' => 'sha256 of the file contents, if the file is stored locally'],
'mimetype' => ['type' => 'varchar', 'length' => 255, 'description' => 'resource mime type 127+1+127 as per rfc6838#section-4.2'], 'mimetype' => ['type' => 'varchar', 'length' => 255, 'description' => 'resource mime type 127+1+127 as per rfc6838#section-4.2'],
'filename' => ['type' => 'varchar', 'length' => 191, 'description' => 'file name of resource when available'], 'filename' => ['type' => 'varchar', 'length' => 191, 'description' => 'file name of resource when available'],

View File

@@ -24,12 +24,13 @@ declare(strict_types = 1);
namespace Component\Attachment\Entity; namespace Component\Attachment\Entity;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
use App\Core\Log; use App\Core\Log;
use App\Core\Router\Router; use App\Core\Router;
use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
use App\Util\Exception\NotFoundException; use App\Util\Exception\NotFoundException;
@@ -66,12 +67,11 @@ class AttachmentThumbnail extends Entity
'medium' => self::SIZE_MEDIUM, 'medium' => self::SIZE_MEDIUM,
'big' => self::SIZE_BIG, 'big' => self::SIZE_BIG,
]; ];
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $attachment_id; private int $attachment_id;
private ?string $mimetype; private ?string $mimetype = null;
private int $size = self::SIZE_SMALL; private int $size = 0;
private string $filename; private string $filename;
private int $width; private int $width;
private int $height; private int $height;
@@ -90,7 +90,7 @@ class AttachmentThumbnail extends Entity
public function setMimetype(?string $mimetype): self public function setMimetype(?string $mimetype): self
{ {
$this->mimetype = $mimetype; $this->mimetype = \is_null($mimetype) ? null : mb_substr($mimetype, 0, 129);
return $this; return $this;
} }
@@ -99,20 +99,20 @@ class AttachmentThumbnail extends Entity
return $this->mimetype; return $this->mimetype;
} }
public function getSize(): int
{
return $this->size;
}
public function setSize(int $size): self public function setSize(int $size): self
{ {
$this->size = $size; $this->size = $size;
return $this; return $this;
} }
public function getSize(): int
{
return $this->size;
}
public function setFilename(string $filename): self public function setFilename(string $filename): self
{ {
$this->filename = $filename; $this->filename = mb_substr($filename, 0, 191);
return $this; return $this;
} }
@@ -121,6 +121,28 @@ class AttachmentThumbnail extends Entity
return $this->filename; return $this->filename;
} }
public function setWidth(int $width): self
{
$this->width = $width;
return $this;
}
public function getWidth(): int
{
return $this->width;
}
public function setHeight(int $height): self
{
$this->height = $height;
return $this;
}
public function getHeight(): int
{
return $this->height;
}
public function setModified(DateTimeInterface $modified): self public function setModified(DateTimeInterface $modified): self
{ {
$this->modified = $modified; $this->modified = $modified;
@@ -132,28 +154,6 @@ class AttachmentThumbnail extends Entity
return $this->modified; return $this->modified;
} }
public function getWidth(): int
{
return $this->width;
}
public function setWidth(int $width): self
{
$this->width = $width;
return $this;
}
public function getHeight(): int
{
return $this->height;
}
public function setHeight(int $height): self
{
$this->height = $height;
return $this;
}
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
@@ -180,7 +180,7 @@ class AttachmentThumbnail extends Entity
if (isset($this->attachment) && !\is_null($this->attachment)) { if (isset($this->attachment) && !\is_null($this->attachment)) {
return $this->attachment; return $this->attachment;
} else { } else {
return $this->attachment = DB::findOneBy('attachment', ['id' => $this->attachment_id]); return $this->attachment = DB::findOneBy(Attachment::class, ['id' => $this->attachment_id]);
} }
} }
@@ -205,7 +205,7 @@ class AttachmentThumbnail extends Entity
try { try {
return Cache::get( return Cache::get(
self::getCacheKey($attachment->getId(), $size_int), self::getCacheKey($attachment->getId(), $size_int),
fn () => DB::findOneBy('attachment_thumbnail', ['attachment_id' => $attachment->getId(), 'size' => $size_int]), fn () => DB::findOneBy(self::class, ['attachment_id' => $attachment->getId(), 'size' => $size_int]),
); );
} catch (NotFoundException) { } catch (NotFoundException) {
if (\is_null($attachment->getWidth()) || \is_null($attachment->getHeight())) { if (\is_null($attachment->getWidth()) || \is_null($attachment->getHeight())) {
@@ -214,7 +214,7 @@ class AttachmentThumbnail extends Entity
[$predicted_width, $predicted_height] = self::predictScalingValues($attachment->getWidth(), $attachment->getHeight(), $size, $crop); [$predicted_width, $predicted_height] = self::predictScalingValues($attachment->getWidth(), $attachment->getHeight(), $size, $crop);
if (\is_null($attachment->getPath()) || !file_exists($attachment->getPath())) { if (\is_null($attachment->getPath()) || !file_exists($attachment->getPath())) {
// Before we quit, check if there's any other thumb // Before we quit, check if there's any other thumb
$alternative_thumbs = DB::findBy('attachment_thumbnail', ['attachment_id' => $attachment->getId()]); $alternative_thumbs = DB::findBy(self::class, ['attachment_id' => $attachment->getId()]);
usort($alternative_thumbs, fn ($l, $r) => $r->getSize() <=> $l->getSize()); usort($alternative_thumbs, fn ($l, $r) => $r->getSize() <=> $l->getSize());
if (empty($alternative_thumbs)) { if (empty($alternative_thumbs)) {
throw new NotStoredLocallyException(); throw new NotStoredLocallyException();
@@ -254,14 +254,14 @@ class AttachmentThumbnail extends Entity
} }
} }
public function getPath() public function getPath(): string
{ {
return Common::config('thumbnail', 'dir') . \DIRECTORY_SEPARATOR . $this->getFilename(); return Common::config('thumbnail', 'dir') . \DIRECTORY_SEPARATOR . $this->getFilename();
} }
public function getUrl() public function getUrl(Note|int $note): string
{ {
return Router::url('attachment_thumbnail', ['id' => $this->getAttachmentId(), 'size' => self::sizeIntToStr($this->getSize())]); return Router::url('note_attachment_thumbnail', ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getAttachmentId(), 'size' => self::sizeIntToStr($this->getSize())]);
} }
/** /**
@@ -278,9 +278,10 @@ class AttachmentThumbnail extends Entity
} }
} }
Cache::delete(self::getCacheKey($this->getAttachmentId(), $this->getSize())); Cache::delete(self::getCacheKey($this->getAttachmentId(), $this->getSize()));
DB::remove($this);
if ($flush) { if ($flush) {
DB::flush(); DB::wrapInTransaction(fn () => DB::remove($this));
} else {
DB::remove($this);
} }
} }

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -19,7 +21,7 @@
namespace Component\Attachment\Entity; namespace Component\Attachment\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use DateTimeInterface; use DateTimeInterface;
@@ -37,20 +39,9 @@ class AttachmentToLink extends Entity
{ {
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $attachment_id;
private int $link_id; private int $link_id;
private \DateTimeInterface $modified; private int $attachment_id;
private DateTimeInterface $modified;
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getAttachmentId(): int
{
return $this->attachment_id;
}
public function setLinkId(int $link_id): self public function setLinkId(int $link_id): self
{ {
@@ -63,6 +54,17 @@ class AttachmentToLink extends Entity
return $this->link_id; return $this->link_id;
} }
public function setAttachmentId(int $attachment_id): self
{
$this->attachment_id = $attachment_id;
return $this;
}
public function getAttachmentId(): int
{
return $this->attachment_id;
}
public function setModified(DateTimeInterface $modified): self public function setModified(DateTimeInterface $modified): self
{ {
$this->modified = $modified; $this->modified = $modified;
@@ -77,10 +79,6 @@ class AttachmentToLink extends Entity
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
/**
* @param int $attachment_id
* @return mixed
*/
public static function removeWhereAttachmentId(int $attachment_id): mixed public static function removeWhereAttachmentId(int $attachment_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -92,11 +90,6 @@ class AttachmentToLink extends Entity
); );
} }
/**
* @param int $link_id
* @param int $attachment_id
* @return mixed
*/
public static function removeWhere(int $link_id, int $attachment_id): mixed public static function removeWhere(int $link_id, int $attachment_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -109,10 +102,6 @@ class AttachmentToLink extends Entity
); );
} }
/**
* @param int $link_id
* @return mixed
*/
public static function removeWhereLinkId(int $link_id): mixed public static function removeWhereLinkId(int $link_id): mixed
{ {
return DB::dql( return DB::dql(

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -19,8 +21,7 @@
namespace Component\Attachment\Entity; namespace Component\Attachment\Entity;
use App\Core\Cache; use App\Core\DB;
use App\Core\DB\DB;
use App\Core\Entity; use App\Core\Entity;
use DateTimeInterface; use DateTimeInterface;
@@ -44,8 +45,8 @@ class AttachmentToNote extends Entity
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $attachment_id; private int $attachment_id;
private int $note_id; private int $note_id;
private ?string $title; private ?string $title = null;
private \DateTimeInterface $modified; private DateTimeInterface $modified;
public function setAttachmentId(int $attachment_id): self public function setAttachmentId(int $attachment_id): self
{ {
@@ -94,11 +95,6 @@ class AttachmentToNote extends Entity
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
/**
* @param int $note_id
* @param int $attachment_id
* @return mixed
*/
public static function removeWhere(int $note_id, int $attachment_id): mixed public static function removeWhere(int $note_id, int $attachment_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -111,10 +107,6 @@ class AttachmentToNote extends Entity
); );
} }
/**
* @param int $note_id
* @return mixed
*/
public static function removeWhereNoteId(int $note_id): mixed public static function removeWhereNoteId(int $note_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -126,10 +118,6 @@ class AttachmentToNote extends Entity
); );
} }
/**
* @param int $attachment_id
* @return mixed
*/
public static function removeWhereAttachmentId(int $attachment_id): mixed public static function removeWhereAttachmentId(int $attachment_id): mixed
{ {
return DB::dql( return DB::dql(

View File

@@ -21,10 +21,12 @@ declare(strict_types = 1);
// }}} // }}}
namespace App\Tests\Controller; namespace Component\Attachment\tests\Controller;
use App\Core\DB\DB; use App\Core\DB;
use App\Util\GNUsocialTestCase; use App\Util\GNUsocialTestCase;
use Component\Attachment\Entity\Attachment;
use Component\Attachment\Entity\AttachmentToNote;
class AttachmentTest extends GNUsocialTestCase class AttachmentTest extends GNUsocialTestCase
{ {
@@ -32,31 +34,33 @@ class AttachmentTest extends GNUsocialTestCase
{ {
// This calls static::bootKernel(), and creates a "client" that is acting as the browser // This calls static::bootKernel(), and creates a "client" that is acting as the browser
$client = static::createClient(); $client = static::createClient();
$client->request('GET', '/attachment'); //$client->request('GET', '/attachment');
//$this->assertResponseStatusCodeSame(404);
$client->request('GET', '/object/note/1/attachment/-1');
$this->assertResponseStatusCodeSame(404); $this->assertResponseStatusCodeSame(404);
$client->request('GET', '/attachment/-1'); $client->request('GET', '/object/note/1/attachment/asd');
$this->assertResponseStatusCodeSame(404); $this->assertResponseStatusCodeSame(404);
$client->request('GET', '/attachment/asd'); $client->request('GET', '/object/note/1/attachment/0');
$this->assertResponseStatusCodeSame(404);
$client->request('GET', '/attachment/0');
// In the meantime, throwing ClientException doesn't actually result in the reaching the UI, as it's intercepted // In the meantime, throwing ClientException doesn't actually result in the reaching the UI, as it's intercepted
// by the helpful framework that displays the stack traces and such. This should be easily fixable when we have // by the helpful framework that displays the stack traces and such. This should be easily fixable when we have
// our own error pages // our own error pages
$this->assertSelectorTextContains('.stacktrace', 'ClientException'); $this->assertResponseStatusCodeSame(500); // TODO (exception page) 404
$this->assertSelectorTextContains('.stacktrace', 'No such attachment.');
} }
private function testAttachment(string $suffix = '') private function testAttachment(string $suffix = '')
{ {
$client = static::createClient(); $client = static::createClient();
$id = DB::findOneBy('attachment', ['filehash' => '5d8ee7ead51a28803b4ee5cb2306a0b90b6ba570f1e5bcc2209926f6ab08e7ea'])->getId(); $attachment_id = DB::findOneBy(Attachment::class, ['filehash' => '5d8ee7ead51a28803b4ee5cb2306a0b90b6ba570f1e5bcc2209926f6ab08e7ea'])->getId();
$crawler = $client->request('GET', "/attachment/{$id}{$suffix}"); $note_id = DB::findOneBy(AttachmentToNote::class, ['attachment_id' => $attachment_id])->getNoteId();
$crawler = $client->request('GET', "/object/note/{$note_id}/attachment/{$attachment_id}{$suffix}");
} }
public function testAttachmentShow() public function testAttachmentShow()
{ {
$this->testAttachment(); $this->testAttachment();
$this->assertResponseIsSuccessful(); $this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('figure figcaption', '5d8ee7ead51a28803b4ee5cb2306a0b90b6ba570f1e5bcc2209926f6ab08e7ea'); $this->assertSelectorTextContains('figure figcaption', 'image.jpg');
} }
public function testAttachmentView() public function testAttachmentView()
@@ -65,16 +69,6 @@ class AttachmentTest extends GNUsocialTestCase
$this->assertResponseIsSuccessful(); $this->assertResponseIsSuccessful();
} }
public function testAttachmentViewNotStored()
{
$client = static::createClient();
$last_attachment = DB::findBy('attachment', [], order_by: ['id' => 'DESC'], limit: 1)[0];
$id = $last_attachment->getId() + 1;
$crawler = $client->request('GET', "/attachment/{$id}/view");
$this->assertResponseStatusCodeSame(500); // TODO (exception page) 404
$this->assertSelectorTextContains('.stacktrace', 'ClientException');
}
public function testAttachmentDownload() public function testAttachmentDownload()
{ {
$this->testAttachment('/download'); $this->testAttachment('/download');

View File

@@ -19,15 +19,17 @@ declare(strict_types = 1);
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Tests\Entity; namespace Component\Attachment\tests\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
use Component\Attachment\Entity\AttachmentToNote; use App\Core\Router;
use App\Entity\Note; use App\Entity\Note;
use App\Util\GNUsocialTestCase; use App\Util\GNUsocialTestCase;
use App\Util\TemporaryFile; use App\Util\TemporaryFile;
use Component\Attachment\Entity\AttachmentToNote;
use Component\Conversation\Conversation;
use Jchook\AssertThrows\AssertThrows; use Jchook\AssertThrows\AssertThrows;
use SplFileInfo; use SplFileInfo;
use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\File;
@@ -105,8 +107,9 @@ class AttachmentTest extends GNUsocialTestCase
static::assertSame('Untitled attachment', $attachment->getBestTitle()); static::assertSame('Untitled attachment', $attachment->getBestTitle());
$attachment->setFilename($filename); $attachment->setFilename($filename);
$actor = DB::findOneBy('actor', ['nickname' => 'taken_user']); $actor = DB::findOneBy('actor', ['nickname' => 'taken_user']);
DB::persist($note = Note::create(['actor_id' => $actor->getId(), 'content' => 'attachment: some content', 'content_type' => 'text/plain', 'is_local' => true])); DB::persist($note = Note::create(['actor_id' => $actor->getId(), 'content' => 'attachment: some content', 'content_type' => 'text/plain', 'is_local' => true]));
Conversation::assignLocalConversation($note, null);
DB::persist(AttachmentToNote::create(['attachment_id' => $attachment->getId(), 'note_id' => $note->getId(), 'title' => 'A title'])); DB::persist(AttachmentToNote::create(['attachment_id' => $attachment->getId(), 'note_id' => $note->getId(), 'title' => 'A title']));
DB::flush(); DB::flush();
@@ -118,7 +121,7 @@ class AttachmentTest extends GNUsocialTestCase
static::bootKernel(); static::bootKernel();
$attachment = DB::findBy('attachment', ['mimetype' => 'image/png'], limit: 1)[0]; $attachment = DB::findBy('attachment', ['mimetype' => 'image/png'], limit: 1)[0];
$id = $attachment->getId(); $id = $attachment->getId();
static::assertSame("/attachment/{$id}/view", $attachment->getUrl()); static::assertSame("/object/note/42/attachment/{$id}/view", $attachment->getUrl(note: 42, type: Router::ABSOLUTE_PATH));
} }
public function testMimetype() public function testMimetype()

View File

@@ -19,13 +19,14 @@ declare(strict_types = 1);
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Tests\Entity; namespace Component\Attachment\tests\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use Component\Attachment\Entity\AttachmentThumbnail;
use App\Util\Exception\NotStoredLocallyException; use App\Util\Exception\NotStoredLocallyException;
use App\Util\GNUsocialTestCase; use App\Util\GNUsocialTestCase;
use Component\Attachment\Entity\Attachment;
use Component\Attachment\Entity\AttachmentThumbnail;
use Functional as F; use Functional as F;
use Jchook\AssertThrows\AssertThrows; use Jchook\AssertThrows\AssertThrows;
use SplFileInfo; use SplFileInfo;
@@ -42,9 +43,9 @@ class AttachmentThumbnailTest extends GNUsocialTestCase
$file = new SplFileInfo(INSTALLDIR . '/tests/sample-uploads/attachment-lifecycle-target.jpg'); $file = new SplFileInfo(INSTALLDIR . '/tests/sample-uploads/attachment-lifecycle-target.jpg');
$hash = null; $hash = null;
Event::handle('HashFile', [$file->getPathname(), &$hash]); Event::handle('HashFile', [$file->getPathname(), &$hash]);
$attachment = DB::findOneBy('attachment', ['filehash' => $hash]); $attachment = DB::findOneBy(Attachment::class, ['filehash' => $hash]);
$thumbs = [ $expected = [
AttachmentThumbnail::getOrCreate($attachment, 'small', crop: false), AttachmentThumbnail::getOrCreate($attachment, 'small', crop: false),
AttachmentThumbnail::getOrCreate($attachment, 'medium', crop: false), AttachmentThumbnail::getOrCreate($attachment, 'medium', crop: false),
$thumb = AttachmentThumbnail::getOrCreate($attachment, 'big', crop: false), $thumb = AttachmentThumbnail::getOrCreate($attachment, 'big', crop: false),
@@ -54,21 +55,29 @@ class AttachmentThumbnailTest extends GNUsocialTestCase
$thumb->setAttachment(null); $thumb->setAttachment(null);
static::assertSame($attachment, $thumb->getAttachment()); static::assertSame($attachment, $thumb->getAttachment());
$sort = fn ($l, $r) => [$l->getWidth(), $l->getHeight()] <=> [$r->getWidth(), $r->getHeight()]; $actual = $attachment->getThumbnails();
$at_thumbs = F\sort($attachment->getThumbnails(), $sort); static::assertSame(\count($expected), \count($actual));
static::assertSame($thumbs, $at_thumbs); foreach ($expected as $e) {
array_pop($thumbs); $a = array_shift($actual);
$thumb->delete(flush: true); static::assertObjectEquals($e, $a);
$at_thumbs = F\sort($attachment->getThumbnails(), $sort); }
static::assertSame($thumbs, $at_thumbs);
array_pop($expected);
$thumb->delete();
$actual = $attachment->getThumbnails();
static::assertSame(\count($expected), \count($actual));
foreach ($expected as $e) {
$a = array_shift($actual);
static::assertObjectEquals($e, $a);
}
$attachment->deleteStorage(); $attachment->deleteStorage();
foreach (array_reverse($thumbs) as $t) { foreach (array_reverse($attachment->getThumbnails()) as $t) {
// Since we still have thumbnails, those will be used as the new thumbnail, even though we don't have the original // Since we still have thumbnails, those will be used as the new thumbnail, even though we don't have the original
$new = AttachmentThumbnail::getOrCreate($attachment, 'big', crop: false); $new = AttachmentThumbnail::getOrCreate($attachment, 'big', crop: false);
static::assertSame([$t->getFilename(), $t->getSize()], [$new->getFilename(), $new->getSize()]); static::assertSame([$t->getFilename(), $t->getSize()], [$new->getFilename(), $new->getSize()]);
$t->delete(flush: true); $t->delete();
} }
// Since the backed storage was deleted and we don't have any more previous thumnbs, we can't generate another thumbnail // Since the backed storage was deleted and we don't have any more previous thumnbs, we can't generate another thumbnail
@@ -159,10 +168,10 @@ class AttachmentThumbnailTest extends GNUsocialTestCase
public function testGetUrl() public function testGetUrl()
{ {
parent::bootKernel(); parent::bootKernel();
$attachment = DB::findBy('attachment', ['mimetype' => 'image/png'], limit: 1)[0]; $attachment = DB::findBy(Attachment::class, ['mimetype' => 'image/png'], limit: 1)[0];
$thumb = AttachmentThumbnail::getOrCreate($attachment, 'big', crop: false); $thumb = AttachmentThumbnail::getOrCreate($attachment, 'big', crop: false);
$id = $attachment->getId(); $id = $attachment->getId();
$url = "/attachment/{$id}/thumbnail/big"; $expected = "/object/note/42/attachment/{$id}/thumbnail/big";
static::assertSame($url, $thumb->getUrl()); static::assertSame($expected, $thumb->getUrl(note: 42));
} }
} }

View File

@@ -22,13 +22,14 @@ declare(strict_types = 1);
namespace Component\Avatar; namespace Component\Avatar;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Core\Router\Router;
use App\Util\Common; use App\Util\Common;
use Component\Attachment\Entity\Attachment;
use Component\Attachment\Entity\AttachmentThumbnail;
use Component\Avatar\Controller as C; use Component\Avatar\Controller as C;
use Component\Avatar\Exception\NoAvatarException; use Component\Avatar\Exception\NoAvatarException;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -39,10 +40,10 @@ class Avatar extends Component
{ {
} }
public function onAddRoute(RouteLoader $r): bool public function onAddRoute(Router $r): bool
{ {
$r->connect('avatar_actor', '/actor/{actor_id<\d+>}/avatar/{size<full|big|medium|small>?full}', [Controller\Avatar::class, 'avatar_view']); $r->connect('avatar_actor', '/actor/{actor_id<\d+>}/avatar/{size<full|big|medium|small>?medium}', [Controller\Avatar::class, 'avatar_view']);
$r->connect('avatar_default', '/avatar/default/{size<full|big|medium|small>?full}', [Controller\Avatar::class, 'default_avatar_view']); $r->connect('avatar_default', '/avatar/default/{size<full|big|medium|small>?medium}', [Controller\Avatar::class, 'default_avatar_view']);
$r->connect('avatar_settings', '/settings/avatar', [Controller\Avatar::class, 'settings_avatar']); $r->connect('avatar_settings', '/settings/avatar', [Controller\Avatar::class, 'settings_avatar']);
return Event::next; return Event::next;
} }
@@ -102,7 +103,7 @@ class Avatar extends Component
/** /**
* Get the cached avatar associated with the given Actor id, or the current user if not given * Get the cached avatar associated with the given Actor id, or the current user if not given
*/ */
public static function getUrl(int $actor_id, string $size = 'full', int $type = Router::ABSOLUTE_PATH): string public static function getUrl(int $actor_id, string $size = 'medium', int $type = Router::ABSOLUTE_PATH): string
{ {
try { try {
return self::getAvatar($actor_id)->getUrl($size, $type); return self::getAvatar($actor_id)->getUrl($size, $type);
@@ -111,13 +112,13 @@ class Avatar extends Component
} }
} }
public static function getDimensions(int $actor_id, string $size = 'full') public static function getDimensions(int $actor_id, string $size = 'medium')
{ {
try { try {
$attachment = self::getAvatar($actor_id)->getAttachment(); $attachment = self::getAvatar($actor_id)->getAttachment();
return ['width' => $attachment->getWidth(), 'height' => $attachment->getHeight()]; return ['width' => (int) $attachment->getWidth(), 'height' => (int) $attachment->getHeight()];
} catch (NoAvatarException) { } catch (NoAvatarException) {
return ['width' => Common::config('thumbnail', 'small'), 'height' => Common::config('thumbnail', 'small')]; return ['width' => (int) (Common::config('thumbnail', 'small')), 'height' => (int) (Common::config('thumbnail', 'small'))];
} }
} }
@@ -127,7 +128,7 @@ class Avatar extends Component
* Returns the avatar file's hash, mimetype, title and path. * Returns the avatar file's hash, mimetype, title and path.
* Ensures exactly one cached value exists * Ensures exactly one cached value exists
*/ */
public static function getAvatarFileInfo(int $actor_id, string $size = 'full'): array public static function getAvatarFileInfo(int $actor_id, string $size = 'medium'): array
{ {
$res = Cache::get( $res = Cache::get(
"avatar-file-info-{$actor_id}-{$size}", "avatar-file-info-{$actor_id}-{$size}",
@@ -151,8 +152,12 @@ class Avatar extends Component
'title' => 'default_avatar.svg', 'title' => 'default_avatar.svg',
]; ];
} else { } else {
$res = $res[0]; // A user must always only have one avatar. $res = $res[0]; // A user must always only have one avatar.
$res['filepath'] = DB::findOneBy('attachment', ['id' => $res['id']])->getPath(); if ($size === 'full') {
$res['filepath'] = Attachment::getByPK(['id' => $res['id']])->getPath();
} else {
$res['filepath'] = AttachmentThumbnail::getOrCreate(Attachment::getByPK(['id' => $res['id']]), $size)->getPath();
}
return $res; return $res;
} }
} }

View File

@@ -24,7 +24,7 @@ declare(strict_types = 1);
namespace Component\Avatar\Controller; namespace Component\Avatar\Controller;
use App\Core\Controller; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\Form; use App\Core\Form;
use App\Core\GSFile; use App\Core\GSFile;
@@ -33,7 +33,6 @@ use function App\Core\I18n\_m;
use App\Core\Log; use App\Core\Log;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
use App\Util\Exception\NotFoundException;
use App\Util\TemporaryFile; use App\Util\TemporaryFile;
use Component\Avatar\Entity\Avatar as AvatarEntity; use Component\Avatar\Entity\Avatar as AvatarEntity;
use Exception; use Exception;
@@ -57,13 +56,8 @@ class Avatar extends Controller
*/ */
public function avatar_view(Request $request, int $actor_id, string $size): Response public function avatar_view(Request $request, int $actor_id, string $size): Response
{ {
switch ($size) { $res = \Component\Avatar\Avatar::getAvatarFileInfo($actor_id, $size);
case 'full': return M::sendFile($res['filepath'], $res['mimetype'], $res['title']);
$res = \Component\Avatar\Avatar::getAvatarFileInfo($actor_id);
return M::sendFile($res['filepath'], $res['mimetype'], $res['title']);
default:
throw new Exception('Not implemented');
}
} }
/** /**
@@ -85,15 +79,14 @@ class Avatar extends Controller
$user = Common::user(); $user = Common::user();
$actor_id = $user->getId(); $actor_id = $user->getId();
if ($data['remove'] == true) { if ($data['remove'] == true) {
try { if (\is_null($avatar = DB::findOneBy(AvatarEntity::class, ['actor_id' => $actor_id], return_null: true))) {
$avatar = DB::findOneBy('avatar', ['actor_id' => $actor_id]); $form->addError(new FormError(_m('No avatar set, so cannot delete.')));
} else {
$avatar->delete(); $avatar->delete();
Event::handle('AvatarUpdate', [$user->getId()]);
} catch (NotFoundException) {
$form->addError(new FormError(_m('No avatar set, so cannot delete')));
} }
} else { } else {
$attachment = null; $attachment = null;
$title = $data['avatar']?->getClientOriginalName() ?? null;
if (isset($data['hidden'])) { if (isset($data['hidden'])) {
// Cropped client side // Cropped client side
$matches = []; $matches = [];
@@ -113,15 +106,18 @@ class Avatar extends Controller
$file = $data['avatar']; $file = $data['avatar'];
$attachment = GSFile::storeFileAsAttachment($file); $attachment = GSFile::storeFileAsAttachment($file);
} else { } else {
throw new ClientException('Invalid form'); throw new ClientException(_m('Invalid form.'));
} }
// Delete current avatar if there's one // Delete current avatar if there's one
$avatar = DB::find('avatar', ['actor_id' => $actor_id]); if (!\is_null($avatar = DB::findOneBy(AvatarEntity::class, ['actor_id' => $actor_id], return_null: true))) {
$avatar?->delete(); $avatar->delete();
}
DB::persist($attachment); DB::persist($attachment);
// Can only get new id after inserting DB::persist(AvatarEntity::create([
DB::flush(); 'actor_id' => $actor_id,
DB::persist(AvatarEntity::create(['actor_id' => $actor_id, 'attachment_id' => $attachment->getId()])); 'attachment_id' => $attachment->getId(),
'title' => $title,
]));
DB::flush(); DB::flush();
Event::handle('AvatarUpdate', [$user->getId()]); Event::handle('AvatarUpdate', [$user->getId()]);
} }

View File

@@ -24,11 +24,13 @@ declare(strict_types = 1);
namespace Component\Avatar\Entity; namespace Component\Avatar\Entity;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Router\Router; use App\Core\Event;
use Component\Attachment\Entity\Attachment; use App\Core\Router;
use App\Util\Common; use App\Util\Common;
use Component\Attachment\Entity\Attachment;
use Component\Attachment\Entity\AttachmentThumbnail;
use DateTimeInterface; use DateTimeInterface;
/** /**
@@ -51,7 +53,7 @@ class Avatar extends Entity
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $actor_id; private int $actor_id;
private int $attachment_id; private int $attachment_id;
private ?string $title; private ?string $title = null;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
@@ -77,16 +79,17 @@ class Avatar extends Entity
return $this->attachment_id; return $this->attachment_id;
} }
public function setTitle(?string $title): self
{
$this->title = \is_null($title) ? null : mb_substr($title, 0, 191);
return $this;
}
public function getTitle(): ?string public function getTitle(): ?string
{ {
return $this->title; return $this->title;
} }
public function setTitle(?string $title): void
{
$this->title = $title;
}
public function setCreated(DateTimeInterface $created): self public function setCreated(DateTimeInterface $created): self
{ {
$this->created = $created; $this->created = $created;
@@ -114,7 +117,7 @@ class Avatar extends Entity
private ?Attachment $attachment = null; private ?Attachment $attachment = null;
public function getUrl(string $size = 'full', int $type = Router::ABSOLUTE_PATH): string public function getUrl(string $size = 'medium', int $type = Router::ABSOLUTE_PATH): string
{ {
$actor_id = $this->getActorId(); $actor_id = $this->getActorId();
return Cache::get("avatar-url-{$actor_id}-{$size}-{$type}", fn () => Router::url('avatar_actor', ['actor_id' => $actor_id, 'size' => $size], $type)); return Cache::get("avatar-url-{$actor_id}-{$size}-{$type}", fn () => Router::url('avatar_actor', ['actor_id' => $actor_id, 'size' => $size], $type));
@@ -122,10 +125,15 @@ class Avatar extends Entity
public function getAttachment(): Attachment public function getAttachment(): Attachment
{ {
$this->attachment ??= DB::findOneBy('attachment', ['id' => $this->attachment_id]); $this->attachment ??= DB::findOneBy('attachment', ['id' => $this->getAttachmentId()]);
return $this->attachment; return $this->attachment;
} }
public function getAttachmentThumbnail(string $size): ?AttachmentThumbnail
{
return AttachmentThumbnail::getOrCreate($this->getAttachment(), $size);
}
public static function getFilePathStatic(string $filename): string public static function getFilePathStatic(string $filename): string
{ {
return Common::config('avatar', 'dir') . $filename; return Common::config('avatar', 'dir') . $filename;
@@ -141,10 +149,11 @@ class Avatar extends Entity
*/ */
public function delete(): bool public function delete(): bool
{ {
DB::remove($this); $actor_id = $this->getActorId();
$attachment = $this->getAttachment(); $attachment = $this->getAttachment();
DB::wrapInTransaction(fn () => DB::removeBy(static::class, ['actor_id' => $actor_id]));
$attachment->kill(); $attachment->kill();
DB::flush(); Event::handle('AvatarUpdate', [$actor_id]);
return true; return true;
} }

View File

@@ -44,12 +44,12 @@ class ForeignLink
private int $user_id; private int $user_id;
private int $foreign_id; private int $foreign_id;
private int $service; private int $service;
private ?string $credentials; private ?string $credentials = null;
private int $noticesync = 1; private int $noticesync = 1;
private int $friendsync = 2; private int $friendsync = 2;
private int $profilesync = 1; private int $profilesync = 1;
private ?DateTimeInterface $last_noticesync; private ?DateTimeInterface $last_noticesync = null;
private ?DateTimeInterface $last_friendsync; private ?DateTimeInterface $last_friendsync = null;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
@@ -88,7 +88,7 @@ class ForeignLink
public function setCredentials(?string $credentials): self public function setCredentials(?string $credentials): self
{ {
$this->credentials = $credentials; $this->credentials = \is_null($credentials) ? null : mb_substr($credentials, 0, 191);
return $this; return $this;
} }

View File

@@ -43,7 +43,7 @@ class ForeignService
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $id; private int $id;
private string $name; private string $name;
private ?string $description; private ?string $description = null;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
@@ -60,7 +60,7 @@ class ForeignService
public function setName(string $name): self public function setName(string $name): self
{ {
$this->name = $name; $this->name = mb_substr($name, 0, 32);
return $this; return $this;
} }
@@ -71,7 +71,7 @@ class ForeignService
public function setDescription(?string $description): self public function setDescription(?string $description): self
{ {
$this->description = $description; $this->description = \is_null($description) ? null : mb_substr($description, 0, 191);
return $this; return $this;
} }

View File

@@ -44,7 +44,7 @@ class ForeignUser
private int $id; private int $id;
private int $service; private int $service;
private string $uri; private string $uri;
private ?string $nickname; private ?string $nickname = null;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
@@ -72,7 +72,7 @@ class ForeignUser
public function setUri(string $uri): self public function setUri(string $uri): self
{ {
$this->uri = $uri; $this->uri = mb_substr($uri, 0, 191);
return $this; return $this;
} }
@@ -83,7 +83,7 @@ class ForeignUser
public function setNickname(?string $nickname): self public function setNickname(?string $nickname): self
{ {
$this->nickname = $nickname; $this->nickname = \is_null($nickname) ? null : mb_substr($nickname, 0, 191);
return $this; return $this;
} }

View File

@@ -0,0 +1,232 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Circle;
use App\Core\Cache;
use App\Core\DB;
use App\Core\Event;
use function App\Core\I18n\_m;
use App\Core\Modules\Component;
use App\Core\Router;
use App\Entity\Actor;
use App\Entity\Feed;
use App\Entity\LocalUser;
use App\Util\Nickname;
use Component\Circle\Controller as CircleController;
use Component\Circle\Entity\ActorCircle;
use Component\Circle\Entity\ActorCircleSubscription;
use Component\Circle\Entity\ActorTag;
use Component\Collection\Util\MetaCollectionTrait;
use Component\Tag\Tag;
use Functional as F;
use Symfony\Component\HttpFoundation\Request;
/**
* Component responsible for handling and representing ActorCircles and ActorTags
*
* @author Hugo Sales <hugo@hsal.es>
* @author Phablulo <phablulo@gmail.com>
* @author Diogo Peralta Cordeiro <@diogo.site>
* @copyright 2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Circle extends Component
{
use MetaCollectionTrait;
public const TAG_CIRCLE_REGEX = '/' . Nickname::BEFORE_MENTIONS . '@#([\pL\pN_\-\.]{1,64})/';
protected const SLUG = 'circle';
protected const PLURAL_SLUG = 'circles';
public function onAddRoute(Router $r): bool
{
$r->connect('actor_circle_view_by_circle_id', '/circle/{circle_id<\d+>}', [CircleController\Circle::class, 'circleById']);
// View circle members by (tagger id or nickname) and tag
$r->connect('actor_circle_view_by_circle_tagger_tag', '/circle/actor/{tagger_id<\d+>/{tag<' . Tag::TAG_SLUG_REGEX . '>}}', [CircleController\Circle::class, 'circleByTaggerIdAndTag']);
$r->connect('actor_circle_view_by_circle_tagger_tag', '/circle/@{nickname<' . Nickname::DISPLAY_FMT . '>}/{tag<' . Tag::TAG_SLUG_REGEX . '>}', [CircleController\Circle::class, 'circleByTaggerNicknameAndTag']);
// View all circles by actor id or nickname
$r->connect(
id: 'actor_circles_view_by_actor_id',
uri_path: '/actor/{tag<' . Tag::TAG_SLUG_REGEX . '>}/circles',
target: [CircleController\Circles::class, 'collectionsViewByActorId'],
);
$r->connect(
id: 'actor_circles_view_by_nickname',
uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/circles',
target: [CircleController\Circles::class, 'collectionsViewByActorNickname'],
);
$r->connect('actor_circle_view_feed_by_circle_id', '/circle/{circle_id<\d+>}/feed', [CircleController\Circles::class, 'feedByCircleId']);
// View circle feed by (tagger id or nickname) and tag
$r->connect('actor_circle_view_feed_by_circle_tagger_tag', '/circle/actor/{tagger_id<\d+>/{tag<' . Tag::TAG_SLUG_REGEX . '>}}/feed', [CircleController\Circles::class, 'feedByTaggerIdAndTag']);
$r->connect('actor_circle_view_feed_by_circle_tagger_tag', '/circle/@{nickname<' . Nickname::DISPLAY_FMT . '>}/{tag<' . Tag::TAG_SLUG_REGEX . '>}/feed', [CircleController\Circles::class, 'feedByTaggerNicknameAndTag']);
return Event::next;
}
public static function cacheKeys(string $tag_single_or_multi): array
{
return [
'actor_single' => "actor-tag-feed-{$tag_single_or_multi}",
'actor_multi' => "actor-tags-feed-{$tag_single_or_multi}",
];
}
public function onPopulateSettingsTabs(Request $request, string $section, array &$tabs): bool
{
if ($section === 'profile' && \in_array($request->get('_route'), ['person_actor_settings', 'group_actor_settings'])) {
$tabs[] = [
'title' => _m('Self tags'),
'desc' => _m('Add or remove tags to this actor'),
'id' => 'settings-self-tags',
'controller' => CircleController\SelfTagsSettings::settingsSelfTags($request, Actor::getById((int) $request->get('id')), 'settings-self-tags-details'),
];
}
return Event::next;
}
public function onPostingFillTargetChoices(Request $request, Actor $actor, array &$targets): bool
{
$circles = $actor->getCircles();
foreach ($circles as $circle) {
$tag = $circle->getTag();
$targets["#{$tag}"] = $tag;
}
return Event::next;
}
// Meta Collection -------------------------------------------------------------------
private function getActorIdFromVars(array $vars): int
{
$id = $vars['request']->get('id', null);
if ($id) {
return (int) $id;
}
$nick = $vars['request']->get('nickname');
$user = LocalUser::getByNickname($nick);
return $user->getId();
}
public static function createCircle(Actor|int $tagger_id, string $tag): int
{
$tagger_id = \is_int($tagger_id) ? $tagger_id : $tagger_id->getId();
$circle = ActorCircle::create([
'tagger' => $tagger_id,
'tag' => $tag,
'description' => null, // TODO
'private' => false, // TODO
]);
DB::persist($circle);
Cache::delete(Actor::cacheKeys($tagger_id)['circles']);
return $circle->getId();
}
protected function createCollection(Actor $owner, array $vars, string $name)
{
$this->createCircle($owner, $name);
DB::persist(ActorTag::create([
'tagger' => $owner->getId(),
'tagged' => self::getActorIdFromVars($vars),
'tag' => $name,
]));
}
protected function removeItem(Actor $owner, array $vars, $items, array $collections)
{
$tagger_id = $owner->getId();
$tagged_id = $this->getActorIdFromVars($vars);
$circles_to_remove_tagged_from = DB::findBy(ActorCircle::class, ['id' => $items]);
foreach ($circles_to_remove_tagged_from as $circle) {
DB::removeBy(ActorCircleSubscription::class, ['actor_id' => $tagged_id, 'circle_id' => $circle->getId()]);
}
$tags = F\map($circles_to_remove_tagged_from, fn ($x) => $x->getTag());
foreach ($tags as $tag) {
DB::removeBy(ActorTag::class, ['tagger' => $tagger_id, 'tagged' => $tagged_id, 'tag' => $tag]);
}
Cache::delete(Actor::cacheKeys($tagger_id)['circles']);
}
protected function addItem(Actor $owner, array $vars, $items, array $collections)
{
$tagger_id = $owner->getId();
$tagged_id = $this->getActorIdFromVars($vars);
$circles_to_add_tagged_to = DB::findBy(ActorCircle::class, ['id' => $items]);
foreach ($circles_to_add_tagged_to as $circle) {
DB::persist(ActorCircleSubscription::create(['actor_id' => $tagged_id, 'circle_id' => $circle->getId()]));
}
$tags = F\map($circles_to_add_tagged_to, fn ($x) => $x->getTag());
foreach ($tags as $tag) {
DB::persist(ActorTag::create(['tagger' => $tagger_id, 'tagged' => $tagged_id, 'tag' => $tag]));
}
Cache::delete(Actor::cacheKeys($tagger_id)['circles']);
}
/**
* @see MetaCollectionPlugin->shouldAddToRightPanel
*/
protected function shouldAddToRightPanel(Actor $user, $vars, Request $request): bool
{
return \in_array($vars['path'], ['actor_view_nickname', 'actor_view_id']);
}
/**
* Retrieves an array of Collections owned by an Actor.
* In this case, Collections of those within Actor's own circle of Actors, aka ActorCircle.
*
* Differs from the overwritten method in MetaCollectionsTrait, since retrieved Collections come from the $owner
* itself, and from every Actor that is a part of its ActorCircle.
*
* @param Actor $owner the Actor, and by extension its own circle of Actors
* @param null|array $vars Page vars sent by AppendRightPanelBlock event
* @param bool $ids_only true if only the Collections ids are to be returned
*/
protected function getCollectionsBy(Actor $owner, ?array $vars = null, bool $ids_only = false): array
{
$tagged_id = !\is_null($vars) ? $this->getActorIdFromVars($vars) : null;
$circles = \is_null($tagged_id) ? $owner->getCircles() : F\select($owner->getCircles(), function ($x) use ($tagged_id) {
foreach ($x->getActorTags() as $at) {
if ($at->getTagged() === $tagged_id) {
return true;
}
}
return false;
});
return $ids_only ? array_map(fn ($x) => $x->getId(), $circles) : $circles;
}
public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering)
{
DB::persist(Feed::create([
'actor_id' => $actor_id,
'url' => Router::url($route = 'actor_circles_view_by_nickname', ['nickname' => $user->getNickname()]),
'route' => $route,
'title' => _m('Circles'),
'ordering' => $ordering++,
]));
return Event::next;
}
}

View File

@@ -0,0 +1,69 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Circle\Controller;
use function App\Core\I18n\_m;
use App\Entity\LocalUser;
use App\Util\Exception\ClientException;
use Component\Circle\Entity\ActorCircle;
use Component\Collection\Util\Controller\CircleController;
class Circle extends CircleController
{
/**
* Render an existing ActorCircle with the given id as a Collection of Actors
*
* @param ActorCircle|int $circle_id the desired ActorCircle id
*
* @throws \App\Util\Exception\ServerException
* @throws ClientException
*/
public function circleById(int|ActorCircle $circle_id): array
{
$circle = \is_int($circle_id) ? ActorCircle::getByPK(['id' => $circle_id]) : $circle_id;
unset($circle_id);
if (\is_null($circle)) {
throw new ClientException(_m('No such circle.'), 404);
} else {
return [
'_template' => 'collection/actors.html.twig',
'title' => _m('Circle'),
'empty_message' => _m('No members.'),
'sort_form_fields' => [],
'page' => $this->int('page') ?? 1,
'actors' => $circle->getTaggedActors(),
];
}
}
public function circleByTaggerIdAndTag(int $tagger_id, string $tag): array
{
return $this->circleById(ActorCircle::getByPK(['tagger' => $tagger_id, 'tag' => $tag]));
}
public function circleByTaggerNicknameAndTag(string $tagger_nickname, string $tag): array
{
return $this->circleById(ActorCircle::getByPK(['tagger' => LocalUser::getByNickname($tagger_nickname)->getId(), 'tag' => $tag]));
}
}

View File

@@ -0,0 +1,107 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Circle\Controller;
use App\Core\Cache;
use App\Core\DB;
use App\Core\Router;
use App\Entity\Actor;
use App\Entity\LocalUser;
use Component\Circle\Entity\ActorCircle;
use Component\Collection\Util\Controller\MetaCollectionController;
class Circles extends MetaCollectionController
{
protected const SLUG = 'circle';
protected const PLURAL_SLUG = 'circles';
protected string $page_title = 'Actor circles';
public function createCollection(int $owner_id, string $name)
{
return \Component\Circle\Circle::createCircle($owner_id, $name);
}
public function getCollectionUrl(int $owner_id, ?string $owner_nickname, int $collection_id): string
{
return Router::url(
'actor_circle_view_by_circle_id',
['circle_id' => $collection_id],
);
}
public function getCollectionItems(int $owner_id, $collection_id): array
{
$notes = []; // TODO: Use Feed::query
return [
'_template' => 'collection/notes.html.twig',
'notes' => $notes,
];
}
public function feedByCircleId(int $circle_id)
{
// Owner id isn't used
return $this->getCollectionItems(0, $circle_id);
}
public function feedByTaggerIdAndTag(int $tagger_id, string $tag)
{
// Owner id isn't used
$circle_id = ActorCircle::getByPK(['tagger' => $tagger_id, 'tag' => $tag])->getId();
return $this->getCollectionItems($tagger_id, $circle_id);
}
public function feedByTaggerNicknameAndTag(string $tagger_nickname, string $tag)
{
$tagger_id = LocalUser::getByNickname($tagger_nickname)->getId();
$circle_id = ActorCircle::getByPK(['tagger' => $tagger_id, 'tag' => $tag])->getId();
return $this->getCollectionItems($tagger_id, $circle_id);
}
public function getCollectionsByActorId(int $owner_id): array
{
return DB::findBy(ActorCircle::class, ['tagger' => $owner_id], order_by: ['id' => 'desc']);
}
public function getCollectionBy(int $owner_id, int $collection_id): ActorCircle
{
return DB::findOneBy(ActorCircle::class, ['id' => $collection_id, 'actor_id' => $owner_id]);
}
public function setCollectionName(int $actor_id, string $actor_nickname, ActorCircle $collection, string $name)
{
foreach ($collection->getActorTags(db_reference: true) as $at) {
$at->setTag($name);
}
$collection->setTag($name);
Cache::delete(Actor::cacheKeys($actor_id)['circles']);
}
public function removeCollection(int $actor_id, string $actor_nickname, ActorCircle $collection)
{
foreach ($collection->getActorTags(db_reference: true) as $at) {
DB::remove($at);
}
DB::remove($collection);
Cache::delete(Actor::cacheKeys($actor_id)['circles']);
}
}

View File

@@ -0,0 +1,118 @@
<?php
declare(strict_types = 1);
namespace Component\Circle\Controller;
use App\Core\Cache;
use App\Core\Controller;
use App\Core\DB;
use function App\Core\I18n\_m;
use App\Entity as E;
use App\Util\Common;
use App\Util\Exception\ClientException;
use App\Util\Exception\RedirectException;
use Component\Circle\Entity\ActorCircle;
use Component\Circle\Entity\ActorTag;
use Component\Circle\Form\SelfTagsForm;
use Component\Tag\Tag as CompTag;
use Symfony\Component\Form\SubmitButton;
use Symfony\Component\HttpFoundation\Request;
class SelfTagsSettings extends Controller
{
/**
* Generic settings page for an Actor's self tags
* TODO: We should have $actor->setSelfTags(), $actor->addSelfTags(), $actor->removeSelfTags()
*/
public static function settingsSelfTags(Request $request, E\Actor $target, string $details_id)
{
$actor = Common::actor();
if (!$actor->canModerate($target)) {
throw new ClientException(_m('You don\'t have enough permissions to edit {nickname}\'s settings', ['{nickname}' => $target->getNickname()]));
}
$actor_self_tags = $target->getSelfTags();
[$add_form, $existing_form] = SelfTagsForm::handleTags(
$request,
$actor_self_tags,
handle_new: /**
* Handle adding tags
*/
function ($form) use ($request, $target, $details_id) {
$data = $form->getData();
$tags = $data['new-tags'];
foreach ($tags as $tag) {
$tag = CompTag::sanitize($tag);
[$actor_tag, $actor_tag_existed] = ActorTag::checkExistingAndCreateOrUpdate([
'tagger' => $target->getId(), // self tag means tagger = tagger in ActorTag
'tagged' => $target->getId(),
'tag' => $tag,
]);
if (!$actor_tag_existed) {
DB::persist($actor_tag);
// Try to find the self-tag circle
$actor_circle = DB::findOneBy(
ActorCircle::class,
[
'tagger' => null, // Self-tag circle
'tag' => $tag,
],
return_null: true,
);
// It is the first time someone uses this self-tag!
if (\is_null($actor_circle)) {
DB::persist(ActorCircle::create([
'tagger' => null, // Self-tag circle
'tag' => $tag,
'private' => false, // by definition
'description' => null, // The controller can show this in every language as appropriate
]));
}
}
}
DB::flush();
Cache::delete(E\Actor::cacheKeys($target->getId())['self-tags']);
throw new RedirectException($request->get('_route'), ['nickname' => $target->getNickname(), 'open' => $details_id, '_fragment' => $details_id]);
},
handle_existing: /**
* Handle changes to the existing tags
*/
function ($form, array $form_definition) use ($request, $target, $details_id) {
$changed = false;
foreach (array_chunk($form_definition, 2) as $entry) {
$tag = CompTag::sanitize($entry[0][2]['data']);
/** @var SubmitButton $remove */
$remove = $form->get($entry[1][0]);
if ($remove->isClicked()) {
$changed = true;
DB::removeBy(
'actor_tag',
[
'tagger' => $target->getId(),
'tagged' => $target->getId(),
'tag' => $tag,
],
);
// We intentionally leave the self-tag actor circle, even if it is now empty
}
}
if ($changed) {
DB::flush();
Cache::delete(E\Actor::cacheKeys($target->getId())['self-tags']);
throw new RedirectException($request->get('_route'), ['nickname' => $target->getNickname(), 'open' => $details_id, '_fragment' => $details_id]);
}
},
remove_label: _m('Remove self tag'),
add_label: _m('Add self tag'),
);
return [
'_template' => 'self_tags_settings.fragment.html.twig',
'add_self_tags_form' => $add_form->createView(),
'existing_self_tags_form' => $existing_form?->createView(),
];
}
}

View File

@@ -19,11 +19,12 @@ declare(strict_types = 1);
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Entity; namespace Component\Circle\Entity;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Router;
use DateTimeInterface; use DateTimeInterface;
/** /**
@@ -48,10 +49,10 @@ class ActorCircle extends Entity
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $id; private int $id;
private int $tagger; private ?int $tagger = null;
private string $tag; private string $tag;
private ?string $description; private ?string $description = null;
private ?bool $private; private ?bool $private = false;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
@@ -66,20 +67,20 @@ class ActorCircle extends Entity
return $this->id; return $this->id;
} }
public function setTagger(int $tagger): self public function setTagger(?int $tagger): self
{ {
$this->tagger = $tagger; $this->tagger = $tagger;
return $this; return $this;
} }
public function getTagger(): int public function getTagger(): ?int
{ {
return $this->tagger; return $this->tagger;
} }
public function setTag(string $tag): self public function setTag(string $tag): self
{ {
$this->tag = $tag; $this->tag = mb_substr($tag, 0, 64);
return $this; return $this;
} }
@@ -135,60 +136,86 @@ class ActorCircle extends Entity
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
public function getActorTag() /**
* For use with MetaCollection trait only
*/
public function getName(): string
{
return $this->tag;
}
public function getActorTags(bool $db_reference = false): array
{
$handle = fn () => DB::findBy('actor_tag', ['tagger' => $this->getTagger(), 'tag' => $this->getTag()]);
if ($db_reference) {
return $handle();
}
return Cache::get(
"circle-{$this->getId()}-tagged",
$handle,
);
}
public function getTaggedActors()
{ {
return Cache::get( return Cache::get(
"actor-tag-{$this->getTag()}", "circle-{$this->getId()}-tagged-actors",
fn () => DB::findBy('actor_tag', ['tagger' => $this->getTagger(), 'canonical' => $this->getTag()], limit: 1)[0], // TODO jank function () {
if ($this->getTagger()) {
return DB::dql('SELECT a FROM actor AS a JOIN actor_tag AS at WITH at.tagged = a.id WHERE at.tag = :tag AND at.tagger = :tagger', ['tag' => $this->getTag(), 'tagger' => $this->getTagger()]);
} else { // Self-tag
return DB::dql('SELECT a FROM actor AS a JOIN actor_tag AS at WITH at.tagged = a.id WHERE at.tag = :tag AND at.tagger = at.tagged', ['tag' => $this->getTag()]);
}
},
); );
} }
public function getSubscribedActors(?int $offset = null, ?int $limit = null): array public function getSubscribedActors(?int $offset = null, ?int $limit = null): array
{ {
return Cache::get( return Cache::get(
"circle-{$this->getId()}", "circle-{$this->getId()}-subscribers",
fn () => DB::dql( fn () => DB::dql(
<<< 'EOQ' <<< 'EOQ'
SELECT a SELECT a
FROM App\Entity\Actor a FROM actor a
JOIN App\Entity\ActorCircleSubscription s JOIN actor_circle_subscription s
WITH a.id = s.actor_id WITH a.id = s.actor_id
ORDER BY s.created DESC, a.id DESC ORDER BY s.created DESC, a.id DESC
EOQ, EOQ,
options: ['offset' => $offset, options: [
'limit' => $limit, ], 'offset' => $offset,
'limit' => $limit,
],
), ),
); );
} }
public function getUrl(int $type = Router::ABSOLUTE_PATH): string
{
return Router::url('actor_circle_view_by_circle_id', ['circle_id' => $this->getId()], type: $type);
}
public static function schemaDef(): array public static function schemaDef(): array
{ {
return [ return [
'name' => 'actor_circle', 'name' => 'actor_circle',
'description' => 'a actor can have lists of actors, to separate their feed', 'description' => 'An actor can have lists of actors, to separate their feed or quickly mention his friend',
'fields' => [ 'fields' => [
'id' => ['type' => 'serial', 'not null' => true, 'description' => 'unique identifier'], 'id' => ['type' => 'serial', 'not null' => true, 'description' => 'unique identifier'], // An actor can be tagged by many actors
// An actor can be tagged by many actors 'tagger' => ['type' => 'int', 'default' => null, 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'many to one', 'name' => 'actor_list_tagger_fkey', 'description' => 'user making the tag, null if self-tag. If null, is the special global self-tag circle'],
'tagger' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'many to one', 'name' => 'actor_list_tagger_fkey', 'not null' => true, 'description' => 'user making the tag'], 'tag' => ['type' => 'varchar', 'length' => 64, 'foreign key' => true, 'target' => 'ActorTag.tag', 'multiplicity' => 'many to one', 'not null' => true, 'description' => 'actor tag'], // Join with ActorTag // // so, Doctrine doesn't like that the target is not unique, even though the pair is // Many Actor Circles can reference (and probably will) an Actor Tag
// Many Actor Circles can reference (and probably will) an Actor Tag
'tag' => ['type' => 'varchar', 'length' => 64, 'foreign key' => true, 'target' => 'ActorTag.tag', 'multiplicity' => 'many to one', 'not null' => true, 'description' => 'actor tag'], // Join with ActorTag // // so, Doctrine doesn't like that the target is not unique, even though the pair is
'description' => ['type' => 'text', 'description' => 'description of the people tag'], 'description' => ['type' => 'text', 'description' => 'description of the people tag'],
'private' => ['type' => 'bool', 'default' => false, 'description' => 'is this tag private'], 'private' => ['type' => 'bool', 'default' => false, 'description' => 'is this tag private'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'], 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
], ],
'primary key' => ['id'], 'primary key' => ['id'], // But we will mostly refer to them with `tagger` and `tag`
'indexes' => [ 'indexes' => [
'actor_list_modified_idx' => ['modified'], 'actor_list_modified_idx' => ['modified'],
'actor_list_tagger_tag_idx' => ['tagger', 'tag'], // The actual identifier we will use the most
'actor_list_tag_idx' => ['tag'], 'actor_list_tag_idx' => ['tag'],
'actor_list_tagger_tag_idx' => ['tagger', 'tag'],
'actor_list_tagger_idx' => ['tagger'], 'actor_list_tagger_idx' => ['tagger'],
], ],
]; ];
} }
public function __toString()
{
return $this->getTag();
}
} }

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -17,7 +19,7 @@
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Entity; namespace Component\Circle\Entity;
use App\Core\Entity; use App\Core\Entity;
use DateTimeInterface; use DateTimeInterface;
@@ -59,13 +61,13 @@ class ActorCircleSubscription extends Entity
return $this->actor_id; return $this->actor_id;
} }
public function setCircleid(int $circle_id): self public function setCircleId(int $circle_id): self
{ {
$this->circle_id = $circle_id; $this->circle_id = $circle_id;
return $this; return $this;
} }
public function getCircleid(): int public function getCircleId(): int
{ {
return $this->circle_id; return $this->circle_id;
} }
@@ -98,18 +100,18 @@ class ActorCircleSubscription extends Entity
public static function schemaDef(): array public static function schemaDef(): array
{ {
return [ return [
'name' => 'actor_circle_subscription', 'name' => 'actor_circle_subscription',
'fields' => [ 'fields' => [
'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'actor_circle_subscription_actor_id_fkey', 'not null' => true, 'description' => 'foreign key to actor table'], 'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'actor_circle_subscription_actor_id_fkey', 'not null' => true, 'description' => 'foreign key to actor table'],
// An actor subscribes many circles; A Circle is subscribed by many actors. // An actor subscribes many circles; A Circle is subscribed by many actors.
'circle_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'ActorCircle.id', 'multiplicity' => 'one to many', 'name' => 'actor_circle_subscription_actor_circle_fkey', 'not null' => true, 'description' => 'foreign key to actor_circle'], 'circle_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'ActorCircle.id', 'multiplicity' => 'one to many', 'name' => 'actor_circle_subscription_actor_circle_fkey', 'not null' => true, 'description' => 'foreign key to actor_circle'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'], 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
], ],
'primary key' => ['circle_id', 'actor_id'], 'primary key' => ['circle_id', 'actor_id'],
'indexes' => [ 'indexes' => [
'actor_circle_subscription_actor_id_idx' => ['actor_id'], 'actor_circle_subscription_actor_id_idx' => ['actor_id'],
'actor_circle_subscription_created_idx' => ['created'], 'actor_circle_subscription_created_idx' => ['created'],
], ],
]; ];
} }

View File

@@ -19,12 +19,12 @@ declare(strict_types = 1);
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Entity; namespace Component\Circle\Entity;
use App\Core\Cache; use App\Core\DB;
use App\Core\DB\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Router\Router; use App\Core\Router;
use App\Entity\Actor;
use Component\Tag\Tag; use Component\Tag\Tag;
use DateTimeInterface; use DateTimeInterface;
@@ -54,8 +54,6 @@ class ActorTag extends Entity
private int $tagger; private int $tagger;
private int $tagged; private int $tagged;
private string $tag; private string $tag;
private string $canonical;
private bool $use_canonical;
private DateTimeInterface $modified; private DateTimeInterface $modified;
public function setTagger(int $tagger): self public function setTagger(int $tagger): self
@@ -82,7 +80,7 @@ class ActorTag extends Entity
public function setTag(string $tag): self public function setTag(string $tag): self
{ {
$this->tag = $tag; $this->tag = mb_substr($tag, 0, 64);
return $this; return $this;
} }
@@ -91,28 +89,6 @@ class ActorTag extends Entity
return $this->tag; return $this->tag;
} }
public function setCanonical(string $canonical): self
{
$this->canonical = $canonical;
return $this;
}
public function getCanonical(): string
{
return $this->canonical;
}
public function setUseCanonical(bool $use_canonical): self
{
$this->use_canonical = $use_canonical;
return $this;
}
public function getUseCanonical(): bool
{
return $this->use_canonical;
}
public function setModified(DateTimeInterface $modified): self public function setModified(DateTimeInterface $modified): self
{ {
$this->modified = $modified; $this->modified = $modified;
@@ -127,18 +103,22 @@ class ActorTag extends Entity
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
public static function getByActorId(int $actor_id): array public function getUrl(?Actor $actor = null, int $type = Router::ABSOLUTE_PATH): string
{ {
return Cache::getList(Actor::cacheKeys($actor_id)['tags'], fn () => DB::dql('select at from actor_tag at join actor a with a.id = at.tagger where a.id = :id', ['id' => $actor_id])); $params = ['tag' => $this->getTag()];
if (!\is_null($actor)) {
$params['locale'] = $actor->getTopLanguage()->getLocale();
}
return Router::url('single_actor_tag', $params, type: $type);
} }
public function getUrl(?Actor $actor = null): string public function getCircle(): ActorCircle
{ {
$params = ['canon' => $this->getCanonical(), 'tag' => $this->getTag()]; if ($this->getTagger() === $this->getTagged()) { // Self-tag
if (!\is_null($actor)) { return DB::findOneBy(ActorCircle::class, ['tagger' => null, 'tag' => $this->getTag()]);
$params['lang'] = $actor->getTopLanguage()->getLocale(); } else {
return DB::findOneBy(ActorCircle::class, ['tagger' => $this->getTagger(), 'tag' => $this->getTag()]);
} }
return Router::url('single_actor_tag', $params);
} }
public static function schemaDef(): array public static function schemaDef(): array
@@ -146,24 +126,16 @@ class ActorTag extends Entity
return [ return [
'name' => 'actor_tag', 'name' => 'actor_tag',
'fields' => [ 'fields' => [
'tagger' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'actor_tag_tagger_fkey', 'not null' => true, 'description' => 'actor making the tag'], 'tagger' => ['type' => 'int', 'not null' => true, 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'actor_tag_tagger_fkey', 'description' => 'actor making the tag'],
'tagged' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'actor_tag_tagged_fkey', 'not null' => true, 'description' => 'actor tagged'], 'tagged' => ['type' => 'int', 'not null' => true, 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'actor_tag_tagged_fkey', 'description' => 'actor tagged'],
'tag' => ['type' => 'varchar', 'length' => Tag::MAX_TAG_LENGTH, 'not null' => true, 'description' => 'hash tag associated with this actor'], 'tag' => ['type' => 'varchar', 'length' => Tag::MAX_TAG_LENGTH, 'not null' => true, 'description' => 'hashtag associated with this note'],
'canonical' => ['type' => 'varchar', 'length' => Tag::MAX_TAG_LENGTH, 'not null' => true, 'description' => 'ascii slug of tag'], 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
'use_canonical' => ['type' => 'bool', 'not null' => true, 'description' => 'whether the user wanted to block canonical tags'], ], // We will always assume the tagger's preferred language for tags and circles
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'], 'primary key' => ['tagger', 'tagged', 'tag'],
],
'primary key' => ['tagger', 'tagged', 'tag', 'use_canonical'],
'indexes' => [ 'indexes' => [
'actor_tag_modified_idx' => ['modified'],
'actor_tag_tagger_tag_idx' => ['tagger', 'tag'], // For Circles 'actor_tag_tagger_tag_idx' => ['tagger', 'tag'], // For Circles
'actor_tag_tagged_idx' => ['tagged'], 'actor_tag_tagged_idx' => ['tagged'],
], ],
]; ];
} }
public function __toString(): string
{
return $this->getTag();
}
} }

View File

@@ -2,13 +2,11 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace Component\Tag\Form; namespace Component\Circle\Form;
use App\Core\Form; use App\Core\Form;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Entity as E;
use App\Util\Form\ArrayTransformer; use App\Util\Form\ArrayTransformer;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -16,31 +14,27 @@ use Symfony\Component\HttpFoundation\Request;
abstract class SelfTagsForm abstract class SelfTagsForm
{ {
/** /**
* @param E\ActorTag[]|E\ActorTagBlock[]|E\NoteTagBlock[] $tags
*
* @return array [Form (add), ?Form (existing)] * @return array [Form (add), ?Form (existing)]
*/ */
public static function handleTags( public static function handleTags(
Request $request, Request $request,
array $tags, array $actor_self_tags,
callable $handle_new, callable $handle_new,
callable $handle_existing, callable $handle_existing,
string $remove_label, string $remove_label,
string $add_label, string $add_label,
): array { ): array {
$form_definition = []; $form_definition = [];
foreach ($tags as $tag) { foreach ($actor_self_tags as $tag) {
$canon = $tag->getCanonical(); $tag = $tag->getTag();
$form_definition[] = ["{$canon}:old-tag", TextType::class, ['data' => '#' . $tag->getTag(), 'label' => ' ', 'disabled' => true]]; $form_definition[] = ["{$tag}:old-tag", TextType::class, ['data' => $tag, 'label' => ' ', 'disabled' => true]];
$form_definition[] = ["{$canon}:toggle-canon", SubmitType::class, ['attr' => ['data' => $tag->getUseCanonical()], 'label' => $tag->getUseCanonical() ? _m('Set non-canonical') : _m('Set canonical')]]; $form_definition[] = [$existing_form_name = "{$tag}:remove", SubmitType::class, ['label' => $remove_label]];
$form_definition[] = [$existing_form_name = "{$canon}:remove", SubmitType::class, ['label' => $remove_label]];
} }
$existing_form = !empty($form_definition) ? Form::create($form_definition) : null; $existing_form = !empty($form_definition) ? Form::create($form_definition) : null;
$add_form = Form::create([ $add_form = Form::create([
['new-tags', TextType::class, ['label' => ' ', 'data' => [], 'required' => false, 'help' => _m('Tags for yourself (letters, numbers, -, ., and _), comma- or space-separated.'), 'transformer' => ArrayTransformer::class]], ['new-tags', TextType::class, ['label' => ' ', 'data' => [], 'required' => false, 'help' => _m('Tags for this actor (letters, numbers, -, ., and _), comma- or space-separated.'), 'transformer' => ArrayTransformer::class]],
['new-tags-use-canon', CheckboxType::class, ['label' => _m('Use canonical'), 'help' => _m('Assume this tag is the same as similar tags'), 'required' => false, 'data' => true]],
[$add_form_name = 'new-tags-add', SubmitType::class, ['label' => $add_label]], [$add_form_name = 'new-tags-add', SubmitType::class, ['label' => $add_label]],
]); ]);

View File

@@ -0,0 +1,163 @@
<?php
declare(strict_types = 1);
namespace Component\Collection;
use App\Core\DB;
use App\Core\Event;
use App\Core\Modules\Component;
use App\Entity\Actor;
use App\Util\Formatting;
use Component\Collection\Util\Parser;
use Component\Subscription\Entity\ActorSubscription;
use Doctrine\Common\Collections\ExpressionBuilder;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
class Collection extends Component
{
/**
* Perform a high level query on notes or actors
*
* Supports a variety of query terms and is used both in feeds and
* in search. Uses query builders to allow for extension
*/
public static function query(string $query, int $page, ?string $locale = null, ?Actor $actor = null, array $note_order_by = [], array $actor_order_by = []): array
{
$note_criteria = null;
$actor_criteria = null;
if (!empty($query = trim($query))) {
[$note_criteria, $actor_criteria] = Parser::parse($query, $locale, $actor);
}
$note_qb = DB::createQueryBuilder();
$actor_qb = DB::createQueryBuilder();
// TODO consider selecting note related stuff, to avoid separate queries (though they're cached, so maybe it's okay)
$note_qb->select('note')->from('App\Entity\Note', 'note');
$actor_qb->select('actor')->from('App\Entity\Actor', 'actor');
Event::handle('CollectionQueryAddJoins', [&$note_qb, &$actor_qb, $note_criteria, $actor_criteria]);
// Handle ordering
$note_order_by = !empty($note_order_by) ? $note_order_by : ['note.created' => 'DESC', 'note.id' => 'DESC'];
$actor_order_by = !empty($actor_order_by) ? $actor_order_by : ['actor.created' => 'DESC', 'actor.id' => 'DESC'];
foreach ($note_order_by as $field => $order) {
$note_qb->addOrderBy($field, $order);
}
foreach ($actor_order_by as $field => $order) {
$actor_qb->addOrderBy($field, $order);
}
$notes = [];
$actors = [];
if (!\is_null($note_criteria)) {
$note_qb->addCriteria($note_criteria);
$notes = $note_qb->getQuery()->execute();
}
if (!\is_null($actor_criteria)) {
$actor_qb->addCriteria($actor_criteria);
$actors = $actor_qb->getQuery()->execute();
}
// N.B.: Scope is only enforced at FeedController level
return ['notes' => $notes ?? null, 'actors' => $actors ?? null];
}
public function onCollectionQueryAddJoins(QueryBuilder &$note_qb, QueryBuilder &$actor_qb): bool
{
$note_aliases = $note_qb->getAllAliases();
if (!\in_array('subscription', $note_aliases)) {
$note_qb->leftJoin(ActorSubscription::class, 'subscription', Expr\Join::WITH, 'note.actor_id = subscription.subscribed_id');
}
if (!\in_array('note_actor', $note_aliases)) {
$note_qb->leftJoin(Actor::class, 'note_actor', Expr\Join::WITH, 'note.actor_id = note_actor.id');
}
return Event::next;
}
/**
* Convert $term to $note_expr and $actor_expr, search criteria. Handles searching for text
* notes, for different types of actors and for the content of text notes
*/
public function onCollectionQueryCreateExpression(ExpressionBuilder $eb, string $term, ?string $locale, ?Actor $actor, &$note_expr, &$actor_expr)
{
if (str_contains($term, ':')) {
$term = explode(':', $term);
if (Formatting::startsWith($term[0], 'note')) {
switch ($term[0]) {
case 'notes-all':
$note_expr = $eb->neq('note.created', null);
break;
case 'note-local':
$note_expr = $eb->eq('note.is_local', filter_var($term[1], \FILTER_VALIDATE_BOOLEAN));
break;
case 'note-types':
case 'notes-include':
case 'note-filter':
if (\is_null($note_expr)) {
$note_expr = [];
}
if (array_intersect(explode(',', $term[1]), ['text', 'words']) !== []) {
$note_expr[] = $eb->neq('note.content', null);
} else {
$note_expr[] = $eb->eq('note.content', null);
}
break;
case 'note-conversation':
$note_expr = $eb->eq('note.conversation_id', (int) trim($term[1]));
break;
case 'note-from':
case 'notes-from':
$subscribed_expr = $eb->eq('subscription.subscriber_id', $actor->getId());
$type_consts = [];
if ($term[1] === 'subscribed') {
$type_consts = null;
}
foreach (explode(',', $term[1]) as $from) {
if (str_starts_with($from, 'subscribed-')) {
[, $type] = explode('-', $from);
if (\in_array($type, ['actor', 'actors'])) {
$type_consts = null;
} else {
$type_consts[] = \constant(Actor::class . '::' . mb_strtoupper($type === 'organisation' ? 'group' : $type));
}
}
}
if (\is_null($type_consts)) {
$note_expr = $subscribed_expr;
} elseif (!empty($type_consts)) {
$note_expr = $eb->andX($subscribed_expr, $eb->in('note_actor.type', $type_consts));
}
break;
}
} elseif (Formatting::startsWith($term, 'actor-')) {
switch ($term[0]) {
case 'actor-types':
case 'actors-include':
case 'actor-filter':
case 'actor-local':
if (\is_null($actor_expr)) {
$actor_expr = [];
}
foreach (
[
Actor::PERSON => ['person', 'people'],
Actor::GROUP => ['group', 'groups', 'org', 'orgs', 'organisation', 'organisations', 'organization', 'organizations'],
Actor::BOT => ['bot', 'bots'],
] as $type => $match) {
if (array_intersect(explode(',', $term[1]), $match) !== []) {
$actor_expr[] = $eb->eq('actor.type', $type);
} else {
$actor_expr[] = $eb->neq('actor.type', $type);
}
}
break;
}
}
} else {
$note_expr = $eb->contains('note.content', $term);
}
return Event::next;
}
}

View File

@@ -0,0 +1,9 @@
<?php
declare(strict_types = 1);
namespace Component\Collection\Util\Controller;
class CircleController extends OrderedCollection
{
}

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types = 1);
namespace Component\Collection\Util\Controller;
use App\Core\Controller;
use App\Entity\Actor;
use App\Util\Common;
use Component\Collection\Collection as CollectionModule;
class Collection extends Controller
{
public function query(string $query, ?string $locale = null, ?Actor $actor = null, array $note_order_by = [], array $actor_order_by = []): array
{
$actor ??= Common::actor();
$locale ??= Common::currentLanguage()->getLocale();
return CollectionModule::query($query, $this->int('page') ?? 1, $locale, $actor, $note_order_by, $actor_order_by);
}
}

View File

@@ -30,29 +30,36 @@ declare(strict_types = 1);
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
namespace Component\Feed\Util; namespace Component\Collection\Util\Controller;
use App\Core\Controller;
use App\Core\Event; use App\Core\Event;
use App\Entity\Actor;
use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use Functional as F;
abstract class FeedController extends Controller abstract class FeedController extends OrderedCollection
{ {
/** /**
* Post process the result of a feed controller, to remove any * Post-processing of the result of a feed controller, to remove any
* notes or actors the user specified, as well as format the raw * notes or actors the user specified, as well as format the raw
* list of notes into a usable format * list of notes into a usable format
*/ */
public static function post_process(array $result): array protected function postProcess(array $result): array
{ {
$actor = Common::actor(); $actor = Common::actor();
if (\array_key_exists('notes', $result)) { if (\array_key_exists('notes', $result)) {
$notes = $result['notes']; $notes = $result['notes'];
self::enforceScope($notes, $actor, $result['actor'] ?? null);
Event::handle('FilterNoteList', [$actor, &$notes, $result['request']]); Event::handle('FilterNoteList', [$actor, &$notes, $result['request']]);
Event::handle('FormatNoteList', [$notes, &$result['notes']]); Event::handle('FormatNoteList', [$notes, &$result['notes'], &$result['request']]);
} }
return $result; return $result;
} }
private static function enforceScope(array &$notes, ?Actor $actor, ?Actor $in = null): void
{
$notes = F\select($notes, fn (Note $n) => $n->isVisibleTo($actor, $in));
}
} }

View File

@@ -3,7 +3,6 @@
declare(strict_types = 1); declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
// GNU social is free software: you can redistribute it and/or modify // GNU social is free software: you can redistribute it and/or modify
@@ -18,109 +17,123 @@ declare(strict_types = 1);
// //
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
/**
* Collections Controller for GNU social
*
* @package GNUsocial
* @category Plugin
*
* @author Phablulo <phablulo@gmail.com>
* @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Plugin\AttachmentCollections\Controller; namespace Component\Collection\Util\Controller;
use App\Core\DB;
use App\Core\Form; use App\Core\Form;
use App\Core\DB\DB;
use App\Util\Common;
use App\Core\Router\Router;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use Component\Feed\Util\FeedController; use App\Entity\LocalUser;
use Symfony\Component\HttpFoundation\Request; use App\Util\Common;
use Plugin\AttachmentCollections\Entity\Collection; use App\Util\Exception\RedirectException;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
class Controller extends FeedController abstract class MetaCollectionController extends FeedController
{ {
public function collectionsByActorNickname(Request $request, string $nickname): array protected const SLUG = 'collectionsEntry';
protected const PLURAL_SLUG = 'collectionsList';
protected string $page_title = 'Collections';
abstract public function getCollectionUrl(int $owner_id, string $owner_nickname, int $collection_id): string;
abstract public function getCollectionItems(int $owner_id, $collection_id): array;
abstract public function getCollectionsByActorId(int $owner_id): array;
abstract public function getCollectionBy(int $owner_id, int $collection_id);
abstract public function createCollection(int $owner_id, string $name);
public function collectionsViewByActorNickname(Request $request, string $nickname): array
{ {
$user = DB::findOneBy('local_user', ['nickname' => $nickname]); $user = DB::findOneBy(LocalUser::class, ['nickname' => $nickname]);
return self::collectionsView($request, $user->getId(), $nickname); return self::collectionsView($request, $user->getId(), $nickname);
} }
public function collectionsViewByActorId(Request $request, int $id): array public function collectionsViewByActorId(Request $request, int $id): array
{ {
return self::collectionsView($request, $id, null); return self::collectionsView($request, $id, null);
} }
/** /**
* Generate Collections page * Generate Collections page
*
* @param int $id actor id * @param int $id actor id
* @param ?string $nickname actor nickname * @param ?string $nickname actor nickname
* @return array twig template options *
* @return array twig template options
*/ */
public function collectionsView(Request $request, int $id, ?string $nickname): array public function collectionsView(Request $request, int $id, ?string $nickname): array
{ {
$collections = DB::dql( $collections = $this->getCollectionsByActorId($id);
'select collection from Plugin\AttachmentCollections\Entity\Collection collection '
. 'where collection.actor_id = :id', $create_title = _m('Create a ' . mb_strtolower(preg_replace('/([a-z0-9])([A-Z])/', '$1 $2', static::SLUG)));
['id' => $id] $collections_title = _m('The ' . mb_strtolower(preg_replace('/([a-z0-9])([A-Z])/', '$1 $2', static::PLURAL_SLUG)));
);
// create collection form // create collection form
$create = null; $create = null;
if (Common::user()?->getId() === $id) { if (Common::user()?->getId() === $id) {
$create = Form::create([ $create = Form::create([
['name', TextType::class, [ ['name', TextType::class, [
'label' => _m('Create collection'), 'label' => $create_title,
'attr' => [ 'attr' => [
'placeholder' => _m('Name'), 'placeholder' => _m('Name'),
'required' => 'required' 'required' => 'required',
], ],
'data' => '', 'data' => '',
]], ]],
['add_collection', SubmitType::class, [ ['add_collection', SubmitType::class, [
'label' => _m('Create collection'), 'label' => $create_title,
'attr' => [ 'attr' => [
'title' => _m('Create collection'), 'title' => $create_title,
], ],
]], ]],
]); ]);
$create->handleRequest($request); $create->handleRequest($request);
if ($create->isSubmitted() && $create->isValid()) { if ($create->isSubmitted() && $create->isValid()) {
DB::persist(Collection::create([ $this->createCollection($id, $create->getData()['name']);
'name' => $create->getData()['name'],
'actor_id' => $id,
]));
DB::flush(); DB::flush();
throw new RedirectException();
} }
} }
// We need to inject some functions in twig, // We need to inject some functions in twig,
// but i don't want to create an enviroment for this // but I don't want to create an environment for this
// as twig docs suggest in https://twig.symfony.com/doc/2.x/advanced.html#functions. // as twig docs suggest in https://twig.symfony.com/doc/2.x/advanced.html#functions.
// //
// Instead, I'm using an anonymous class to encapsulate // Instead, I'm using an anonymous class to encapsulate
// the functions and passing how the class to the template. // the functions and passing that class to the template.
// It's suggested at https://stackoverflow.com/a/50364502. // This is suggested at https://web.archive.org/web/20220226132328/https://stackoverflow.com/questions/3595727/twig-pass-function-into-template/50364502
$fn = new class ($id, $nickname, $request) $fn = new class($id, $nickname, $request, $this, static::SLUG) {
{
private $id; private $id;
private $nick; private $nick;
private $request; private $request;
public function __construct($id, $nickname, $request) private $parent;
private $slug;
public function __construct($id, $nickname, $request, $parent, $slug)
{ {
$this->id = $id; $this->id = $id;
$this->nick = $nickname; $this->nick = $nickname;
$this->request = $request; $this->request = $request;
$this->parent = $parent;
$this->slug = $slug;
} }
// there's already a injected function called path, // there's already an injected function called path,
// that maps to Router::url(name, args), but since // that maps to Router::url(name, args), but since
// I want to preserve nicknames, I think it's better // I want to preserve nicknames, I think it's better
// to use that getUrl function // to use that getUrl function
public function getUrl($cid) public function getUrl($cid)
{ {
if (\is_null($this->nick)) { return $this->parent->getCollectionUrl($this->id, $this->nick, $cid);
return Router::url(
'collection_notes_view_by_actor_id',
['id' => $this->id, 'cid' => $cid]
);
}
return Router::url(
'collection_notes_view_by_nickname',
['nickname' => $this->nick, 'cid' => $cid]
);
} }
// There are many collections in this page and we need two // There are many collections in this page and we need two
// forms for each one of them: one form to edit the collection's // forms for each one of them: one form to edit the collection's
@@ -133,11 +146,11 @@ class Controller extends FeedController
['name', TextType::class, [ ['name', TextType::class, [
'attr' => [ 'attr' => [
'placeholder' => 'New name', 'placeholder' => 'New name',
'required' => 'required' 'required' => 'required',
], ],
'data' => '', 'data' => '',
]], ]],
['update_'.$collection->getId(), SubmitType::class, [ ['update_' . $collection->getId(), SubmitType::class, [
'label' => _m('Save'), 'label' => _m('Save'),
'attr' => [ 'attr' => [
'title' => _m('Save'), 'title' => _m('Save'),
@@ -146,61 +159,58 @@ class Controller extends FeedController
]); ]);
$edit->handleRequest($this->request); $edit->handleRequest($this->request);
if ($edit->isSubmitted() && $edit->isValid()) { if ($edit->isSubmitted() && $edit->isValid()) {
$collection->setName($edit->getData()['name']); $this->parent->setCollectionName($this->id, $this->nick, $collection, $edit->getData()['name']);
DB::persist($collection);
DB::flush(); DB::flush();
throw new RedirectException();
} }
return $edit->createView(); return $edit->createView();
} }
// creating the remove form // creating the remove form
public function rmForm($collection) public function rmForm($collection)
{ {
$rm = Form::create([ $rm = Form::create([
['remove_'.$collection->getId(), SubmitType::class, [ ['remove_' . $collection->getId(), SubmitType::class, [
'label' => _m('Delete collection'), 'label' => _m('Delete ' . $this->slug),
'attr' => [ 'attr' => [
'title' => _m('Delete collection'), 'title' => _m('Delete ' . $this->slug),
'class' => 'danger', 'class' => 'danger',
], ],
]], ]],
]); ]);
$rm->handleRequest($this->request); $rm->handleRequest($this->request);
if ($rm->isSubmitted()) { if ($rm->isSubmitted()) {
DB::remove($collection); $this->parent->removeCollection($this->id, $this->nick, $collection);
DB::flush(); DB::flush();
throw new RedirectException();
} }
return $rm->createView(); return $rm->createView();
} }
}; };
return [ return [
'_template' => 'AttachmentCollections/collections.html.twig', '_template' => 'collection/meta_collections.html.twig',
'page_title' => 'Attachment Collections list', 'page_title' => $this->page_title,
'list_title' => $collections_title,
'add_collection' => $create?->createView(), 'add_collection' => $create?->createView(),
'fn' => $fn, 'fn' => $fn,
'collections' => $collections, 'collections' => $collections,
]; ];
} }
public function collectionNotesByNickname(Request $request, string $nickname, int $cid): array public function collectionsEntryViewNotesByNickname(Request $request, string $nickname, int $cid): array
{ {
$user = DB::findOneBy('local_user', ['nickname' => $nickname]); $user = DB::findOneBy(LocalUser::class, ['nickname' => $nickname]);
return self::collectionNotesByActorId($request, $user->getId(), $cid); return self::collectionsEntryViewNotesByActorId($request, $user->getId(), $cid);
} }
public function collectionNotesByActorId(Request $request, int $id, int $cid): array
public function collectionsEntryViewNotesByActorId(Request $request, int $id, int $cid): array
{ {
$collection = DB::findOneBy('attachment_collection', ['id' => $cid]); $collection = $this->getCollectionBy($id, $cid);
$attchs = DB::dql( $vars = $this->getCollectionItems($id, $cid);
'select attch from attachment_album_entry entry ' return array_merge([
. 'left join Component\Attachment\Entity\Attachment attch ' '_template' => 'collections/collection_entry_view.html.twig',
. 'with entry.attachment_id = attch.id ' 'page_title' => $collection->getName(),
. 'where entry.collection_id = :cid', ], $vars);
['cid' => $cid]
);
return [
'_template' => 'AttachmentCollections/collection.html.twig',
'page_title' => $collection->getName(),
'attachments' => $attchs,
];
} }
} }

View File

@@ -0,0 +1,9 @@
<?php
declare(strict_types = 1);
namespace Component\Collection\Util\Controller;
class OrderedCollection extends Collection
{
}

View File

@@ -0,0 +1,195 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/**
* Collections for GNU social
*
* @package GNUsocial
* @category Plugin
*
* @author Phablulo <phablulo@gmail.com>
* @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Component\Collection\Util;
use App\Core\DB;
use App\Core\Event;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Entity\Actor;
use App\Util\Common;
use App\Util\Exception\RedirectException;
use App\Util\Formatting;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
trait MetaCollectionTrait
{
//protected const SLUG = 'collection';
//protected const PLURAL_SLUG = 'collections';
/**
* create a collection owned by Actor $owner.
*
* @param Actor $owner The collection's owner
* @param array $vars Page vars sent by AppendRightPanelBlock event
* @param string $name Collection's name
*/
abstract protected function createCollection(Actor $owner, array $vars, string $name);
/**
* remove item from collections.
*
* @param Actor $owner Current user
* @param array $vars Page vars sent by AppendRightPanelBlock event
* @param array $items Array of collections's ids to remove the current item from
* @param array $collections List of ids of collections owned by $owner
*/
abstract protected function removeItem(Actor $owner, array $vars, array $items, array $collections);
/**
* add item to collections.
*
* @param Actor $owner Current user
* @param array $vars Page vars sent by AppendRightPanelBlock event
* @param array $items Array of collections's ids to add the current item to
* @param array $collections List of ids of collections owned by $owner
*/
abstract protected function addItem(Actor $owner, array $vars, array $items, array $collections);
/**
* Check the route to determine whether the widget should be added
*/
abstract protected function shouldAddToRightPanel(Actor $user, $vars, Request $request): bool;
/**
* Get array of collections's owned by $actor
*
* @param Actor $owner Collection's owner
* @param ?array $vars Page vars sent by AppendRightPanelBlock event
* @param bool $ids_only if true, the function must return only the primary key or each collections
*/
abstract protected function getCollectionsBy(Actor $owner, ?array $vars = null, bool $ids_only = false): array;
/**
* Append Collections widget to the right panel.
* It's compose of two forms: one to select collections to add
* the current item to, and another to create a new collection.
*/
public function onAppendRightPanelBlock(Request $request, $vars, &$res): bool
{
$user = Common::actor();
if (\is_null($user)) {
return Event::next;
}
if (!$this->shouldAddToRightPanel($user, $vars, $request)) {
return Event::next;
}
$collections = $this->getCollectionsBy($user);
// form: add to collection
$choices = [];
foreach ($collections as $col) {
$choices[$col->getName()] = $col->getId();
}
$collections = array_map(fn ($x) => $x->getId(), $collections);
$already_selected = $this->getCollectionsBy($user, $vars, true);
$add_form = Form::create([
['collections', ChoiceType::class, [
'choices' => $choices,
'multiple' => true,
'required' => false,
'choice_attr' => function ($id) use ($already_selected) {
if (\in_array($id, $already_selected)) {
return ['selected' => 'selected'];
}
return [];
},
]],
['add', SubmitType::class, [
'label' => _m('Add to ' . static::PLURAL_SLUG),
'attr' => [
'title' => _m('Add to ' . static::PLURAL_SLUG),
],
]],
]);
$add_form->handleRequest($request);
if ($add_form->isSubmitted() && $add_form->isValid()) {
$selected = $add_form->getData()['collections'];
$removed = array_filter($already_selected, fn ($x) => !\in_array($x, $selected));
$added = array_filter($selected, fn ($x) => !\in_array($x, $already_selected));
if (\count($removed) > 0) {
$this->removeItem($user, $vars, $removed, $collections);
}
if (\count($added) > 0) {
$this->addItem($user, $vars, $added, $collections);
}
DB::flush();
throw new RedirectException();
}
// form: add to new collection
$create_form = Form::create([
['name', TextType::class, [
'label' => _m('Add to a new ' . static::SLUG),
'attr' => [
'placeholder' => _m('New ' . static::SLUG . ' name'),
'required' => 'required',
],
'data' => '',
]],
['create', SubmitType::class, [
'label' => _m('Create a new ' . static::SLUG),
'attr' => [
'title' => _m('Create a new ' . static::SLUG),
],
]],
]);
$create_form->handleRequest($request);
if ($create_form->isSubmitted() && $create_form->isValid()) {
$name = $create_form->getData()['name'];
$this->createCollection($user, $vars, $name);
DB::flush();
throw new RedirectException();
}
$res[] = Formatting::twigRenderFile(
'collection/widget_add_to.html.twig',
[
'ctitle' => _m('Add to ' . static::PLURAL_SLUG),
'user' => $user,
'has_collections' => \count($collections) > 0,
'add_form' => $add_form->createView(),
'create_form' => $create_form->createView(),
],
);
return Event::next;
}
public function onEndShowStyles(array &$styles, string $route): bool
{
$styles[] = 'components/Collection/assets/css/widget.css';
$styles[] = 'components/Collection/assets/css/pages.css';
return Event::next;
}
}

View File

@@ -21,7 +21,7 @@ declare(strict_types = 1);
// }}} // }}}
namespace Component\Search\Util; namespace Component\Collection\Util;
use App\Core\Event; use App\Core\Event;
use App\Entity\Actor; use App\Entity\Actor;
@@ -50,10 +50,11 @@ abstract class Parser
* recognises either spaces (currently `or`, should be fuzzy match), `OR` or `|` (`or`) and `AND` or `&` (`and`) * recognises either spaces (currently `or`, should be fuzzy match), `OR` or `|` (`or`) and `AND` or `&` (`and`)
* *
* TODO: Better fuzzy match, implement exact match with quotes and nesting with parens * TODO: Better fuzzy match, implement exact match with quotes and nesting with parens
* TODO: Proper parser, tokenize better. Mostly a rewrite
* *
* @return Criteria[] * @return array{?Criteria, ?Criteria} [?$note_criteria, ?$actor_criteria]
*/ */
public static function parse(string $input, ?string $language = null, ?Actor $actor = null, int $level = 0): array public static function parse(string $input, ?string $locale = null, ?Actor $actor = null, int $level = 0): array
{ {
if ($level === 0) { if ($level === 0) {
$input = trim(preg_replace(['/\s+/', '/\s+AND\s+/', '/\s+OR\s+/'], [' ', '&', '|'], $input), ' |&'); $input = trim(preg_replace(['/\s+/', '/\s+AND\s+/', '/\s+OR\s+/'], [' ', '&', '|'], $input), ' |&');
@@ -78,17 +79,18 @@ abstract class Parser
$term = mb_substr($input, $left, $end ? null : $right - $left); $term = mb_substr($input, $left, $end ? null : $right - $left);
$note_res = null; $note_res = null;
$actor_res = null; $actor_res = null;
Event::handle('SearchCreateExpression', [$eb, $term, $language, $actor, &$note_res, &$actor_res]); Event::handle('CollectionQueryCreateExpression', [$eb, $term, $locale, $actor, &$note_res, &$actor_res]);
if (\is_null($note_res) && \is_null($actor_res)) { if (\is_null($note_res) && \is_null($actor_res)) { // @phpstan-ignore-line
throw new ServerException("No one claimed responsibility for a match term: {$term}"); //throw new ServerException("No one claimed responsibility for a match term: {$term}");
// It's okay if the term doesn't exist, just perform a regular search
} }
if (!\is_null($note_res) && !empty($note_res)) { if (!empty($note_res)) { // @phpstan-ignore-line currently an open bug. See https://web.archive.org/web/20220226131651/https://github.com/phpstan/phpstan/issues/6234
if (\is_array($note_res)) { if (\is_array($note_res)) {
$note_res = $eb->orX(...$note_res); $note_res = $eb->orX(...$note_res);
} }
$note_parts[] = $note_res; $note_parts[] = $note_res;
} }
if (!\is_null($actor_res) && !empty($note_res)) { if (!empty($actor_res)) { // @phpstan-ignore-line currently an open bug. See https://web.archive.org/web/20220226131651/https://github.com/phpstan/phpstan/issues/6234
if (\is_array($actor_res)) { if (\is_array($actor_res)) {
$actor_res = $eb->orX(...$actor_res); $actor_res = $eb->orX(...$actor_res);
} }
@@ -103,9 +105,10 @@ abstract class Parser
$last_op = $delimiter; $last_op = $delimiter;
} }
$match = true; $match = true;
continue 2; break;
} }
} }
// TODO
if (!$match) { if (!$match) {
++$right; ++$right;
} }
@@ -117,7 +120,7 @@ abstract class Parser
self::connectParts($note_parts, $note_criteria_arr, $last_op, $eb, force: true); self::connectParts($note_parts, $note_criteria_arr, $last_op, $eb, force: true);
$note_criteria = new Criteria($eb->orX(...$note_criteria_arr)); $note_criteria = new Criteria($eb->orX(...$note_criteria_arr));
} }
if (!empty($actor_parts)) { if (!empty($actor_parts)) { // @phpstan-ignore-line weird, but this whole thing needs a rewrite
self::connectParts($actor_parts, $actor_criteria_arr, $last_op, $eb, force: true); self::connectParts($actor_parts, $actor_criteria_arr, $last_op, $eb, force: true);
$actor_criteria = new Criteria($eb->orX(...$actor_criteria_arr)); $actor_criteria = new Criteria($eb->orX(...$actor_criteria_arr));
} }

View File

@@ -0,0 +1,70 @@
{% extends 'stdgrid.html.twig' %}
{% block title %}{{ title }}{% endblock %}
{% block body %}
<section class="frame-section frame-section-padding">
<header class="feed-header">
{% if actors_feed_title is defined %}
{{ actors_feed_title.getHtml() }}
{% endif %}
</header>
{% set prepend_actors_collection = handle_event('PrependActorsCollection', request) %}
{% for widget in prepend_actors_collection %}
{{ widget | raw }}
{% endfor %}
<details class="frame-section section-details-title">
<summary class="details-summary-title">
<strong>
{% trans %}Ordering rules{% endtrans %}
</strong>
</summary>
<form method="GET" class="section-form">
<div class="container-grid">
<section class="frame-section frame-section-padding">
<strong>{% trans %}Sort by{% endtrans %}</strong>
<hr>
<div class="container-block">
{% for field in sort_form_fields %}
<span class="container-block">
<label for="order_by_{{ field.value }}">{{ field.label }}</label>
<input id="order_by_{{ field.value }}" type="radio" name="order_by" value="{{ field.value }}" {% if field.checked %}checked="checked"{% endif %}>
</span>
{% endfor %}
</div>
</section>
<section class="frame-section frame-section-padding">
<strong class="section-title">{% trans %}Order{% endtrans %}</strong>
<hr>
<section class="container-block">
<span class="container-block">
<label for="order_op_asc">{% trans %}Ascending{% endtrans %}</label>
<input id="order_op_asc" type="radio" name="order_op" value="ASC">
</span>
<span class="container-block">
<label for="order_op_desc">{% trans %}Descending{% endtrans %}</label>
<input id="order_op_desc" type="radio" name="order_op" value="DESC" checked="checked">
</span>
</section>
</section>
</div>
<button type="submit">{% trans %}Order{% endtrans %}</button>
</form>
</details>
<section class="frame-section frame-section-padding">
<h2>{% trans %}Results{% endtrans %}</h2>
{% if actors is defined and actors is not empty %}
{% for actor in actors %}
{% block profile_view %}{% include 'cards/blocks/profile.html.twig' %}{% endblock profile_view %}
<hr>
{% endfor %}
<span class="frame-section-button-like">{% trans %}Page: %page%{% endtrans %}</span>
{% else %}
<span>{{ empty_message }}</span>
{% endif %}
</section>
</section>
{% endblock body %}

View File

@@ -0,0 +1,11 @@
{% extends '/collection/notes.html.twig' %}
{% block title %}{% trans %}%page_title%{% endtrans %}{% endblock %}
{% block body %}
<div class="frame-section frame-section-padding">
<h2 class="frame-section-title">{% trans %}%page_title%{% endtrans %}</h2>
{% block collection_items %}
{% endblock collection_items %}
</div>
{% endblock body %}

View File

@@ -0,0 +1,34 @@
{% extends 'stdgrid.html.twig' %}
{% block title %}{% trans %}%page_title%{% endtrans %}{% endblock %}
{% block body %}
<div class="frame-section frame-section-padding">
<h2 class="frame-section-title">{% trans %}%page_title%{% endtrans %}</h2>
{% if add_collection %}
<div class="frame-section section-form">
{{ form(add_collection) }}
</div>
{% endif %}
<div class="frame-section collections-list">
<h3>{% trans %}%list_title%{% endtrans %}</h3>
{% for col in collections %}
<div class="collection-item">
<a class="name" href="{{ fn.getUrl(col.id) }}">{{ col.name }}</a>
<details title="Expand if you want to edit the collection's name">
<summary>
<span class="collection-action">{{ icon('edit') | raw }}</span>
</summary>
{{ form(fn.editForm(col)) }}
</details>
<details title="Expand if you want to delete the collection">
<summary>
<span class="collection-action">{{ icon('delete') | raw }}</span>
</summary>
{{ form(fn.rmForm(col)) }}
</details>
</div>
{% endfor %}
</div>
</div>
{% endblock body %}

View File

@@ -0,0 +1,58 @@
{% extends 'stdgrid.html.twig' %}
{% import '/cards/macros/note/factory.html.twig' as NoteFactory %}
{% block title %}{% if page_title is defined %}{% trans %}%page_title%{% endtrans %}{% endif %}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/feeds.css') }}" type="text/css">
{% endblock stylesheets %}
{% block body %}
{% for block in handle_event('BeforeFeed', app.request) %}
{{ block | raw }}
{% endfor %}
{% if notes is defined %}
<header class="feed-header">
{% set current_path = app.request.get('_route') %}
{% if notes_feed_title is defined %}
{{ notes_feed_title.getHtml() }}
{% endif %}
<nav class="feed-actions" title="{% trans %}Actions that change how the feed behaves{% endtrans %}">
<details class="feed-actions-details" role="group">
<summary>
{{ icon('filter', 'icon icon-feed-actions') | raw }} {# button-container #}
</summary>
<menu class="feed-actions-details-dropdown" role="toolbar">
{% for block in handle_event('AddFeedActions', app.request, notes is defined and notes is not empty) %}
{{ block | raw }}
{% endfor %}
</menu>
</details>
</nav>
</header>
{% if notes is not empty %}
{# Backwards compatibility with hAtom 0.1 #}
<section class="feed h-feed hfeed notes" role="feed" aria-busy="false" title="{% trans %}Feed content{% endtrans %}">
{% for conversation in notes %}
{% block current_note %}
{% if conversation is instanceof('array') %}
{% set args = conversation | merge({'type': 'vanilla_full'}) %}
{{ NoteFactory.constructor(args) }}
{# {% else %}
{% set args = { 'type': 'vanilla_full', 'note': conversation, 'extra': { 'depth': 0 } } %}
{{ NoteFactory.constructor(args) }}#}
{% endif %}
<hr class="hr-replies-end" role="separator" aria-label="{% trans %}Marks the end of previous conversation's initial note{% endtrans %}">
{% endblock current_note %}
{% endfor %}
</section>
{% else %}
<section class="feed h-feed hfeed notes" tabindex="0" role="feed">
<span>{% trans %}No notes here...{% endtrans %}</span>
</section>
{% endif %}
{% endif %}
{% endblock body %}

View File

@@ -0,0 +1,27 @@
<section class="frame-section collections">
<details class="section-details-title" title="Expand if you want to access more options.">
<summary class="details-summary-title">
<span>{{ctitle}}</span>
</summary>
{% if has_collections %}
<section class="section-form">
{{ form(add_form) }}
</section>
<details class="frame-section-padding section-details-subtitle"
title="Expand if you want to access more options.">
<summary class="details-summary-subtitle">
<strong>{% trans %}Other options{% endtrans %}</strong>
</summary>
<section class="section-form">
{{ form(create_form) }}
</section>
</details>
{% else %}
<section class="section-form">
{{ form(create_form) }}
</section>
{% endif %}
</details>
</section>

View File

@@ -20,42 +20,133 @@ declare(strict_types = 1);
/** /**
* @author Hugo Sales <hugo@hsal.es> * @author Hugo Sales <hugo@hsal.es>
* @copyright 2021 Free Software Foundation, Inc http://www.fsf.org * @author Eliseu Amaro <mail@eliseuama.ro>
* @copyright 2021-2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
namespace Component\Conversation\Controller; namespace Component\Conversation\Controller;
use App\Core\Cache;
use App\Core\DB;
use App\Core\Form;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use Component\Feed\Feed; use App\Core\Log;
use Component\Feed\Util\FeedController; use App\Core\Router;
use App\Entity\Note;
use App\Util\Common;
use App\Util\Exception\ClientException;
use App\Util\Exception\NoLoggedInUser;
use App\Util\Exception\NoSuchNoteException;
use App\Util\Exception\RedirectException;
use App\Util\Exception\ServerException;
use App\Util\HTML\Heading;
use Component\Collection\Util\Controller\FeedController;
use Component\Conversation\Entity\ConversationMute;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class Conversation extends FeedController class Conversation extends FeedController
{ {
/** /**
* Render conversation page * Render conversation page.
*
* @param int $conversation_id To identify what Conversation is to be rendered
*
* @throws \App\Util\Exception\ServerException
*
* @return array Array containing keys: 'notes' (all known notes in the given Conversation), 'should_format' (boolean, stating if onFormatNoteList events may or not format given notes), 'page_title' (used as the title header)
*/
public function showConversation(Request $request, int $conversation_id): array
{
$page_title = _m('Conversation');
return [
'_template' => 'collection/notes.html.twig',
'notes' => $this->query(
query: "note-conversation:{$conversation_id}",
note_order_by: ['note.created' => 'ASC', 'note.id' => 'ASC'],
)['notes'] ?? [],
'should_format' => false,
'page_title' => $page_title,
'notes_feed_title' => (new Heading(1, [], $page_title)),
];
}
/**
* Controller for the note reply non-JS page
*
* Leverages the `PostingModifyData` event to add the `reply_to_id` field from the GET variable 'reply_to_id'
*
* @throws ClientException
* @throws NoLoggedInUser
* @throws NoSuchNoteException
* @throws ServerException
* *
* @return array * @return array
*/ */
public function showConversation(Request $request, int $conversation_id) public function addReply(Request $request)
{ {
// TODO: $user = Common::ensureLoggedIn();
// if note is root -> just link $note_id = $this->int('reply_to_id', new ClientException(_m('Malformed query.')));
// if note is a reply -> link from above plus anchor $note = Note::ensureCanInteract(Note::getByPK($note_id), $user);
$conversation_id = $note->getConversationId();
return $this->showConversation($request, $conversation_id);
}
/**
* Creates form view for Muting Conversation extra action.
*
* @param int $conversation_id The Conversation id that this action targets
*
* @throws \App\Util\Exception\NoLoggedInUser
* @throws \App\Util\Exception\RedirectException
* @throws \App\Util\Exception\ServerException
*
* @return array Array containing templating where the form is to be rendered, and the form itself
*/
public function muteConversation(Request $request, int $conversation_id)
{
$user = Common::ensureLoggedIn();
$is_muted = ConversationMute::isMuted($conversation_id, $user);
$form = Form::create([
['mute_conversation', SubmitType::class, ['label' => $is_muted ? _m('Unmute') : _m('Mute'), 'attr' => ['class' => '']]],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if (!$is_muted) {
DB::persist(ConversationMute::create(['conversation_id' => $conversation_id, 'actor_id' => $user->getId()]));
} else {
DB::removeBy('conversation_mute', ['conversation_id' => $conversation_id, 'actor_id' => $user->getId()]);
}
DB::flush();
Cache::delete(ConversationMute::cacheKeys($conversation_id, $user->getId())['mute']);
// Redirect user to where they came from
// Prevent open redirect
if (!\is_null($from = $this->string('from'))) {
if (Router::isAbsolute($from)) {
Log::warning("Actor {$user->getId()} attempted to mute conversation {$conversation_id} and then get redirected to another host, or the URL was invalid ({$from})");
throw new ClientException(_m('Can not redirect to outside the website from here'), 400); // 400 Bad request (deceptive)
} else {
// TODO anchor on element id
throw new RedirectException(url: $from);
}
} else {
// If we don't have a URL to return to, go to the instance root
throw new RedirectException('root');
}
}
/* $notes = DB::findBy(
table: 'note',
criteria: ['conversation_id' => $conversation_id],
order_by: ['created' => 'DESC', 'id' => 'DESC']
);*/
$data = Feed::query(query: "note-conversation:{$conversation_id}", page: $this->int('p') ?? 1);
$notes = $data['notes'];
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'conversation/mute.html.twig',
'notes' => $notes, 'notes' => $this->query(
'should_format' => false, query: "note-conversation:{$conversation_id}",
'page_title' => _m('Conversation'), note_order_by: ['note.created' => 'ASC', 'note.id' => 'ASC'],
)['notes'] ?? [],
'is_muted' => $is_muted,
'form' => $form->createView(),
]; ];
} }
} }

View File

@@ -1,9 +1,7 @@
<?php <?php
declare(strict_types = 1); declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
// GNU social is free software: you can redistribute it and/or modify // GNU social is free software: you can redistribute it and/or modify
@@ -18,29 +16,46 @@ declare(strict_types = 1);
// //
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
/**
* @author Hugo Sales <hugo@hsal.es>
* @author Eliseu Amaro <mail@eliseuama.ro>
* @copyright 2021-2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
namespace Component\Conversation; namespace Component\Conversation;
use App\Core\DB\DB; use App\Core\Cache;
use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Core\Router\Router; use App\Entity\Activity;
use App\Entity\Actor; use App\Entity\Actor;
use App\Entity\Note; use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use App\Util\Formatting; use App\Util\Formatting;
use Component\Conversation\Controller\Reply as ReplyController;
use Component\Conversation\Entity\Conversation as ConversationEntity; use Component\Conversation\Entity\Conversation as ConversationEntity;
use Component\Conversation\Entity\ConversationMute;
use Functional as F;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class Conversation extends Component class Conversation extends Component
{ {
public function onAddRoute(Router $r): bool
{
$r->connect('conversation', '/conversation/{conversation_id<\d+>}', [Controller\Conversation::class, 'showConversation']);
$r->connect('conversation_mute', '/conversation/{conversation_id<\d+>}/mute', [Controller\Conversation::class, 'muteConversation']);
$r->connect('conversation_reply_to', '/conversation/reply', [Controller\Conversation::class, 'addReply']);
return Event::next;
}
/** /**
* **Assigns** the given local Note it's corresponding **Conversation** * **Assigns** the given local Note it's corresponding **Conversation**.
* *
* **If a _$parent_id_ is not given**, then the Actor is not attempting a reply, * **If a _$parent_id_ is not given**, then the Actor is not attempting a reply,
* therefore, we can assume (for now) that we need to create a new Conversation and assign it * therefore, we can assume (for now) that we need to create a new Conversation and assign it
@@ -48,6 +63,9 @@ class Conversation extends Component
* *
* **On the other hand**, given a _$parent_id_, the Actor is attempting to post a reply. Meaning that, * **On the other hand**, given a _$parent_id_, the Actor is attempting to post a reply. Meaning that,
* this Note conversation_id should be same as the parent Note * this Note conversation_id should be same as the parent Note
*
* @param \App\Entity\Note $current_note Local Note currently being assigned a Conversation
* @param null|int $parent_id If present, it's a reply
*/ */
public static function assignLocalConversation(Note $current_note, ?int $parent_id): void public static function assignLocalConversation(Note $current_note, ?int $parent_id): void
{ {
@@ -64,20 +82,27 @@ class Conversation extends Component
} else { } else {
// It's a reply for sure // It's a reply for sure
// Set reply_to property in newly created Note to parent's id // Set reply_to property in newly created Note to parent's id
$current_note->setReplyTo($parent_id);
// Parent will have a conversation of its own, the reply should have the same one // Parent will have a conversation of its own, the reply should have the same one
$parent_note = Note::getById($parent_id); $parent_note = Note::getById($parent_id);
$current_note->setConversationId($parent_note->getConversationId()); $current_note->setConversationId($parent_note->getConversationId());
} }
DB::merge($current_note); DB::persist($current_note);
DB::flush();
} }
/** /**
* HTML rendering event that adds a reply link as a note * HTML rendering event that adds a reply link as a note
* action, if a user is logged in * action, if a user is logged in.
*
* @param \App\Entity\Note $note The Note being rendered
* @param array $actions Contains keys 'url' (linking 'conversation_reply_to'
* route), 'title' (used as title for aforementioned url),
* 'classes' (CSS styling classes used to visually inform the user of action context),
* 'id' (HTML markup id used to redirect user to this anchor upon performing the action)
*
* @throws \App\Util\Exception\ServerException
*
* @return bool EventHook
*/ */
public function onAddNoteActions(Request $request, Note $note, array &$actions): bool public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
{ {
@@ -85,15 +110,19 @@ class Conversation extends Component
return Event::next; return Event::next;
} }
// Generating URL for reply action route $from = $request->query->has('from')
$args = ['note_id' => $note->getId(), 'actor_id' => $note->getActor()->getId()]; ? $request->query->get('from')
$type = Router::ABSOLUTE_PATH; : $request->getPathInfo();
$reply_action_url = Router::url('reply_add', $args, $type);
$query_string = $request->getQueryString(); $reply_action_url = Router::url(
// Concatenating get parameter to redirect the user to where he came from 'conversation_reply_to',
$reply_action_url .= !\is_null($query_string) ? '?from=' : '&from='; [
$reply_action_url .= mb_substr($query_string, 2); 'reply_to_id' => $note->getId(),
'from' => $from,
'_fragment' => 'note-anchor-' . $note->getId(),
],
Router::ABSOLUTE_PATH,
);
$reply_action = [ $reply_action = [
'url' => $reply_action_url, 'url' => $reply_action_url,
@@ -103,79 +132,179 @@ class Conversation extends Component
]; ];
$actions[] = $reply_action; $actions[] = $reply_action;
return Event::next;
}
public function onAddExtraArgsToNoteContent(Request $request, Actor $actor, array $data, array &$extra_args): bool
{
// If Actor is adding a reply, get parent's Note id
// Else it's null
$extra_args['reply_to'] = $request->get('_route') === 'reply_add' ? (int) $request->get('note_id') : null;
return Event::next; return Event::next;
} }
/** /**
* Append on note information about user actions * Append on note information about user actions.
*
* @param array $vars Contains information related to Note currently being rendered
* @param array $result Contains keys 'actors', and 'action'. Needed to construct a string, stating who ($result['actors']), has already performed a reply ($result['action']), in the given Note (vars['note'])
*
* @return bool EventHook
*/ */
public function onAppendCardNote(array $vars, array &$result): bool public function onAppendCardNote(array $vars, array &$result): bool
{ {
// if note is the original, append on end "user replied to this" if (str_contains($vars['request']->getPathInfo(), 'conversation')) {
// if note is the reply itself: append on end "in response to user in conversation" return Event::next;
$check_user = !\is_null(Common::user());
$note = $vars['note'];
$complementary_info = '';
$reply_actor = [];
$note_replies = $note->getReplies();
// Get actors who replied
foreach ($note_replies as $reply) {
$reply_actor[] = Actor::getByPK($reply->getActorId());
} }
if (\count($reply_actor) < 1) {
// The current Note being rendered
$note = $vars['note'];
// Will have actors array, and action string
// Actors are the subjects, action is the verb (in the final phrase)
$reply_actors = F\map(
$note->getReplies(),
fn (Note $reply) => Actor::getByPK($reply->getActorId()),
);
if (empty($reply_actors)) {
return Event::next; return Event::next;
} }
// Filter out multiple replies from the same actor // Filter out multiple replies from the same actor
$reply_actor = array_unique($reply_actor, \SORT_REGULAR); $reply_actors = array_unique($reply_actors, \SORT_REGULAR);
$result[] = ['actors' => $reply_actors, 'action' => 'replied to'];
// Add to complementary info return Event::next;
foreach ($reply_actor as $actor) { }
$reply_actor_url = $actor->getUrl();
$reply_actor_nickname = $actor->getNickname();
if ($check_user && $actor->getId() === (Common::actor())->getId()) { private function getReplyToIdFromRequest(Request $request): ?int
// If the reply is yours {
$you_translation = _m('You'); if (!\is_array($request->get('post_note')) || !\array_key_exists('_next', $request->get('post_note'))) {
$prepend = "<a href={$reply_actor_url}>{$you_translation}</a>, " . ($prepend = &$complementary_info); return null;
$complementary_info = $prepend; }
} else { $next = parse_url($request->get('post_note')['_next']);
// If the repeat is from someone else if (!\array_key_exists('query', $next)) {
$complementary_info .= "<a href={$reply_actor_url}>{$reply_actor_nickname}</a>, "; return null;
} }
parse_str($next['query'], $query);
if (!\array_key_exists('reply_to_id', $query)) {
return null;
}
return (int) $query['reply_to_id'];
}
/**
* Informs **\App\Component\Posting::onAppendRightPostingBlock**, of the **current page context** in which the given
* Actor is in. This is valuable when posting within a group route, allowing \App\Component\Posting to create a
* Note **targeting** that specific Group.
*
* @param \App\Entity\Actor $actor The Actor currently attempting to post a Note
* @param null|\App\Entity\Actor $context_actor The 'owner' of the current route (e.g. Group or Actor), used to target it
*
* @return bool EventHook
*/
public function onPostingGetContextActor(Request $request, Actor $actor, ?Actor &$context_actor): bool
{
$to_note_id = $this->getReplyToIdFromRequest($request);
if (!\is_null($to_note_id)) {
// Getting the actor itself
$context_actor = Actor::getById(Note::getById((int) $to_note_id)->getActorId());
return Event::stop;
}
return Event::next;
}
/**
* Posting event to add extra information to Component\Posting form data
*
* @param array $data Transport data to be filled with reply_to_id
*
* @throws \App\Util\Exception\ClientException
* @throws \App\Util\Exception\NoSuchNoteException
*
* @return bool EventHook
*/
public function onPostingModifyData(Request $request, Actor $actor, array &$data): bool
{
$to_note_id = $this->getReplyToIdFromRequest($request);
if (!\is_null($to_note_id)) {
Note::ensureCanInteract(Note::getById($to_note_id), $actor);
$data['reply_to_id'] = $to_note_id;
} }
$complementary_info = rtrim(trim($complementary_info), ','); return Event::next;
$complementary_info .= _m(' replied to this note.'); }
$result[] = Formatting::twigRenderString($complementary_info, []);
/**
* Add minimal Note card to RightPanel template
*/
public function onPrependPostingForm(Request $request, array &$elements): bool
{
$elements[] = Formatting::twigRenderFile('cards/blocks/note_compact_wrapper.html.twig', ['note' => Note::getById((int) $request->query->get('reply_to_id'))]);
return Event::next;
}
/**
* Event launched when deleting given Note, it's deletion implies further changes to object related to this Note.
* Please note, **replies are NOT deleted**, their reply_to is only set to null since this Note no longer exists.
*
* @param \App\Entity\Note $note Note being deleted
* @param \App\Entity\Actor $actor Actor that performed the delete action
*
* @return bool EventHook
*/
public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
{
// Ensure we have the most up to date replies
Cache::delete(Note::cacheKeys($note->getId())['replies']);
DB::wrapInTransaction(fn () => F\each($note->getReplies(), fn (Note $note) => $note->setReplyTo(null)));
Cache::delete(Note::cacheKeys($note->getId())['replies']);
return Event::next;
}
/**
* Adds extra actions related to Conversation Component, that act upon/from the given Note.
*
* @param \App\Entity\Note $note Current Note being rendered
* @param array $actions Containing 'url' (Controller connected route), 'title' (used in anchor link containing the url), ?'classes' (CSS classes required for styling, if needed)
*
* @throws \App\Util\Exception\ServerException
*
* @return bool EventHook
*/
public function onAddExtraNoteActions(Request $request, Note $note, array &$actions): bool
{
if (\is_null($user = Common::user())) {
return Event::next;
}
$from = $request->query->has('from')
? $request->query->get('from')
: $request->getPathInfo();
$mute_extra_action_url = Router::url(
'conversation_mute',
[
'conversation_id' => $note->getConversationId(),
'from' => $from,
'_fragment' => 'note-anchor-' . $note->getId(),
],
Router::ABSOLUTE_PATH,
);
$actions[] = [
'title' => ConversationMute::isMuted($note, $user) ? _m('Unmute conversation') : _m('Mute conversation'),
'classes' => '',
'url' => $mute_extra_action_url,
];
return Event::next; return Event::next;
} }
public function onAddRoute(RouteLoader $r): bool /**
* Prevents new Notifications to appear for muted conversations
*
* @param Activity $activity Notification Activity
*
* @return bool EventHook
*/
public function onNewNotificationShould(Activity $activity, Actor $actor): bool
{ {
$r->connect('reply_add', '/object/note/new?to={actor_id<\d+>}&reply_to={note_id<\d+>}', [ReplyController::class, 'addReply']); if ($activity->getObjectType() === 'note' && ConversationMute::isMuted($activity, $actor)) {
$r->connect('conversation', '/conversation/{conversation_id<\d+>}', [Controller\Conversation::class, 'showConversation']);
return Event::next;
}
public function onPostingGetContextActor(Request $request, Actor $actor, ?Actor $context_actor)
{
$to_query = $request->get('actor_id');
if (!\is_null($to_query)) {
// Getting the actor itself
$context_actor = Actor::getById((int) $to_query);
return Event::stop; return Event::stop;
} }
return Event::next; return Event::next;

View File

@@ -23,8 +23,9 @@ declare(strict_types = 1);
namespace Component\Conversation\Entity; namespace Component\Conversation\Entity;
use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Router\Router; use App\Core\Router;
/** /**
* Entity class for Conversations * Entity class for Conversations
@@ -46,7 +47,6 @@ class Conversation extends Entity
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $id; private int $id;
private string $uri;
private int $initial_note_id; private int $initial_note_id;
public function setId(int $id): self public function setId(int $id): self

View File

@@ -0,0 +1,132 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Conversation\Entity;
use App\Core\Cache;
use App\Core\DB;
use App\Core\Entity;
use App\Entity\Activity;
use App\Entity\Actor;
use App\Entity\LocalUser;
use App\Entity\Note;
use DateTimeInterface;
/**
* Entity class for Conversations Mutes
*
* @category DB
* @package GNUsocial
*
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class ConversationMute extends Entity
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private int $conversation_id;
private int $actor_id;
private DateTimeInterface $created;
public function setConversationId(int $conversation_id): self
{
$this->conversation_id = $conversation_id;
return $this;
}
public function getConversationId(): int
{
return $this->conversation_id;
}
public function setActorId(int $actor_id): self
{
$this->actor_id = $actor_id;
return $this;
}
public function getActorId(): int
{
return $this->actor_id;
}
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface
{
return $this->created;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function cacheKeys(int $conversation_id, int $actor_id): array
{
return [
'mute' => "conversation-mute-{$conversation_id}-{$actor_id}",
];
}
/**
* Check if a conversation referenced by $object is muted form $actor
*/
public static function isMuted(Activity|Note|int $object, Actor|LocalUser $actor): bool
{
$conversation_id = null;
if (\is_int($object)) {
$conversation_id = $object;
} elseif ($object instanceof Note) {
$conversation_id = $object->getConversationId();
} elseif ($object instanceof Activity) {
$conversation_id = Note::getById($object->getObjectId())->getConversationId();
}
return Cache::get(
self::cacheKeys($conversation_id, $actor->getId())['mute'],
fn () => (bool) DB::count('conversation_mute', ['conversation_id' => $conversation_id, 'actor_id' => $actor->getId()]),
);
}
public static function schemaDef(): array
{
return [
'name' => 'conversation_mute',
'fields' => [
'conversation_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Conversation.id', 'multiplicity' => 'one to one', 'not null' => true, 'description' => 'The conversation being blocked'],
'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'not null' => true, 'description' => 'Who blocked the conversation'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
],
'primary key' => ['conversation_id', 'actor_id'],
'foreign keys' => [
'conversation_id_to_id_fkey' => ['conversation', ['conversation_id' => 'id']],
'actor_id_to_id_fkey' => ['actor', ['actor_id' => 'id']],
],
];
}
}

View File

@@ -0,0 +1,21 @@
{% extends 'collection/notes.html.twig' %}
{% block body %}
<div class="frame-section frame-section-padding">
{% if is_muted %}
<span class="frame-section-padding alert">
<label>Do you wish to <b>unmute</b> this conversation?</label>
{{ form(form) }}
</span>
{% else %}
<span class="frame-section-padding alert">
<label>Do you wish to <b>mute</b> this conversation?</label>
{{ form(form) }}
</span>
{% endif %}
<hr>
{{ parent() }}
</div>
{% endblock body %}

View File

@@ -1,18 +0,0 @@
{% extends 'stdgrid.html.twig' %}
{% import "/cards/note/view.html.twig" as noteView %}
{% block title %}{{ 'Reply to ' | trans }}{{ note.getActorNickname() }}{{ '\'s note.' | trans }}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/feeds.css') }}" type="text/css">
{% endblock stylesheets %}
{% block body %}
{{ parent() }}
<div class="page">
<div class="main">
{{ noteView.macro_note_minimal(note) }}
</div>
</div>
{% endblock body %}

View File

@@ -33,38 +33,28 @@ declare(strict_types = 1);
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
namespace App\Controller; namespace Component\Feed\Controller;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\VisibilityScope;
use App\Util\Common; use App\Util\Common;
use Component\Feed\Feed; use App\Util\HTML\Heading;
use Component\Feed\Util\FeedController; use Component\Collection\Util\Controller\FeedController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class Feeds extends FeedController class Feeds extends FeedController
{ {
// Can't have constants inside herestring
private $public_scope = VisibilityScope::PUBLIC;
private $instance_scope = VisibilityScope::PUBLIC | VisibilityScope::SITE;
private $message_scope = VisibilityScope::MESSAGE;
private $subscriber_scope = VisibilityScope::PUBLIC | VisibilityScope::SUBSCRIBER;
/** /**
* The Planet feed represents every local post. Which is what this instance has to share with the universe. * The Planet feed represents every local post. Which is what this instance has to share with the universe.
*/ */
public function public(Request $request): array public function public(Request $request): array
{ {
$data = Feed::query( $data = $this->query('note-local:true');
query: 'note-local:true', $page_title = _m(\is_null(Common::user()) ? 'Feed' : 'Planet');
page: $this->int('p'),
language: Common::actor()?->getTopLanguage()?->getLocale(),
);
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'collection/notes.html.twig',
'page_title' => _m(\is_null(Common::user()) ? 'Feed' : 'Planet'), 'page_title' => $page_title,
'should_format' => true, 'notes_feed_title' => (new Heading(level: 1, classes: ['feed-title'], text: $page_title)),
'notes' => $data['notes'], 'notes' => $data['notes'],
]; ];
} }
@@ -74,17 +64,12 @@ class Feeds extends FeedController
public function home(Request $request): array public function home(Request $request): array
{ {
Common::ensureLoggedIn(); Common::ensureLoggedIn();
$data = Feed::query( $data = $this->query('note-from:subscribed-person,subscribed-group,subscribed-organisation');
query: 'note-from:subscribed-person,subscribed-group,subscribed-organization,subscribed-business',
page: $this->int('p'),
language: Common::actor()?->getTopLanguage()?->getLocale(),
actor: Common::actor(),
);
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'collection/notes.html.twig',
'page_title' => _m('Home'), 'page_title' => _m('Home'),
'should_format' => true, 'notes_feed_title' => (new Heading(level: 1, classes: ['feed-title'], text: 'Home')),
'notes' => $data['notes'], 'notes' => $data['notes'],
]; ];
} }
} }

View File

@@ -23,142 +23,17 @@ declare(strict_types = 1);
namespace Component\Feed; namespace Component\Feed;
use App\Core\DB\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Entity\Actor; use App\Core\Router;
use App\Entity\Subscription; use Component\Feed\Controller as C;
use App\Util\Formatting;
use Component\Search\Util\Parser;
use Doctrine\Common\Collections\ExpressionBuilder;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
class Feed extends Component class Feed extends Component
{ {
/** public function onAddRoute(Router $r): bool
* Perform a high level query on notes or actors
*
* Supports a variety of query terms and is used both in feeds and
* in search. Uses query builders to allow for extension
*/
public static function query(string $query, int $page, ?string $language = null, ?Actor $actor = null): array
{ {
$note_criteria = null; $r->connect('feed_public', '/feed/public', [C\Feeds::class, 'public']);
$actor_criteria = null; $r->connect('feed_home', '/feed/home', [C\Feeds::class, 'home']);
if (!empty($query = trim($query))) {
[$note_criteria, $actor_criteria] = Parser::parse($query, $language, $actor);
}
$note_qb = DB::createQueryBuilder();
$actor_qb = DB::createQueryBuilder();
$note_qb->select('note')->from('App\Entity\Note', 'note')->orderBy('note.created', 'DESC')->orderBy('note.id', 'DESC');
$actor_qb->select('actor')->from('App\Entity\Actor', 'actor')->orderBy('actor.created', 'DESC')->orderBy('actor.id', 'DESC');
Event::handle('SearchQueryAddJoins', [&$note_qb, &$actor_qb, $note_criteria, $actor_criteria]);
$notes = [];
$actors = [];
if (!\is_null($note_criteria)) {
$note_qb->addCriteria($note_criteria);
}
$notes = $note_qb->getQuery()->execute();
if (!\is_null($actor_criteria)) {
$actor_qb->addCriteria($actor_criteria);
}
$actors = $actor_qb->getQuery()->execute();
// TODO: Enforce scoping on the notes before returning
return ['notes' => $notes ?? null, 'actors' => $actors ?? null];
}
public function onSearchQueryAddJoins(QueryBuilder &$note_qb, QueryBuilder &$actor_qb)
{
$note_qb->leftJoin(Subscription::class, 'subscription', Expr\Join::WITH, 'note.actor_id = subscription.subscribed')
->leftJoin(Actor::class, 'note_actor', Expr\Join::WITH, 'note.actor_id = note_actor.id');
return Event::next;
}
/**
* Convert $term to $note_expr and $actor_expr, search criteria. Handles searching for text
* notes, for different types of actors and for the content of text notes
*/
public function onSearchCreateExpression(ExpressionBuilder $eb, string $term, ?string $language, ?Actor $actor, &$note_expr, &$actor_expr)
{
if (str_contains($term, ':')) {
$term = explode(':', $term);
if (Formatting::startsWith($term[0], 'note-')) {
switch ($term[0]) {
case 'note-local':
$note_expr = $eb->eq('note.is_local', filter_var($term[1], \FILTER_VALIDATE_BOOLEAN));
break;
case 'note-types':
case 'notes-include':
case 'note-filter':
if (\is_null($note_expr)) {
$note_expr = [];
}
if (array_intersect(explode(',', $term[1]), ['text', 'words']) !== []) {
$note_expr[] = $eb->neq('note.content', null);
} else {
$note_expr[] = $eb->eq('note.content', null);
}
break;
case 'note-conversation':
$note_expr = $eb->eq('note.conversation_id', (int) trim($term[1]));
break;
case 'note-from':
case 'notes-from':
$subscribed_expr = $eb->eq('subscription.subscriber', $actor->getId());
$type_consts = [];
if ($term[1] === 'subscribed') {
$type_consts = null;
}
foreach (explode(',', $term[1]) as $from) {
if (str_starts_with($from, 'subscribed-')) {
[, $type] = explode('-', $from);
if (\in_array($type, ['actor', 'actors'])) {
$type_consts = null;
} else {
$type_consts[] = \constant(Actor::class . '::' . mb_strtoupper($type));
}
}
}
if (\is_null($type_consts)) {
$note_expr = $subscribed_expr;
} elseif (!empty($type_consts)) {
$note_expr = $eb->andX($subscribed_expr, $eb->in('note_actor.type', $type_consts));
}
break;
}
} elseif (Formatting::startsWith($term, 'actor-')) {
switch ($term[0]) {
case 'actor-types':
case 'actors-include':
case 'actor-filter':
case 'actor-local':
if (\is_null($actor_expr)) {
$actor_expr = [];
}
foreach (
[
Actor::PERSON => ['person', 'people'],
Actor::GROUP => ['group', 'groups'],
Actor::ORGANIZATION => ['org', 'orgs', 'organization', 'organizations', 'organisation', 'organisations'],
Actor::BUSINESS => ['business', 'businesses'],
Actor::BOT => ['bot', 'bots'],
] as $type => $match) {
if (array_intersect(explode(',', $term[1]), $match) !== []) {
$actor_expr[] = $eb->eq('actor.type', $type);
} else {
$actor_expr[] = $eb->neq('actor.type', $type);
}
}
break;
}
}
} else {
$note_expr = $eb->contains('note.content', $term);
}
return Event::next; return Event::next;
} }
} }

View File

@@ -1,42 +0,0 @@
{% extends 'stdgrid.html.twig' %}
{% import '/cards/note/view.html.twig' as noteView %}
{% block title %}{% if page_title is defined %}{{ page_title | trans }}{% endif %}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/feeds.css') }}" type="text/css">
{% endblock stylesheets %}
{% block body %}
<header class="feed-header">
{% if page_title is defined %}
<h1>{{ page_title | trans }} {{ 'feed' | trans }}</h1>
{% endif %}
<nav class="feed-actions" role=navigation>
{% for block in handle_event('AddFeedActions', app.request) %}
{{ block | raw }}
{% endfor %}
</nav>
</header>
{# Backwards compatibility with hAtom 0.1 #}
<main class="feed" tabindex="0" role="feed">
<div class="h-feed hfeed notes">
{% if notes is defined and notes is not empty %}
{% for conversation in notes %}
{% block current_note %}
{% if conversation is instanceof('array') %}
{{ noteView.macro_note(conversation['note'], conversation['replies']) }}
{% else %}
{{ noteView.macro_note(conversation) }}
{% endif %}
<hr tabindex="0" title="{{ 'End of note and replies.' | trans }}">
{% endblock current_note %}
{% endfor %}
{% else %}
<div id="empty-notes"><h1>{% trans %}No notes here.{% endtrans %}</h1></div>
{% endif %}
</div>
</main>
{% endblock body %}

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Feed\tests\Controller;
use App\Core\Router;
use App\Util\GNUsocialTestCase;
use Component\Feed\Controller\Feeds;
use Jchook\AssertThrows\AssertThrows;
class FeedsTest extends GNUsocialTestCase
{
use AssertThrows;
public function testPublic()
{
// This calls static::bootKernel(), and creates a "client" that is acting as the browser
$client = static::createClient();
$crawler = $client->request('GET', Router::url('feed_public'));
$this->assertResponseIsSuccessful();
}
public function testHome()
{
// This calls static::bootKernel(), and creates a "client" that is acting as the browser
$client = static::createClient();
$crawler = $client->request('GET', Router::url('feed_home'));
$this->assertResponseStatusCodeSame(302);
}
// TODO: It would be nice to actually test whether the feeds are respecting scopes and spitting
// out the expected notes... The ActivityPub plugin have a somewhat obvious way of testing it so,
// for now, having that, might fill that need, let's see
}

View File

@@ -34,11 +34,10 @@ declare(strict_types = 1);
namespace Component\FreeNetwork\Controller; namespace Component\FreeNetwork\Controller;
use App\Core\DB\DB; use App\Core\DB;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Util\Common; use App\Util\Common;
use Component\Feed\Feed; use Component\Collection\Util\Controller\FeedController;
use Component\Feed\Util\FeedController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class Feeds extends FeedController class Feeds extends FeedController
@@ -52,13 +51,9 @@ class Feeds extends FeedController
public function network(Request $request): array public function network(Request $request): array
{ {
Common::ensureLoggedIn(); Common::ensureLoggedIn();
$data = Feed::query( $data = $this->query('note-local:false');
query: 'note-local:false',
page: $this->int('p'),
language: Common::actor()?->getTopLanguage()?->getLocale(),
);
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'collection/notes.html.twig',
'page_title' => _m('Meteorites'), 'page_title' => _m('Meteorites'),
'should_format' => true, 'should_format' => true,
'notes' => $data['notes'], 'notes' => $data['notes'],
@@ -73,6 +68,7 @@ class Feeds extends FeedController
public function clique(Request $request): array public function clique(Request $request): array
{ {
Common::ensureLoggedIn(); Common::ensureLoggedIn();
// TODO: maybe make this a Collection::query
$notes = DB::dql( $notes = DB::dql(
<<<'EOF' <<<'EOF'
SELECT n FROM \App\Entity\Note AS n SELECT n FROM \App\Entity\Note AS n
@@ -86,7 +82,7 @@ class Feeds extends FeedController
EOF, EOF,
); );
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'collection/notes.html.twig',
'page_title' => _m('Planetary System'), 'page_title' => _m('Planetary System'),
'should_format' => true, 'should_format' => true,
'notes' => $notes, 'notes' => $notes,
@@ -101,13 +97,9 @@ class Feeds extends FeedController
public function federated(Request $request): array public function federated(Request $request): array
{ {
Common::ensureLoggedIn(); Common::ensureLoggedIn();
$data = Feed::query( $data = $this->query('notes-all:yeah');
query: '',
page: $this->int('p'),
language: Common::actor()?->getTopLanguage()?->getLocale(),
);
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'collection/notes.html.twig',
'page_title' => _m('Galaxy'), 'page_title' => _m('Galaxy'),
'should_format' => true, 'should_format' => true,
'notes' => $data['notes'], 'notes' => $data['notes'],

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
/** /**
* @author James Walker <james@status.net> * @author James Walker <james@status.net>
* @author Craig Andrews <candrews@integralblue.com> * @author Craig Andrews <candrews@integralblue.com>
@@ -8,17 +10,13 @@
namespace Component\FreeNetwork\Controller; namespace Component\FreeNetwork\Controller;
use App\Core\Controller;
use App\Core\Event; use App\Core\Event;
use Component\FreeNetwork\Util\Discovery; use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\XrdController; use Component\FreeNetwork\Util\XrdController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use XML_XRD;
class HostMeta extends XrdController class HostMeta extends XrdController
{ {
protected string $default_mimetype = Discovery::XRD_MIMETYPE; protected string $default_mimetype = Discovery::JRD_MIMETYPE;
public function setXRD() public function setXRD()
{ {

View File

@@ -1,4 +1,6 @@
<?php <?php
declare(strict_types = 1);
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
// GNU social is free software: you can redistribute it and/or modify // GNU social is free software: you can redistribute it and/or modify
@@ -30,7 +32,6 @@ use App\Util\Common;
use Component\FreeNetwork\Util\Discovery; use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\XrdController; use Component\FreeNetwork\Util\XrdController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class OwnerXrd extends XrdController class OwnerXrd extends XrdController
{ {

View File

@@ -1,4 +1,6 @@
<?php <?php
declare(strict_types = 1);
/* /*
* StatusNet - the distributed open-source microblogging tool * StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc. * Copyright (C) 2010, StatusNet, Inc.
@@ -69,7 +71,7 @@ class Webfinger extends XrdController
$this->xrd->subject = $this->resource; $this->xrd->subject = $this->resource;
foreach ($this->target->getAliases() as $alias) { foreach ($this->target->getAliases() as $alias) {
if ($alias != $this->xrd->subject && !in_array($alias, $this->xrd->aliases)) { if ($alias != $this->xrd->subject && !\in_array($alias, $this->xrd->aliases)) {
$this->xrd->aliases[] = $alias; $this->xrd->aliases[] = $alias;
} }
} }

View File

@@ -32,17 +32,11 @@ declare(strict_types = 1);
namespace Component\FreeNetwork\Entity; namespace Component\FreeNetwork\Entity;
use App\Core\Cache; use App\Core\DB;
use App\Core\DB\DB;
use App\Core\Entity; use App\Core\Entity;
use function App\Core\I18n\_m;
use App\Core\Log;
use App\Entity\Actor; use App\Entity\Actor;
use Component\FreeNetwork\Util\Discovery; use Component\FreeNetwork\Util\Discovery;
use DateTimeInterface; use DateTimeInterface;
use Exception;
use Plugin\ActivityPub\Util\DiscoveryHints;
use Plugin\ActivityPub\Util\Explorer;
/** /**
* Table Definition for free_network_actor_protocol * Table Definition for free_network_actor_protocol
@@ -53,27 +47,27 @@ use Plugin\ActivityPub\Util\Explorer;
class FreeNetworkActorProtocol extends Entity class FreeNetworkActorProtocol extends Entity
{ {
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart; // @codeCoverageIgnoreStart
private int $actor_id; private int $actor_id;
private ?string $protocol; private ?string $protocol = null;
private ?string $addr; private string $addr;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
public function getActorId(): int
{
return $this->actor_id;
}
public function setActorId(int $actor_id): self public function setActorId(int $actor_id): self
{ {
$this->actor_id = $actor_id; $this->actor_id = $actor_id;
return $this; return $this;
} }
public function getActorId(): int
{
return $this->actor_id;
}
public function setProtocol(?string $protocol): self public function setProtocol(?string $protocol): self
{ {
$this->protocol = $protocol; $this->protocol = \is_null($protocol) ? null : mb_substr($protocol, 0, 32);
return $this; return $this;
} }
@@ -93,14 +87,20 @@ class FreeNetworkActorProtocol extends Entity
return $this->addr; return $this->addr;
} }
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface public function getCreated(): DateTimeInterface
{ {
return $this->created; return $this->created;
} }
public function setCreated(DateTimeInterface $created): self public function setModified(DateTimeInterface $modified): self
{ {
$this->created = $created; $this->modified = $modified;
return $this; return $this;
} }
@@ -109,19 +109,14 @@ class FreeNetworkActorProtocol extends Entity
return $this->modified; return $this->modified;
} }
public function setModified(DateTimeInterface $modified): self
{
$this->modified = $modified;
return $this;
}
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
public static function protocolSucceeded(string $protocol, int|Actor $actor_id, string $addr): void public static function protocolSucceeded(string $protocol, int|Actor $actor_id, string $addr): void
{ {
$actor_id = is_int($actor_id) ? $actor_id : $actor_id->getId(); $actor_id = \is_int($actor_id) ? $actor_id : $actor_id->getId();
$attributed_protocol = self::getByPK(['actor_id' => $actor_id]); $attributed_protocol = self::getByPK(['actor_id' => $actor_id]);
if (is_null($attributed_protocol)) { if (\is_null($attributed_protocol)) {
$attributed_protocol = self::create([ $attributed_protocol = self::create([
'actor_id' => $actor_id, 'actor_id' => $actor_id,
'protocol' => $protocol, 'protocol' => $protocol,
@@ -130,14 +125,14 @@ class FreeNetworkActorProtocol extends Entity
} else { } else {
$attributed_protocol->setProtocol($protocol); $attributed_protocol->setProtocol($protocol);
} }
DB::wrapInTransaction(fn() => DB::persist($attributed_protocol)); DB::persist($attributed_protocol);
} }
public static function canIActor(string $protocol, int|Actor $actor_id): bool public static function canIActor(string $protocol, int|Actor $actor_id): bool
{ {
$actor_id = is_int($actor_id) ? $actor_id : $actor_id->getId(); $actor_id = \is_int($actor_id) ? $actor_id : $actor_id->getId();
$attributed_protocol = self::getByPK(['actor_id' => $actor_id])?->getProtocol(); $attributed_protocol = self::getByPK(['actor_id' => $actor_id])?->getProtocol();
if (is_null($attributed_protocol)) { if (\is_null($attributed_protocol)) {
// If it is not attributed, you can go ahead. // If it is not attributed, you can go ahead.
return true; return true;
} else { } else {
@@ -149,9 +144,9 @@ class FreeNetworkActorProtocol extends Entity
public static function canIAddr(string $protocol, string $target): bool public static function canIAddr(string $protocol, string $target): bool
{ {
// Normalize $addr, i.e. add 'acct:' if missing // Normalize $addr, i.e. add 'acct:' if missing
$addr = Discovery::normalize($target); $addr = Discovery::normalize($target);
$attributed_protocol = self::getByPK(['addr' => $addr])?->getProtocol(); $attributed_protocol = self::getByPK(['addr' => $addr])?->getProtocol();
if (is_null($attributed_protocol)) { if (\is_null($attributed_protocol)) {
// If it is not attributed, you can go ahead. // If it is not attributed, you can go ahead.
return true; return true;
} else { } else {
@@ -167,7 +162,7 @@ class FreeNetworkActorProtocol extends Entity
'fields' => [ 'fields' => [
'actor_id' => ['type' => 'int', 'not null' => true], 'actor_id' => ['type' => 'int', 'not null' => true],
'protocol' => ['type' => 'varchar', 'length' => 32, 'description' => 'the protocol plugin that should handle federation of this actor'], 'protocol' => ['type' => 'varchar', 'length' => 32, 'description' => 'the protocol plugin that should handle federation of this actor'],
'addr' => ['type' => 'text', 'not null' => true, 'description' => 'webfinger acct'], 'addr' => ['type' => 'text', 'not null' => true, 'description' => 'webfinger acct'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'], 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
], ],

View File

@@ -1,4 +1,6 @@
<?php <?php
declare(strict_types = 1);
/** /**
* StatusNet, the distributed open-source microblogging tool * StatusNet, the distributed open-source microblogging tool
* *
@@ -50,7 +52,7 @@ use Throwable;
*/ */
class WebfingerReconstructionException extends ServerException class WebfingerReconstructionException extends ServerException
{ {
public function __construct(string $message = '', int $code = 500, Throwable $previous = null) public function __construct(string $message = '', int $code = 500, ?Throwable $previous = null)
{ {
// We could log an entry here with the search parameters // We could log an entry here with the search parameters
parent::__construct(_m('WebFinger URI generation failed.')); parent::__construct(_m('WebFinger URI generation failed.'));

View File

@@ -21,15 +21,14 @@ declare(strict_types = 1);
namespace Component\FreeNetwork; namespace Component\FreeNetwork;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
use App\Core\HTTPClient; use App\Core\HTTPClient;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Log; use App\Core\Log;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Core\Router\Router;
use App\Entity\Activity; use App\Entity\Activity;
use App\Entity\Actor; use App\Entity\Actor;
use App\Entity\LocalUser; use App\Entity\LocalUser;
@@ -44,6 +43,7 @@ use App\Util\Exception\NicknameTakenException;
use App\Util\Exception\NicknameTooLongException; use App\Util\Exception\NicknameTooLongException;
use App\Util\Exception\NoSuchActorException; use App\Util\Exception\NoSuchActorException;
use App\Util\Exception\ServerException; use App\Util\Exception\ServerException;
use App\Util\Formatting;
use App\Util\Nickname; use App\Util\Nickname;
use Component\FreeNetwork\Controller\Feeds; use Component\FreeNetwork\Controller\Feeds;
use Component\FreeNetwork\Controller\HostMeta; use Component\FreeNetwork\Controller\HostMeta;
@@ -53,9 +53,8 @@ use Component\FreeNetwork\Util\Discovery;
use Component\FreeNetwork\Util\WebfingerResource; use Component\FreeNetwork\Util\WebfingerResource;
use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceActor; use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceActor;
use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceNote; use Component\FreeNetwork\Util\WebfingerResource\WebfingerResourceNote;
use Doctrine\Common\Collections\ExpressionBuilder;
use Exception; use Exception;
use Plugin\ActivityPub\Entity\ActivitypubActivity;
use Plugin\ActivityPub\Util\TypeResponse;
use const PREG_SET_ORDER; use const PREG_SET_ORDER;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -78,8 +77,15 @@ class FreeNetwork extends Component
public const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token'; public const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token';
public const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token'; public const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token';
public const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize'; public const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize';
private static array $protocols = [];
public function onAddRoute(RouteLoader $m): bool public function onInitializeComponent(): bool
{
Event::handle('AddFreeNetworkProtocol', [&self::$protocols]);
return Event::next;
}
public function onAddRoute(Router $m): bool
{ {
// Feeds // Feeds
$m->connect('feed_network', '/feed/network', [Feeds::class, 'network']); $m->connect('feed_network', '/feed/network', [Feeds::class, 'network']);
@@ -154,7 +160,7 @@ class FreeNetwork extends Component
$parts = explode('@', mb_substr(urldecode($resource), 5)); // 5 is strlen of 'acct:' $parts = explode('@', mb_substr(urldecode($resource), 5)); // 5 is strlen of 'acct:'
if (\count($parts) === 2) { if (\count($parts) === 2) {
[$nick, $domain] = $parts; [$nick, $domain] = $parts;
if ($domain !== $_ENV['SOCIAL_DOMAIN']) { if ($domain !== Common::config('site', 'server')) {
throw new ServerException(_m('Remote profiles not supported via WebFinger yet.')); throw new ServerException(_m('Remote profiles not supported via WebFinger yet.'));
} }
@@ -171,7 +177,7 @@ class FreeNetwork extends Component
// This means $resource is a valid url // This means $resource is a valid url
$resource_parts = parse_url($resource); $resource_parts = parse_url($resource);
// TODO: Use URLMatcher // TODO: Use URLMatcher
if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) { if ($resource_parts['host'] === Common::config('site', 'server')) {
$str = $resource_parts['path']; $str = $resource_parts['path'];
// actor_view_nickname // actor_view_nickname
$renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m'; $renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
@@ -209,9 +215,8 @@ class FreeNetwork extends Component
return Event::stop; // We got our target, stop handler execution return Event::stop; // We got our target, stop handler execution
} }
$APNote = ActivitypubActivity::getByPK(['object_uri' => $resource]); if (!\is_null($note = DB::findOneBy(Note::class, ['url' => $resource], return_null: true))) {
if ($APNote instanceof ActivitypubActivity) { $target = new WebfingerResourceNote($note);
$target = new WebfingerResourceNote(Note::getByPK(['id' => $APNote->getObjectId()]));
return Event::stop; // We got our target, stop handler execution return Event::stop; // We got our target, stop handler execution
} }
@@ -270,7 +275,7 @@ class FreeNetwork extends Component
* @throws ClientException * @throws ClientException
* @throws ServerException * @throws ServerException
*/ */
public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?TypeResponse &$response = null): bool public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?Response &$response = null): bool
{ {
if (!\in_array($route, ['freenetwork_hostmeta', 'freenetwork_hostmeta_format', 'freenetwork_webfinger', 'freenetwork_webfinger_format', 'freenetwork_ownerxrd'])) { if (!\in_array($route, ['freenetwork_hostmeta', 'freenetwork_hostmeta_format', 'freenetwork_webfinger', 'freenetwork_webfinger_format', 'freenetwork_ownerxrd'])) {
return Event::next; return Event::next;
@@ -300,6 +305,9 @@ class FreeNetwork extends Component
Discovery::XRD_MIMETYPE => new Response(content: $vars['xrd']->to('xml'), headers: $headers), Discovery::XRD_MIMETYPE => new Response(content: $vars['xrd']->to('xml'), headers: $headers),
Discovery::JRD_MIMETYPE, Discovery::JRD_MIMETYPE_OLD => new JsonResponse(data: $vars['xrd']->to('json'), headers: $headers, json: true), Discovery::JRD_MIMETYPE, Discovery::JRD_MIMETYPE_OLD => new JsonResponse(data: $vars['xrd']->to('json'), headers: $headers, json: true),
}; };
$response->headers->set('cache-control', 'no-store, no-cache, must-revalidate');
return Event::stop; return Event::stop;
} }
@@ -379,7 +387,7 @@ class FreeNetwork extends Component
$actor = null; $actor = null;
$resource_parts = explode($preMention, $target); $resource_parts = explode($preMention, $target);
if ($resource_parts[1] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) { if ($resource_parts[1] === Common::config('site', 'server')) {
$actor = LocalUser::getByPK(['nickname' => $resource_parts[0]])->getActor(); $actor = LocalUser::getByPK(['nickname' => $resource_parts[0]])->getActor();
} else { } else {
Event::handle('FreeNetworkFindMentions', [$target, &$actor]); Event::handle('FreeNetworkFindMentions', [$target, &$actor]);
@@ -408,7 +416,7 @@ class FreeNetwork extends Component
// This means $resource is a valid url // This means $resource is a valid url
$resource_parts = parse_url($url); $resource_parts = parse_url($url);
// TODO: Use URLMatcher // TODO: Use URLMatcher
if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) { if ($resource_parts['host'] === Common::config('site', 'server')) {
$str = $resource_parts['path']; $str = $resource_parts['path'];
// actor_view_nickname // actor_view_nickname
$renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m'; $renick = '/\/@(' . Nickname::DISPLAY_FMT . ')\/?/m';
@@ -489,17 +497,39 @@ class FreeNetwork extends Component
public static function notify(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool public static function notify(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool
{ {
$protocols = []; foreach (self::$protocols as $protocol) {
Event::handle('AddFreeNetworkProtocol', [&$protocols]); $protocol::freeNetworkDistribute($sender, $activity, $targets, $reason);
$delivered = [];
foreach ($protocols as $protocol) {
$protocol::freeNetworkDistribute($sender, $activity, $targets, $reason, $delivered);
} }
$failed_targets = array_udiff($targets, $delivered, fn (Actor $a, Actor $b): int => $a->getId() <=> $b->getId());
// TODO: Implement failed queues
return false; return false;
} }
public static function mentionTagToName(string $nickname, string $uri): string
{
return '@' . $nickname . '@' . parse_url($uri, \PHP_URL_HOST);
}
public static function groupTagToName(string $nickname, string $uri): string
{
return '!' . $nickname . '@' . parse_url($uri, \PHP_URL_HOST);
}
/**
* Add fediverse: query expression
* // TODO: adding WebFinger would probably be nice
*/
public function onCollectionQueryCreateExpression(ExpressionBuilder $eb, string $term, ?string $locale, ?Actor $actor, &$note_expr, &$actor_expr): bool
{
if (Formatting::startsWith($term, ['fediverse:'])) {
foreach (self::$protocols as $protocol) {
// 10 is strlen of `fediverse:`
if ($protocol::freeNetworkGrabRemote(mb_substr($term, 10))) {
break;
}
}
}
return Event::next;
}
public function onPluginVersion(array &$versions): bool public function onPluginVersion(array &$versions): bool
{ {
$versions[] = [ $versions[] = [

View File

@@ -1,4 +1,6 @@
<?php <?php
declare(strict_types = 1);
/** /**
* StatusNet - the distributed open-source microblogging tool * StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc. * Copyright (C) 2010, StatusNet, Inc.
@@ -69,7 +71,7 @@ class LinkHeader
$this->type = null; $this->type = null;
// remove uri-reference from header // remove uri-reference from header
$str = substr($str, strlen($uri_reference[0])); $str = mb_substr($str, mb_strlen($uri_reference[0]));
// parse link-params // parse link-params
$params = explode(';', $str); $params = explode(';', $str);
@@ -78,7 +80,7 @@ class LinkHeader
if (empty($param)) { if (empty($param)) {
continue; continue;
} }
list($param_name, $param_value) = explode('=', $param, 2); [$param_name, $param_value] = explode('=', $param, 2);
$param_name = trim($param_name); $param_name = trim($param_name);
$param_value = preg_replace('(^"|"$)', '', trim($param_value)); $param_value = preg_replace('(^"|"$)', '', trim($param_value));
@@ -110,18 +112,17 @@ class LinkHeader
$headers = $response->getHeader('Link'); $headers = $response->getHeader('Link');
if ($headers) { if ($headers) {
// Can get an array or string, so try to simplify the path // Can get an array or string, so try to simplify the path
if (!is_array($headers)) { if (!\is_array($headers)) {
$headers = [$headers]; $headers = [$headers];
} }
foreach ($headers as $header) { foreach ($headers as $header) {
$lh = new self($header); $lh = new self($header);
if ((is_null($rel) || $lh->rel == $rel) && (is_null($type) || $lh->type == $type)) { if ((\is_null($rel) || $lh->rel == $rel) && (\is_null($type) || $lh->type == $type)) {
return $lh->href; return $lh->href;
} }
} }
} }
return null;
} }
} }

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Component\FreeNetwork\Util\LrddMethod; namespace Component\FreeNetwork\Util\LrddMethod;
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
@@ -39,29 +41,27 @@ class LrddMethodHostMeta extends LRDDMethod
/** /**
* For RFC6415 and HTTP URIs, fetch the host-meta file * For RFC6415 and HTTP URIs, fetch the host-meta file
* and look for LRDD templates * and look for LRDD templates
*
* @param mixed $uri
*/ */
public function discover($uri) public function discover($uri)
{ {
// This is allowed for RFC6415 but not the 'WebFinger' RFC7033. // This is allowed for RFC6415 but not the 'WebFinger' RFC7033.
$try_schemes = ['https', 'http']; $try_schemes = ['https', 'http'];
$scheme = mb_strtolower(parse_url($uri, PHP_URL_SCHEME)); $scheme = mb_strtolower(parse_url($uri, \PHP_URL_SCHEME));
switch ($scheme) { switch ($scheme) {
case 'acct': case 'acct':
// We can't use parse_url data for this, since the 'host' // We can't use parse_url data for this, since the 'host'
// entry is only set if the scheme has '://' after it. // entry is only set if the scheme has '://' after it.
$parts = explode('@', parse_url($uri, PHP_URL_PATH), 2); $parts = explode('@', parse_url($uri, \PHP_URL_PATH), 2);
if (!Discovery::isAcct($uri) || count($parts) != 2) { if (!Discovery::isAcct($uri) || \count($parts) != 2) {
throw new Exception('Bad resource URI: ' . $uri); throw new Exception('Bad resource URI: ' . $uri);
} }
[, $domain] = $parts; [, $domain] = $parts;
break; break;
case 'http': case 'http':
case 'https': case 'https':
$domain = mb_strtolower(parse_url($uri, PHP_URL_HOST)); $domain = mb_strtolower(parse_url($uri, \PHP_URL_HOST));
$try_schemes = [$scheme]; $try_schemes = [$scheme];
break; break;
default: default:

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Component\FreeNetwork\Util\LrddMethod; namespace Component\FreeNetwork\Util\LrddMethod;
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
@@ -38,10 +40,7 @@ class LrddMethodLinkHtml extends LRDDMethod
* For HTTP IDs, fetch the URL and look for <link> elements * For HTTP IDs, fetch the URL and look for <link> elements
* in the HTML response. * in the HTML response.
* *
* @param mixed $uri
*
* @todo fail out of WebFinger URIs faster * @todo fail out of WebFinger URIs faster
*
*/ */
public function discover($uri) public function discover($uri)
{ {
@@ -65,7 +64,7 @@ class LrddMethodLinkHtml extends LRDDMethod
preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches); preg_match('/<head(\s[^>]*)?>(.*?)<\/head>/is', $html, $head_matches);
if (count($head_matches) != 3) { if (\count($head_matches) != 3) {
return []; return [];
} }
[, , $head_html] = $head_matches; [, , $head_html] = $head_matches;
@@ -78,23 +77,23 @@ class LrddMethodLinkHtml extends LRDDMethod
$link_type = null; $link_type = null;
preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches); preg_match('/\srel=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $rel_matches);
if (count($rel_matches) > 3) { if (\count($rel_matches) > 3) {
$link_rel = $rel_matches[3]; $link_rel = $rel_matches[3];
} elseif (count($rel_matches) > 1) { } elseif (\count($rel_matches) > 1) {
$link_rel = $rel_matches[1]; $link_rel = $rel_matches[1];
} }
preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches); preg_match('/\shref=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $href_matches);
if (count($href_matches) > 3) { if (\count($href_matches) > 3) {
$link_uri = $href_matches[3]; $link_uri = $href_matches[3];
} elseif (count($href_matches) > 1) { } elseif (\count($href_matches) > 1) {
$link_uri = $href_matches[1]; $link_uri = $href_matches[1];
} }
preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches); preg_match('/\stype=(("|\')([^\\2]*?)\\2|[^"\'\s]+)/i', $link_html, $type_matches);
if (count($type_matches) > 3) { if (\count($type_matches) > 3) {
$link_type = $type_matches[3]; $link_type = $type_matches[3];
} elseif (count($type_matches) > 1) { } elseif (\count($type_matches) > 1) {
$link_type = $type_matches[1]; $link_type = $type_matches[1];
} }

View File

@@ -1,4 +1,6 @@
<?php <?php
declare(strict_types = 1);
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
// GNU social is free software: you can redistribute it and/or modify // GNU social is free software: you can redistribute it and/or modify
@@ -36,19 +38,17 @@ class LrddMethodWebfinger extends LRDDMethod
/** /**
* Simply returns the WebFinger URL over HTTPS at the uri's domain: * Simply returns the WebFinger URL over HTTPS at the uri's domain:
* https://{domain}/.well-known/webfinger?resource={uri} * https://{domain}/.well-known/webfinger?resource={uri}
*
* @param mixed $uri
*/ */
public function discover($uri) public function discover($uri)
{ {
$parts = explode('@', parse_url($uri, PHP_URL_PATH), 2); $parts = explode('@', parse_url($uri, \PHP_URL_PATH), 2);
if (!Discovery::isAcct($uri) || count($parts) != 2) { if (!Discovery::isAcct($uri) || \count($parts) != 2) {
throw new Exception('Bad resource URI: ' . $uri); throw new Exception('Bad resource URI: ' . $uri);
} }
[, $domain] = $parts; [, $domain] = $parts;
if (!filter_var($domain, FILTER_VALIDATE_IP) if (!filter_var($domain, \FILTER_VALIDATE_IP)
&& !filter_var(gethostbyname($domain), FILTER_VALIDATE_IP)) { && !filter_var(gethostbyname($domain), \FILTER_VALIDATE_IP)) {
throw new Exception('Bad resource host.'); throw new Exception('Bad resource host.');
} }
@@ -56,7 +56,7 @@ class LrddMethodWebfinger extends LRDDMethod
Discovery::LRDD_REL, Discovery::LRDD_REL,
'https://' . $domain . '/.well-known/webfinger?resource={uri}', 'https://' . $domain . '/.well-known/webfinger?resource={uri}',
Discovery::JRD_MIMETYPE, Discovery::JRD_MIMETYPE,
true // isTemplate true, // isTemplate
); );
return [$link]; return [$link];

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Component\FreeNetwork\Util; namespace Component\FreeNetwork\Util;
use App\Core\Entity; use App\Core\Entity;
@@ -40,8 +42,6 @@ abstract class WebfingerResource
/** /**
* List of alternative IDs of a certain Actor * List of alternative IDs of a certain Actor
*
* @return array
*/ */
public function getAliases(): array public function getAliases(): array
{ {
@@ -53,7 +53,7 @@ abstract class WebfingerResource
// you've run HTTPS all the time! // you've run HTTPS all the time!
if (Common::config('fix', 'legacy_http')) { if (Common::config('fix', 'legacy_http')) {
foreach ($aliases as $alias => $id) { foreach ($aliases as $alias => $id) {
if (!strtolower(parse_url($alias, PHP_URL_SCHEME)) === 'https') { if (!mb_strtolower(parse_url($alias, \PHP_URL_SCHEME)) === 'https') {
continue; continue;
} }
$aliases[preg_replace('/^https:/i', 'http:', $alias, 1)] = $id; $aliases[preg_replace('/^https:/i', 'http:', $alias, 1)] = $id;

View File

@@ -1,10 +1,12 @@
<?php <?php
declare(strict_types = 1);
namespace Component\FreeNetwork\Util\WebfingerResource; namespace Component\FreeNetwork\Util\WebfingerResource;
use App\Core\Event; use App\Core\Event;
use App\Core\Log; use App\Core\Log;
use App\Core\Router\Router; use App\Core\Router;
use App\Entity\Actor; use App\Entity\Actor;
use App\Util\Common; use App\Util\Common;
use Component\FreeNetwork\Exception\WebfingerReconstructionException; use Component\FreeNetwork\Exception\WebfingerReconstructionException;
@@ -24,9 +26,9 @@ use XML_XRD_Element_Link;
*/ */
class WebfingerResourceActor extends WebFingerResource class WebfingerResourceActor extends WebFingerResource
{ {
const PROFILEPAGE = 'http://webfinger.net/rel/profile-page'; public const PROFILEPAGE = 'http://webfinger.net/rel/profile-page';
public function __construct(Actor $object = null) public function __construct(?Actor $object = null)
{ {
// The type argument above verifies that it's our class // The type argument above verifies that it's our class
parent::__construct($object); parent::__construct($object);
@@ -49,8 +51,9 @@ class WebfingerResourceActor extends WebFingerResource
/** /**
* Reconstruct WebFinger acct: from object * Reconstruct WebFinger acct: from object
* *
* @return array|false|mixed|string|string[]|null
* @throws WebfingerReconstructionException * @throws WebfingerReconstructionException
*
* @return null|array|false|mixed|string|string[]
*/ */
public function reconstructAcct() public function reconstructAcct()
{ {
@@ -58,7 +61,7 @@ class WebfingerResourceActor extends WebFingerResource
if (Event::handle('StartWebFingerReconstruction', [$this->object, &$acct])) { if (Event::handle('StartWebFingerReconstruction', [$this->object, &$acct])) {
// TODO: getUri may not always give us the correct host on remote users? // TODO: getUri may not always give us the correct host on remote users?
$host = parse_url($this->object->getUri(Router::ABSOLUTE_URL), PHP_URL_HOST); $host = parse_url($this->object->getUri(Router::ABSOLUTE_URL), \PHP_URL_HOST);
if (empty($this->object->getNickname()) || empty($host)) { if (empty($this->object->getNickname()) || empty($host)) {
throw new WebFingerReconstructionException(print_r($this->object, true)); throw new WebFingerReconstructionException(print_r($this->object, true));
} }
@@ -75,8 +78,11 @@ class WebfingerResourceActor extends WebFingerResource
if (Event::handle('StartWebFingerProfileLinks', [$xrd, $this->object])) { if (Event::handle('StartWebFingerProfileLinks', [$xrd, $this->object])) {
// Profile page, can give more metadata from Link header or HTML parsing // Profile page, can give more metadata from Link header or HTML parsing
$xrd->links[] = new XML_XRD_Element_Link(self::PROFILEPAGE, $xrd->links[] = new XML_XRD_Element_Link(
$this->object->getUrl(Router::ABSOLUTE_URL), 'text/html'); self::PROFILEPAGE,
$this->object->getUrl(Router::ABSOLUTE_URL),
'text/html',
);
// // XFN // // XFN
// $xrd->links[] = new XML_XRD_Element_Link('http://gmpg.org/xfn/11', // $xrd->links[] = new XML_XRD_Element_Link('http://gmpg.org/xfn/11',

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Component\FreeNetwork\Util\WebfingerResource; namespace Component\FreeNetwork\Util\WebfingerResource;
use App\Core\Event; use App\Core\Event;
@@ -22,7 +24,7 @@ use XML_XRD_Element_Link;
*/ */
class WebfingerResourceNote extends WebfingerResource class WebfingerResourceNote extends WebfingerResource
{ {
public function __construct(Note $object = null) public function __construct(?Note $object = null)
{ {
// The type argument above verifies that it's our class // The type argument above verifies that it's our class
parent::__construct($object); parent::__construct($object);
@@ -30,29 +32,37 @@ class WebfingerResourceNote extends WebfingerResource
/** /**
* Update given XRD with self's data * Update given XRD with self's data
*
* @param XML_XRD $xrd
*/ */
public function updateXRD(XML_XRD $xrd) public function updateXRD(XML_XRD $xrd)
{ {
if (Event::handle('StartWebFingerNoticeLinks', [$xrd, $this->object])) { if (Event::handle('StartWebFingerNoticeLinks', [$xrd, $this->object])) {
if ($this->object->isLocal()) { if ($this->object->isLocal()) {
$xrd->links[] = new XML_XRD_Element_Link('alternate', $xrd->links[] = new XML_XRD_Element_Link(
common_local_url('ApiStatusesShow', 'alternate',
common_local_url(
'ApiStatusesShow',
['id' => $this->object->id, ['id' => $this->object->id,
'format' => 'atom', ]), 'format' => 'atom', ],
'application/atom+xml'); ),
'application/atom+xml',
);
$xrd->links[] = new XML_XRD_Element_Link('alternate', $xrd->links[] = new XML_XRD_Element_Link(
common_local_url('ApiStatusesShow', 'alternate',
common_local_url(
'ApiStatusesShow',
['id' => $this->object->id, ['id' => $this->object->id,
'format' => 'json', ]), 'format' => 'json', ],
'application/json'); ),
'application/json',
);
} else { } else {
try { try {
$xrd->links[] = new XML_XRD_Element_Link('alternate', $xrd->links[] = new XML_XRD_Element_Link(
'alternate',
$this->object->getUrl(), $this->object->getUrl(),
'text/html'); 'text/html',
);
} catch (InvalidUrlException $e) { } catch (InvalidUrlException $e) {
// don't do a fallback in webfinger // don't do a fallback in webfinger
} }

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Component\FreeNetwork\Util; namespace Component\FreeNetwork\Util;
use App\Core\Controller; use App\Core\Controller;

View File

@@ -23,122 +23,161 @@ declare(strict_types = 1);
namespace Component\Group\Controller; namespace Component\Group\Controller;
use App\Core\ActorLocalRoles;
use App\Core\Cache; use App\Core\Cache;
use App\Core\Controller\ActorController; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Form; use App\Core\Form;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Log; use App\Core\Log;
use App\Entity\Actor;
use App\Entity as E; use App\Entity as E;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
use App\Util\Exception\DuplicateFoundException;
use App\Util\Exception\NicknameEmptyException;
use App\Util\Exception\NicknameException;
use App\Util\Exception\NicknameInvalidException;
use App\Util\Exception\NicknameNotAllowedException;
use App\Util\Exception\NicknameTakenException;
use App\Util\Exception\NicknameTooLongException;
use App\Util\Exception\NotFoundException;
use App\Util\Exception\RedirectException; use App\Util\Exception\RedirectException;
use App\Util\Exception\ServerException;
use App\Util\Form\ActorForms; use App\Util\Form\ActorForms;
use App\Util\Nickname; use App\Util\Nickname;
use Component\Group\Entity\GroupMember;
use Component\Group\Entity\LocalGroup;
use Component\Subscription\Entity\ActorSubscription;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class Group extends ActorController class Group extends Controller
{ {
public function groupViewId(Request $request, int $id)
{
return $this->handleActorById(
$id,
fn ($actor) => [
'_template' => 'group/view.html.twig',
'actor' => $actor,
],
);
}
/** /**
* View a group feed and give the option of creating it if it doesn't exist * Page that allows an actor to create a new group
*
* @throws RedirectException
* @throws ServerException
*/ */
public function groupViewNickname(Request $request, string $nickname) public function groupCreate(Request $request): array
{ {
Nickname::validate($nickname, which: Nickname::CHECK_LOCAL_GROUP); // throws if (\is_null($actor = Common::actor())) {
$group = Actor::getByNickname($nickname, type: Actor::GROUP); throw new RedirectException('security_login');
if (\is_null($group)) {
$actor = Common::actor();
if (!\is_null($actor)) {
$form = Form::create([
['create', SubmitType::class, ['label' => _m('Create this group')]],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
Log::info(
_m(
'Actor id:{actor_id} nick:{actor_nick} created the group {nickname}',
['{actor_id}' => $actor->getId(), 'actor_nick' => $actor->getNickname(), 'nickname' => $nickname],
),
);
$group = Actor::create([
'nickname' => $nickname,
'type' => Actor::GROUP,
'is_local' => true,
]);
DB::persist($group);
DB::persist(E\Subscription::create([
'subscriber' => $group->getId(),
'subscribed' => $group->getId(),
]));
DB::persist(E\Subscription::create([
'subscriber' => $actor->getId(),
'subscribed' => $group->getId(),
]));
DB::persist(E\GroupMember::create([
'group_id' => $group->getId(),
'actor_id' => $actor->getId(),
'is_admin' => true,
]));
DB::flush();
Cache::delete(Actor::cacheKeys($actor->getId())['subscriber']);
Cache::delete(Actor::cacheKeys($actor->getId())['subscribed']);
throw new RedirectException;
}
return [
'_template' => 'group/view.html.twig',
'nickname' => $nickname,
'create_form' => $form->createView(),
];
}
} }
$notes = !\is_null($group) ? DB::dql( $create_form = self::getGroupCreateForm($request, $actor);
<<<'EOF'
select n from note n
join activity a with n.id = a.object_id
join group_inbox gi with a.id = gi.activity_id
where a.object_type = 'note' and gi.group_id = :group_id
EOF,
['group_id' => $group->getId()],
) : [];
return [ return [
'_template' => 'group/view.html.twig', '_template' => 'group/create.html.twig',
'actor' => $group, 'create_form' => $create_form->createView(),
'nickname' => $group?->getNickname() ?? $nickname,
'notes' => $notes,
]; ];
} }
public function groupSettings(Request $request, string $nickname) /**
* Settings page for the group with the provided nickname, checks if the current actor can administrate given group
*
* @throws ClientException
* @throws DuplicateFoundException
* @throws NicknameEmptyException
* @throws NicknameException
* @throws NicknameInvalidException
* @throws NicknameNotAllowedException
* @throws NicknameTakenException
* @throws NicknameTooLongException
* @throws NotFoundException
* @throws ServerException
*/
public function groupSettings(Request $request, int $id): array
{ {
$group = Actor::getByNickname($nickname, type: Actor::GROUP); $local_group = DB::findOneBy(LocalGroup::class, ['actor_id' => $id]);
$actor = Common::actor(); $group_actor = $local_group->getActor();
if (!\is_null($group) && $actor->canAdmin($group)) { $actor = Common::actor();
if (!\is_null($group_actor) && $actor->canModerate($group_actor)) {
return [ return [
'_template' => 'group/settings.html.twig', '_template' => 'group/settings.html.twig',
'group' => $group, 'group' => $group_actor,
'personal_info_form' => ActorForms::personalInfo($request, $group)->createView(), 'personal_info_form' => ActorForms::personalInfo(request: $request, scope: $actor, target: $group_actor)->createView(),
'open_details_query' => $this->string('open'), 'open_details_query' => $this->string('open'),
]; ];
} else { } else {
throw new ClientException(_m('You do not have permission to edit settings for the group "{group}"', ['{group}' => $nickname]), code: 404); throw new ClientException(_m('You do not have permission to edit settings for the group "{group}"', ['{group}' => $id]), code: 404);
} }
} }
/**
* Create a new Group FormInterface getter
*
* @throws RedirectException
* @throws ServerException
*/
public static function getGroupCreateForm(Request $request, E\Actor $actor): FormInterface
{
$create_form = Form::create([
['group_nickname', TextType::class, ['label' => _m('Group nickname')]],
['group_type', ChoiceType::class, ['label' => _m('Type:'), 'multiple' => false, 'expanded' => false, 'choices' => [
_m('Group') => 'group',
_m('Organisation') => 'organisation',
]]],
['group_scope', ChoiceType::class, ['label' => _m('Is this a private group:'), 'multiple' => false, 'expanded' => false, 'choices' => [
_m('No') => 'public',
_m('Yes') => 'private',
]]],
['group_create', SubmitType::class, ['label' => _m('Create this group!')]],
]);
$create_form->handleRequest($request);
if ($create_form->isSubmitted() && $create_form->isValid()) {
$data = $create_form->getData();
$nickname = Nickname::normalize(
nickname: $data['group_nickname'],
check_already_used: true,
which: Nickname::CHECK_LOCAL_GROUP,
check_is_allowed: true,
);
$roles = ActorLocalRoles::VISITOR; // Can send direct messages to other actors
if ($data['group_scope'] === 'private') {
$roles |= ActorLocalRoles::PRIVATE_GROUP;
}
Log::info(
_m(
'Actor id:{actor_id} nick:{actor_nick} created the ' . ($roles & ActorLocalRoles::PRIVATE_GROUP ? 'private' : 'public') . ' group {nickname}',
['{actor_id}' => $actor->getId(), 'actor_nick' => $actor->getNickname(), 'nickname' => $nickname],
),
);
DB::persist($group = E\Actor::create([
'nickname' => $nickname,
'type' => E\Actor::GROUP,
'is_local' => true,
'roles' => $roles,
]));
DB::persist(LocalGroup::create([
'actor_id' => $group->getId(),
'type' => $data['group_type'],
'nickname' => $nickname,
]));
DB::persist(ActorSubscription::create([
'subscriber_id' => $group->getId(),
'subscribed_id' => $group->getId(),
]));
DB::persist(GroupMember::create([
'group_id' => $group->getId(),
'actor_id' => $actor->getId(),
// Group Owner
'roles' => ActorLocalRoles::OPERATOR | ActorLocalRoles::MODERATOR | ActorLocalRoles::PARTICIPANT | ActorLocalRoles::VISITOR,
]));
DB::flush();
Cache::delete(E\Actor::cacheKeys($actor->getId())['subscribers']);
Cache::delete(E\Actor::cacheKeys($actor->getId())['subscribed']);
throw new RedirectException();
}
return $create_form;
}
} }

View File

@@ -0,0 +1,131 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Group\Controller;
use App\Core\Cache;
use App\Core\DB;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Core\Router;
use App\Entity\Actor;
use App\Entity as E;
use App\Util\Common;
use App\Util\Exception\ClientException;
use App\Util\Exception\ServerException;
use App\Util\HTML\Heading;
use Component\Collection\Util\Controller\FeedController;
use Component\Group\Entity\LocalGroup;
use Component\Subscription\Entity\ActorSubscription;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
class GroupFeed extends FeedController
{
/**
* @throws ServerException
*/
public function groupView(Request $request, Actor $group): array
{
$actor = Common::actor();
$subscribe_form = null;
if (!\is_null($actor)
&& \is_null(Cache::get(
ActorSubscription::cacheKeys($actor, $group)['subscribed'],
fn () => DB::findOneBy('actor_subscription', [
'subscriber_id' => $actor->getId(),
'subscribed_id' => $group->getId(),
], return_null: true),
))
) {
$subscribe_form = Form::create([['subscribe', SubmitType::class, ['label' => _m('Subscribe to this group')]]]);
$subscribe_form->handleRequest($request);
if ($subscribe_form->isSubmitted() && $subscribe_form->isValid()) {
DB::persist(ActorSubscription::create([
'subscriber_id' => $actor->getId(),
'subscribed_id' => $group->getId(),
]));
DB::flush();
Cache::delete(E\Actor::cacheKeys($group->getId())['subscribers']);
Cache::delete(E\Actor::cacheKeys($actor->getId())['subscribed']);
Cache::delete(ActorSubscription::cacheKeys($actor, $group)['subscribed']);
}
}
$notes = DB::dql(<<<'EOF'
SELECT n FROM \App\Entity\Note AS n
WHERE n.id IN (
SELECT act.object_id FROM \App\Entity\Activity AS act
WHERE act.object_type = 'note' AND act.id IN
(SELECT att.activity_id FROM \Component\Notification\Entity\Notification AS att WHERE att.target_id = :id)
)
ORDER BY n.created DESC
EOF, ['id' => $group->getId()]);
return [
'_template' => 'group/view.html.twig',
'actor' => $group,
'nickname' => $group->getNickname(),
'notes' => $notes,
'notes_feed_title' => (new Heading(1, [], $group->getNickname() . '\'s feed')),
'subscribe_form' => $subscribe_form?->createView(),
];
}
/**
* @throws ClientException
* @throws ServerException
*/
public function groupViewId(Request $request, int $id): array
{
$group = Actor::getById($id);
if (\is_null($group) || !$group->isGroup()) {
throw new ClientException(_m('No such group.'), 404);
}
if ($group->getIsLocal()) {
return [
'_redirect' => Router::url('group_actor_view_nickname', ['nickname' => $group->getNickname()]),
'actor' => $group,
];
}
return $this->groupView($request, $group);
}
/**
* View a group feed by its nickname
*
* @param string $nickname The group's nickname to be shown
*
* @throws ClientException
* @throws ServerException
*/
public function groupViewNickname(Request $request, string $nickname): array
{
$group = LocalGroup::getActorByNickname($nickname);
if (\is_null($group)) {
throw new ClientException(_m('No such group.'), 404);
}
return $this->groupView($request, $group);
}
}

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -17,7 +19,7 @@
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Entity; namespace Component\Group\Entity;
use App\Core\Entity; use App\Core\Entity;
@@ -74,7 +76,7 @@ class GroupJoinQueue extends Entity
'description' => 'Holder for group join requests awaiting moderation.', 'description' => 'Holder for group join requests awaiting moderation.',
'fields' => [ 'fields' => [
'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'many to one', 'name' => 'group_join_queue_actor_id_fkey', 'not null' => true, 'description' => 'remote or local actor making the request'], 'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'many to one', 'name' => 'group_join_queue_actor_id_fkey', 'not null' => true, 'description' => 'remote or local actor making the request'],
'group_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Group.id', 'multiplicity' => 'many to one', 'name' => 'group_join_queue_group_id_fkey', 'not null' => true, 'description' => 'remote or local group to join, if any'], 'group_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Group.id', 'multiplicity' => 'many to one', 'name' => 'group_join_queue_group_id_fkey', 'not null' => true, 'description' => 'remote or local group to join, if any'],
], ],
'primary key' => ['actor_id', 'group_id'], 'primary key' => ['actor_id', 'group_id'],
'indexes' => [ 'indexes' => [

View File

@@ -19,8 +19,9 @@ declare(strict_types = 1);
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Entity; namespace Component\Group\Entity;
use App\Core\ActorLocalRoles;
use App\Core\Entity; use App\Core\Entity;
use DateTimeInterface; use DateTimeInterface;
@@ -44,8 +45,7 @@ class GroupMember extends Entity
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $group_id; private int $group_id;
private int $actor_id; private int $actor_id;
private ?bool $is_admin; private int $roles = ActorLocalRoles::VISITOR;
private ?string $uri;
private DateTimeInterface $created; private DateTimeInterface $created;
private DateTimeInterface $modified; private DateTimeInterface $modified;
@@ -71,26 +71,15 @@ class GroupMember extends Entity
return $this->actor_id; return $this->actor_id;
} }
public function setIsAdmin(?bool $is_admin): self public function setRoles(int $roles): self
{ {
$this->is_admin = $is_admin; $this->roles = $roles;
return $this; return $this;
} }
public function getIsAdmin(): ?bool public function getRoles(): int
{ {
return $this->is_admin; return $this->roles;
}
public function setUri(?string $uri): self
{
$this->uri = $uri;
return $this;
}
public function getUri(): ?string
{
return $this->uri;
} }
public function setCreated(DateTimeInterface $created): self public function setCreated(DateTimeInterface $created): self
@@ -123,18 +112,14 @@ class GroupMember extends Entity
return [ return [
'name' => 'group_member', 'name' => 'group_member',
'fields' => [ 'fields' => [
'group_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'group_member_group_id_fkey', 'not null' => true, 'description' => 'foreign key to group table'], 'group_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'group_member_group_id_fkey', 'not null' => true, 'description' => 'foreign key to group table'],
'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'group_member_actor_id_fkey', 'not null' => true, 'description' => 'foreign key to actor table'], 'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'name' => 'group_member_actor_id_fkey', 'not null' => true, 'description' => 'foreign key to actor table'],
'is_admin' => ['type' => 'bool', 'default' => false, 'description' => 'is this actor an admin?'], 'roles' => ['type' => 'int', 'not null' => true, 'default' => ActorLocalRoles::VISITOR, 'description' => 'Bitmap of permissions this actor has'],
'uri' => ['type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'], 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
], ],
'primary key' => ['group_id', 'actor_id'], 'primary key' => ['group_id', 'actor_id'],
'unique keys' => [ 'indexes' => [
'group_member_uri_key' => ['uri'],
],
'indexes' => [
'group_member_actor_id_idx' => ['actor_id'], 'group_member_actor_id_idx' => ['actor_id'],
'group_member_created_idx' => ['created'], 'group_member_created_idx' => ['created'],
'group_member_actor_id_created_idx' => ['actor_id', 'created'], 'group_member_actor_id_created_idx' => ['actor_id', 'created'],

View File

@@ -0,0 +1,174 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/soci
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as publ
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public Li
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Group\Entity;
use App\Core\DB;
use App\Core\Entity;
use App\Entity\Actor;
use App\Util\Exception\NicknameEmptyException;
use App\Util\Exception\NicknameException;
use App\Util\Exception\NicknameInvalidException;
use App\Util\Exception\NicknameNotAllowedException;
use App\Util\Exception\NicknameTakenException;
use App\Util\Exception\NicknameTooLongException;
use App\Util\Nickname;
use DateTimeInterface;
/**
* Entity for local groups
*
* @category DB
* @package GNUsocial
*
* @author Zach Copley <zach@status.net>
* @copyright 2010 StatusNet Inc.
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2020-2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class LocalGroup extends Entity
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private int $actor_id;
private string $nickname;
private string $type = 'group';
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setActorId(int $actor_id): self
{
$this->actor_id = $actor_id;
return $this;
}
public function getActorId(): int
{
return $this->actor_id;
}
public function setNickname(string $nickname): self
{
$this->nickname = mb_substr($nickname, 0, 64);
return $this;
}
public function getNickname(): string
{
return $this->nickname;
}
public function setType(string $type): self
{
$this->type = mb_substr($type, 0, 64);
return $this;
}
public function getType(): string
{
return $this->type;
}
public function setCreated(DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
public function getCreated(): DateTimeInterface
{
return $this->created;
}
public function setModified(DateTimeInterface $modified): self
{
$this->modified = $modified;
return $this;
}
public function getModified(): DateTimeInterface
{
return $this->modified;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public function getActor()
{
return DB::findOneBy(Actor::class, ['id' => $this->actor_id]);
}
public static function getByNickname(string $nickname): ?self
{
return DB::findOneBy(self::class, ['nickname' => $nickname]);
}
public static function getActorByNickname(string $nickname): ?Actor
{
return DB::findOneBy(Actor::class, ['nickname' => $nickname, 'type' => Actor::GROUP]);
}
/**
* Checks if desired nickname is allowed, and in case it is, it sets Actor's nickname cache to newly set nickname
*
* @param string $nickname Desired NEW nickname (do not use in local user creation)
*
* @throws NicknameEmptyException
* @throws NicknameException
* @throws NicknameInvalidException
* @throws NicknameNotAllowedException
* @throws NicknameTakenException
* @throws NicknameTooLongException
*
* @return $this
*/
public function setNicknameSanitizedAndCached(string $nickname): self
{
$nickname = Nickname::normalize($nickname, check_already_used: true, which: Nickname::CHECK_LOCAL_GROUP, check_is_allowed: true);
$this->setNickname($nickname);
$this->getActor()->setNickname($nickname);
/// XXX: cache?
return $this;
}
public static function schemaDef(): array
{
return [
'name' => 'local_group',
'description' => 'Record for a user group on the local site, with some additional info not in user_group',
'fields' => [
'actor_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Group.id', 'multiplicity' => 'one to one', 'name' => 'local_group_group_id_fkey', 'not null' => true, 'description' => 'group represented'],
'nickname' => ['type' => 'varchar', 'not null' => true, 'length' => 64, 'description' => 'group represented'],
'type' => ['type' => 'varchar', 'not null' => true, 'default' => 'group', 'length' => 64, 'description' => 'Group or Organisation'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
'modified' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
],
'primary key' => ['actor_id'],
'unique keys' => [
'local_group_nickname_key' => ['nickname'],
],
];
}
}

View File

@@ -24,51 +24,61 @@ namespace Component\Group;
use App\Core\Event; use App\Core\Event;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Core\Router\Router; use App\Entity\Activity;
use App\Entity\Actor; use App\Entity\Actor;
use App\Util\Common; use App\Util\Common;
use App\Util\HTML; use App\Util\HTML;
use App\Util\Nickname; use App\Util\Nickname;
use Component\Group\Controller as C; use Component\Group\Controller as C;
use Component\Tag\Controller\Tag as TagController; use Component\Group\Entity\LocalGroup;
use Component\Notification\Notification;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class Group extends Component class Group extends Component
{ {
public function onAddRoute(RouteLoader $r): bool public function onAddRoute(Router $r): bool
{ {
$r->connect(id: 'group_actor_view_id', uri_path: '/group/{id<\d+>}', target: [C\Group::class, 'groupViewId']); $r->connect(id: 'group_actor_view_id', uri_path: '/group/{id<\d+>}', target: [C\GroupFeed::class, 'groupViewId']);
$r->connect(id: 'group_actor_view_nickname', uri_path: '/!{nickname<' . Nickname::DISPLAY_FMT . '>}', target: [C\Group::class, 'groupViewNickname'], options: ['is_system_path' => false]); $r->connect(id: 'group_actor_view_nickname', uri_path: '/!{nickname<' . Nickname::DISPLAY_FMT . '>}', target: [C\GroupFeed::class, 'groupViewNickname']);
$r->connect(id: 'group_settings', uri_path: '/!{nickname<' . Nickname::DISPLAY_FMT . '>}/settings', target: [C\Group::class, 'groupSettings'], options: ['is_system_path' => false]); $r->connect(id: 'group_create', uri_path: '/group/new', target: [C\Group::class, 'groupCreate']);
$r->connect(id: 'group_actor_settings', uri_path: '/group/{id<\d+>}/settings', target: [C\Group::class, 'groupSettings']);
return Event::next; return Event::next;
} }
/** /**
* Add an <a href=group_settings> to the profile card for groups, if the current actor can access them * Enqueues a notification for an Actor (such as person or group) which means
* it shows up in their home feed and such.
*/
public function onNewNotificationStart(Actor $sender, Activity $activity, array $targets = [], ?string $reason = null): bool
{
foreach ($targets as $target) {
if ($target->isGroup()) {
// The Group announces to its subscribers
Notification::notify(
sender: $target,
activity: $activity,
targets: $target->getSubscribers(),
reason: $reason,
);
}
}
return Event::next;
}
/**
* Add an <a href=group_actor_settings> to the profile card for groups, if the current actor can access them
*/ */
public function onAppendCardProfile(array $vars, array &$res): bool public function onAppendCardProfile(array $vars, array &$res): bool
{ {
$actor = Common::actor(); $actor = Common::actor();
$group = $vars['actor']; $group = $vars['actor'];
if (!\is_null($actor) && $group->isGroup() && $actor->canAdmin($group)) { if (!\is_null($actor) && $group->isGroup()) {
$url = Router::url('group_settings', ['nickname' => $group->getNickname()]); if ($actor->canModerate($group)) {
$res[] = HTML::html(['hr' => '', 'a' => ['attrs' => ['href' => $url, 'title' => _m('Edit group settings')], 'p' => _m('Group settings')]]); $url = Router::url('group_actor_settings', ['id' => $group->getId()]);
} $res[] = HTML::html(['a' => ['attrs' => ['href' => $url, 'title' => _m('Edit group settings'), 'class' => 'profile-extra-actions'], _m('Group settings')]]);
return Event::next; }
}
public function onPopulateSettingsTabs(Request $request, string $section, array &$tabs)
{
if ($section === 'profile' && $request->get('_route') === 'group_settings') {
$nickname = $request->get('nickname');
$group = Actor::getByNickname($nickname, type: Actor::GROUP);
$tabs[] = [
'title' => 'Self tags',
'desc' => 'Add or remove tags on this group',
'id' => 'settings-self-tags',
'controller' => TagController::settingsSelfTags($request, $group, 'settings-self-tags-details'),
];
} }
return Event::next; return Event::next;
} }
@@ -78,27 +88,46 @@ class Group extends Component
*/ */
private function getGroupFromContext(Request $request): ?Actor private function getGroupFromContext(Request $request): ?Actor
{ {
if (str_starts_with($request->get('_route'), 'group_actor_view_')) { if (\is_array($request->get('post_note')) && \array_key_exists('_next', $request->get('post_note'))) {
if (!\is_null($id = $request->get('id'))) { $next = parse_url($request->get('post_note')['_next']);
return Actor::getById((int) $id); $match = Router::match($next['path']);
} elseif (!\is_null($nickname = $request->get('nickname'))) { $route = $match['_route'];
return Actor::getByNickname($nickname, type: Actor::GROUP); $identifier = $match['id'] ?? $match['nickname'] ?? null;
} else {
$route = $request->get('_route');
$identifier = $request->get('id') ?? $request->get('nickname');
}
if (str_starts_with($route, 'group_actor_view_')) {
switch ($route) {
case 'group_actor_view_nickname':
return LocalGroup::getActorByNickname($identifier);
case 'group_actor_view_id':
return Actor::getById((int) $identifier);
} }
} }
return null; return null;
} }
public function onPostingFillTargetChoices(Request $request, Actor $actor, array &$targets) public function onPostingFillTargetChoices(Request $request, Actor $actor, array &$targets): bool
{ {
$group = $this->getGroupFromContext($request); $group = $this->getGroupFromContext($request);
if (!\is_null($group)) { if (!\is_null($group)) {
$nick = '!' . $group->getNickname(); $nick = "!{$group->getNickname()}";
$targets[$nick] = $nick; $targets[$nick] = $group->getId();
} }
return Event::next; return Event::next;
} }
public function onPostingGetContextActor(Request $request, Actor $actor, ?Actor $context_actor) /**
* Indicates the context in which Posting's form is to be presented. Passing on $context_actor to Posting's
* onAppendRightPostingBlock event, the Group a given $actor is currently browsing.
*
* Makes it possible to automagically fill in the targets (aka the Group which this $request route is connected to)
* in the Posting's form.
*
* @param null|Actor $context_actor Actor group, if current route is part of an existing Group set of routes
*/
public function onPostingGetContextActor(Request $request, Actor $actor, ?Actor &$context_actor): bool
{ {
$ctx = $this->getGroupFromContext($request); $ctx = $this->getGroupFromContext($request);
if (!\is_null($ctx)) { if (!\is_null($ctx)) {

View File

@@ -0,0 +1,10 @@
<details class="frame-section section-details-title">
<summary class="details-summary-title">
<strong>
{% trans %}Create a group{% endtrans %}
</strong>
</summary>
<form method="POST" class="section-form">
{{ form(create_form) }}
</form>
</details>

View File

@@ -0,0 +1,5 @@
{% extends 'stdgrid.html.twig' %}
{% block body %}
{{ form(create_form) }}
{% endblock body %}

View File

@@ -1,19 +1,13 @@
{% extends 'base.html.twig' %} {% extends 'base.html.twig' %}
{% import 'settings/macros.html.twig' as macros %} {% import 'cards/macros/settings.html.twig' as macros %}
{% block stylesheets %}
{{ parent() }}
<link rel="preload" href="{{ asset('assets/default_theme/css/pages/settings.css') }}" as="style" type="text/css">
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/settings.css') }}">
{% endblock stylesheets %}
{% block body %} {% block body %}
<nav class='section-settings'> <nav class='section-settings'>
<h2>Settings</h2> <h1>Settings</h1>
<ul> <ul>
<li> <li>
{% set profile_tabs = [{'title': 'Personal Info', 'desc': 'Nickname, Homepage, Bio, Self Tags and more.', 'id': 'settings-personal-info', 'form': personal_info_form}] %} {% set profile_tabs = [{'title': 'Personal Info', 'desc': 'Nickname, Homepage, Bio and more.', 'id': 'settings-personal-info', 'form': personal_info_form}] %}
{% set profile_tabs = profile_tabs|merge(handle_event('PopulateSettingsTabs', app.request, 'profile')) %} {% set profile_tabs = profile_tabs|merge(handle_event('PopulateSettingsTabs', app.request, 'profile')) %}
{{ macros.settings_details_container('Profile', 'Personal Information, Avatar and Profile', 'settings-profile-details', profile_tabs, _context) }} {{ macros.settings_details_container('Profile', 'Personal Information, Avatar and Profile', 'settings-profile-details', profile_tabs, _context) }}
</li> </li>

View File

@@ -1,47 +1,16 @@
{% extends 'stdgrid.html.twig' %} {% extends 'collection/notes.html.twig' %}
{% import '/cards/note/view.html.twig' as noteView %}
{% set nickname = nickname|escape %} {% set nickname = nickname|escape %}
{% block title %}{{ nickname }}{% endblock %} {% block title %}{{ nickname }}{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/feeds.css') }}" type="text/css">
{% endblock stylesheets %}
{% block body %} {% block body %}
{% if actor is defined and actor is not null %} {% if actor is defined and actor is not null %}
{% block profile_view %} {% block profile_view %}
{% include 'cards/profile/view.html.twig' with { 'actor': actor } only %} {% include 'cards/blocks/profile.html.twig' with { 'actor': actor } only %}
{% endblock profile_view %} {% endblock profile_view %}
<hr>
<main class="feed" tabindex="0" role="feed"> {% if notes is defined %}
<div class="h-feed hfeed notes"> {{ parent() }}
{% if notes is defined and notes is not empty %} {% endif %}
{% for conversation in notes %}
{% block current_note %}
{% if conversation is instanceof('array') %}
{{ noteView.macro_note(conversation['note'], conversation['replies']) }}
{% else %}
{{ noteView.macro_note(conversation) }}
{% endif %}
<hr tabindex="0" title="{{ 'End of note and replies.' | trans }}">
{% endblock current_note %}
{% endfor %}
{% else %}
<div id="empty-notes"><h1>{% trans %}No notes here.{% endtrans %}</h1></div>
{% endif %}
</div>
</main>
{% else %}
<div class="section-padding section-widget">
<p>{% trans with { '%group%': nickname } %}The group <em>%group%</em> doesn't exist.{% endtrans %}</p>
{% if create_form is defined and create_form is not null %}
<p>{% trans %}Would you like to create it?{% endtrans %}</p>
{{ form(create_form) }}
{% endif %}
</div>
{% endif %} {% endif %}
{% endblock body %} {% endblock body %}

View File

@@ -19,10 +19,12 @@ declare(strict_types = 1);
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}} // }}}
namespace App\Tests\Entity; namespace Component\Group\tests\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Entity\Actor;
use App\Util\GNUsocialTestCase; use App\Util\GNUsocialTestCase;
use Component\Group\Entity\LocalGroup;
use Jchook\AssertThrows\AssertThrows; use Jchook\AssertThrows\AssertThrows;
class GroupTest extends GNUsocialTestCase class GroupTest extends GNUsocialTestCase
@@ -31,8 +33,8 @@ class GroupTest extends GNUsocialTestCase
public function testGetActor() public function testGetActor()
{ {
$group = DB::findOneBy('local_group', ['nickname' => 'taken_group']); $group = DB::findOneBy(LocalGroup::class, ['nickname' => 'taken_public_group']);
$actor = DB::findOneBy('actor', ['nickname' => 'taken_group']); $actor = DB::findOneBy(Actor::class, ['nickname' => 'taken_public_group']);
static::assertSame($actor, $group->getActor()); static::assertObjectEquals($actor, $group->getActor());
} }
} }

View File

@@ -25,16 +25,16 @@ namespace Component\Language\Controller;
use App\Core\Cache; use App\Core\Cache;
use App\Core\Controller; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Form; use App\Core\Form;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Entity\ActorLanguage;
use App\Entity\Language as LangEntity;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\NoLoggedInUser; use App\Util\Exception\NoLoggedInUser;
use App\Util\Exception\RedirectException; use App\Util\Exception\RedirectException;
use App\Util\Exception\ServerException; use App\Util\Exception\ServerException;
use App\Util\Form\FormFields; use App\Util\Form\FormFields;
use Component\Language\Entity\ActorLanguage;
use Component\Language\Entity\Language as LangEntity;
use Functional as F; use Functional as F;
use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@@ -70,7 +70,7 @@ class Language extends Controller
['actor_id' => $user->getId()], ['actor_id' => $user->getId()],
); );
$new_langs = array_udiff($selected_langs, $existing_langs, fn ($l, $r) => $l->getId() <=> $r->getId()); $new_langs = array_udiff($selected_langs, $existing_langs, fn ($l, $r) => $l->getId() <=> $r->getId());
$removing_langs = array_udiff($existing_langs, $selected_langs, fn ($l, $r) => $l->getId() <=> $r->getId()); $removing_langs = array_udiff($existing_langs, $selected_langs, fn ($l, $r) => $l->getId() <=> $r->getId());
foreach ($new_langs as $l) { foreach ($new_langs as $l) {
DB::persist(ActorLanguage::create(['actor_id' => $user->getId(), 'language_id' => $l->getId(), 'ordering' => 0])); DB::persist(ActorLanguage::create(['actor_id' => $user->getId(), 'language_id' => $l->getId(), 'ordering' => 0]));
@@ -134,12 +134,12 @@ class Language extends Controller
// Stay on same page, but force update and prevent resubmission // Stay on same page, but force update and prevent resubmission
throw new RedirectException('settings_sort_languages'); throw new RedirectException('settings_sort_languages');
} else { } else {
throw new RedirectException('settings', ['open' => 'account', '_fragment' => 'save_account_info_languages']); throw new RedirectException('person_actor_settings', ['id' => $user->getId(), 'open' => 'settings-language-details', '_fragment' => 'settings-language-details']);
} }
} }
return [ return [
'_template' => 'settings/sort_languages.html.twig', '_template' => 'language/sort.html.twig',
'form' => $form->createView(), 'form' => $form->createView(),
]; ];
} }

View File

@@ -21,11 +21,13 @@ declare(strict_types = 1);
// }}} // }}}
namespace App\Entity; namespace Component\Language\Entity;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Entity\Actor;
use App\Entity\LocalUser;
use App\Util\Common; use App\Util\Common;
use Functional as F; use Functional as F;
@@ -69,16 +71,17 @@ class ActorLanguage extends Entity
return $this->language_id; return $this->language_id;
} }
public function getOrdering(): int
{
return $this->ordering;
}
public function setOrdering(int $ordering): self public function setOrdering(int $ordering): self
{ {
$this->ordering = $ordering; $this->ordering = $ordering;
return $this; return $this;
} }
public function getOrdering(): int
{
return $this->ordering;
}
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode

View File

@@ -21,12 +21,14 @@ declare(strict_types = 1);
// }}} // }}}
namespace App\Entity; namespace Component\Language\Entity;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Entity\Actor;
use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use DateTimeInterface; use DateTimeInterface;
use Functional as F; use Functional as F;
@@ -46,9 +48,9 @@ class Language extends Entity
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $id; private int $id;
private string $locale; private ?string $locale = null;
private string $long_display; private ?string $long_display = null;
private string $short_display; private ?string $short_display = null;
private DateTimeInterface $created; private DateTimeInterface $created;
public function setId(int $id): self public function setId(int $id): self
@@ -62,35 +64,35 @@ class Language extends Entity
return $this->id; return $this->id;
} }
public function setLocale(string $locale): self public function setLocale(?string $locale): self
{ {
$this->locale = $locale; $this->locale = \is_null($locale) ? null : mb_substr($locale, 0, 64);
return $this; return $this;
} }
public function getLocale(): string public function getLocale(): ?string
{ {
return $this->locale; return $this->locale;
} }
public function setLongDisplay(string $long_display): self public function setLongDisplay(?string $long_display): self
{ {
$this->long_display = $long_display; $this->long_display = \is_null($long_display) ? null : mb_substr($long_display, 0, 64);
return $this; return $this;
} }
public function getLongDisplay(): string public function getLongDisplay(): ?string
{ {
return $this->long_display; return $this->long_display;
} }
public function setShortDisplay(string $short_display): self public function setShortDisplay(?string $short_display): self
{ {
$this->short_display = $short_display; $this->short_display = \is_null($short_display) ? null : mb_substr($short_display, 0, 12);
return $this; return $this;
} }
public function getShortDisplay(): string public function getShortDisplay(): ?string
{ {
return $this->short_display; return $this->short_display;
} }
@@ -105,6 +107,7 @@ class Language extends Entity
{ {
return $this->created; return $this->created;
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
@@ -113,7 +116,7 @@ class Language extends Entity
return Cache::getHashMapKey( return Cache::getHashMapKey(
map_key: 'languages-id', map_key: 'languages-id',
key: (string) $id, key: (string) $id,
calculate_map: fn () => F\reindex(DB::dql('select l from language l'), fn (self $l) => (string) $l->getId()), calculate_map: fn () => F\reindex(DB::dql('SELECT l FROM \Component\Language\Entity\Language AS l'), fn (self $l) => (string) $l->getId()),
); );
} }
@@ -122,7 +125,7 @@ class Language extends Entity
return Cache::getHashMapKey( return Cache::getHashMapKey(
'languages', 'languages',
$locale, $locale,
calculate_map: fn () => F\reindex(DB::dql('select l from language l'), fn (self $l) => $l->getLocale()), calculate_map: fn () => F\reindex(DB::dql('SELECT l FROM \Component\Language\Entity\Language AS l'), fn (self $l) => $l->getLocale()),
); );
} }
@@ -135,7 +138,7 @@ class Language extends Entity
{ {
$langs = Cache::getHashMap( $langs = Cache::getHashMap(
'languages', 'languages',
fn () => F\reindex(DB::dql('select l from language l'), fn (self $l) => $l->getLocale()), fn () => F\reindex(DB::dql('SELECT l FROM \Component\Language\Entity\Language AS l'), fn (self $l) => $l->getLocale()),
); );
return array_merge(...F\map(array_values($langs), fn ($l) => $l->toChoiceFormat())); return array_merge(...F\map(array_values($langs), fn ($l) => $l->toChoiceFormat()));
@@ -159,12 +162,12 @@ class Language extends Entity
$preferred_language_choices = $actor->getPreferredLanguageChoices($context_actor); $preferred_language_choices = $actor->getPreferredLanguageChoices($context_actor);
ksort($language_choices); ksort($language_choices);
if ($use_short_display ?? Common::config('posting', 'use_short_language_display')) { if ($use_short_display ?? Common::config('posting', 'use_short_language_display')) {
$key = array_key_first($preferred_language_choices); $key = array_key_first($preferred_language_choices);
$locale = $preferred_language_choices[$key]; $language = $preferred_language_choices[$key];
unset($preferred_language_choices[$key], $language_choices[$key]); unset($preferred_language_choices[$key], $language_choices[$key]);
$short_display = self::getByLocale($locale)->getShortDisplay(); $short_display = $language->getShortDisplay();
$preferred_language_choices[$short_display] = trim($locale); $preferred_language_choices[$short_display] = ($locale = $language->getLocale());
$language_choices[$short_display] = trim($locale); $language_choices[$short_display] = $locale;
} }
return [$language_choices, $preferred_language_choices]; return [$language_choices, $preferred_language_choices];
} }
@@ -175,10 +178,10 @@ class Language extends Entity
'name' => 'language', 'name' => 'language',
'description' => 'all known languages', 'description' => 'all known languages',
'fields' => [ 'fields' => [
'id' => ['type' => 'serial', 'not null' => true, 'description' => 'unique identifier'], 'id' => ['type' => 'serial', 'not null' => true, 'description' => 'unique identifier'],
'locale' => ['type' => 'varchar', 'length' => 64, 'description' => 'The locale identifier for the language of a note. 2-leter-iso-language-code_4-leter-script-code_2-leter-iso-country-code, but kept longer in case we get a different format'], 'locale' => ['type' => 'varchar', 'length' => 64, 'description' => 'The locale identifier for the language of a note. 2-leter-iso-language-code_4-leter-script-code_2-leter-iso-country-code, but kept longer in case we get a different format'],
'long_display' => ['type' => 'varchar', 'length' => 64, 'description' => 'The long display string for the language, in english (translated later)'], 'long_display' => ['type' => 'varchar', 'length' => 64, 'description' => 'The long display string for the language, in english (translated later)'],
'short_display' => ['type' => 'varchar', 'length' => 12, 'description' => 'The short display string for the language (used for the first option)'], 'short_display' => ['type' => 'varchar', 'length' => 12, 'description' => 'The short display string for the language (used for the first option)'],
'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'],
], ],
'primary key' => ['id'], 'primary key' => ['id'],

View File

@@ -23,13 +23,13 @@ namespace Component\Language;
use App\Core\Event; use App\Core\Event;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Entity\Actor; use App\Entity\Actor;
use App\Entity\ActorLanguage;
use App\Entity\Note; use App\Entity\Note;
use App\Util\Formatting; use App\Util\Formatting;
use App\Util\Functional as GSF; use App\Util\Functional as GSF;
use Component\Language\Controller as C; use Component\Language\Controller as C;
use Component\Language\Entity\ActorLanguage;
use Doctrine\Common\Collections\ExpressionBuilder; use Doctrine\Common\Collections\ExpressionBuilder;
use Doctrine\ORM\Query\Expr; use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
@@ -38,20 +38,20 @@ use Symfony\Component\HttpFoundation\Request;
class Language extends Component class Language extends Component
{ {
public function onAddRoute(RouteLoader $r) public function onAddRoute(Router $r): bool
{ {
$r->connect('settings_sort_languages', '/settings/sort_languages', [C\Language::class, 'sortLanguages']); $r->connect('settings_sort_languages', '/settings/sort_languages', [C\Language::class, 'sortLanguages']);
return Event::next; return Event::next;
} }
public function onFilterNoteList(?Actor $actor, array &$notes, Request $request) public function onFilterNoteList(?Actor $actor, array &$notes, Request $request): bool
{ {
if (\is_null($actor)) { if (\is_null($actor)) {
return Event::next; return Event::next;
} }
$notes = F\select( $notes = F\select(
$notes, $notes,
fn (Note $n) => \in_array($n->getLanguageId(), ActorLanguage::getActorRelatedLanguagesIds($actor)), fn (Note $n) => \is_null($n->getLanguageId()) || \in_array($n->getLanguageId(), ActorLanguage::getActorRelatedLanguagesIds($actor)),
); );
return Event::next; return Event::next;
@@ -60,7 +60,7 @@ class Language extends Component
/** /**
* Populate $note_expr or $actor_expr with an expression to match a language * Populate $note_expr or $actor_expr with an expression to match a language
*/ */
public function onSearchCreateExpression(ExpressionBuilder $eb, string $term, ?string $language, ?Actor $actor, &$note_expr, &$actor_expr) public function onCollectionQueryCreateExpression(ExpressionBuilder $eb, string $term, ?string $locale, ?Actor $actor, &$note_expr, &$actor_expr): bool
{ {
$search_term = str_contains($term, ':') ? explode(':', $term)[1] : $term; $search_term = str_contains($term, ':') ? explode(':', $term)[1] : $term;
@@ -90,26 +90,40 @@ class Language extends Component
$note_expr = $temp_note_expr; $note_expr = $temp_note_expr;
$actor_expr = $temp_actor_expr; $actor_expr = $temp_actor_expr;
return Event::stop; return Event::stop;
} elseif (Formatting::startsWith($term, GSF::cartesianProduct(['-', '_'], ['note', 'post'], ['lang', 'language'], [':']))) { } elseif (Formatting::startsWith($term, GSF::cartesianProduct([['note', 'post'], ['lang', 'language'], [':']], separator: ['-', '_']))) {
$note_expr = $temp_note_expr; $note_expr = $temp_note_expr;
return Event::stop; return Event::stop;
} elseif (Formatting::startsWith($term, GSF::cartesianProduct(['-', '_'], ['note', 'post'], ['author', 'actor', 'people', 'person'], ['lang', 'language'], [':']))) { } elseif (Formatting::startsWith($term, GSF::cartesianProduct([['note', 'post'], ['author', 'actor', 'people', 'person'], ['lang', 'language'], [':']], separator: ['-', '_']))) {
$note_expr = $temp_note_actor_expr; $note_expr = $temp_note_actor_expr;
return Event::stop; return Event::stop;
} elseif (Formatting::startsWith($term, GSF::cartesianProduct(['-', '_'], ['actor', 'people', 'person'], ['lang', 'language'], [':']))) { } elseif (Formatting::startsWith($term, GSF::cartesianProduct([['actor', 'people', 'person'], ['lang', 'language'], [':']], separator: ['-', '_']))) {
$actor_expr = $temp_actor_expr; $actor_expr = $temp_actor_expr;
return Event::stop; return Event::stop;
} }
return Event::next; return Event::next;
} }
public function onSearchQueryAddJoins(QueryBuilder &$note_qb, QueryBuilder &$actor_qb): bool public function onCollectionQueryAddJoins(QueryBuilder &$note_qb, QueryBuilder &$actor_qb): bool
{ {
$note_qb->leftJoin('App\Entity\Language', 'note_language', Expr\Join::WITH, 'note.language_id = note_language.id') $note_aliases = $note_qb->getAllAliases();
->leftJoin('App\Entity\ActorLanguage', 'actor_language', Expr\Join::WITH, 'note.actor_id = actor_language.actor_id') if (!\in_array('note_language', $note_aliases)) {
->leftJoin('App\Entity\Language', 'note_actor_language', Expr\Join::WITH, 'note_actor_language.id = actor_language.language_id'); $note_qb->leftJoin('Component\Language\Entity\Language', 'note_language', Expr\Join::WITH, 'note.language_id = note_language.id');
$actor_qb->leftJoin('App\Entity\ActorLanguage', 'actor_language', Expr\Join::WITH, 'actor.id = actor_language.actor_id') }
->leftJoin('App\Entity\Language', 'language', Expr\Join::WITH, 'actor_language.language_id = language.id'); if (!\in_array('actor_language', $note_aliases)) {
$note_qb->leftJoin('Component\Language\Entity\ActorLanguage', 'actor_language', Expr\Join::WITH, 'note.actor_id = actor_language.actor_id');
}
if (!\in_array('note_actor_language', $note_aliases)) {
$note_qb->leftJoin('Component\Language\Entity\Language', 'note_actor_language', Expr\Join::WITH, 'note_actor_language.id = actor_language.language_id');
}
$actor_aliases = $note_qb->getAllAliases();
if (!\in_array('actor_language', $actor_aliases)) {
$actor_qb->leftJoin('Component\Language\Entity\ActorLanguage', 'actor_language', Expr\Join::WITH, 'actor.id = actor_language.actor_id');
}
if (!\in_array('language', $actor_aliases)) {
$actor_qb->leftJoin('Component\Language\Entity\Language', 'language', Expr\Join::WITH, 'actor_language.language_id = language.id');
}
return Event::next; return Event::next;
} }
} }

View File

@@ -1,8 +1,8 @@
{% extends 'base.html.twig' %} {% extends 'base.html.twig' %}
{% block body %} {% block body %}
<div class="section-widget section-widget-padded"> <div class="frame-section frame-section-padding">
<h3>{{ 'Put the languages in the order you\'d like to see them in your language selection dropdown, when posting' | trans}}</h3> <h3>{% trans %}Put the languages in the order you'd like to see them in your language selection dropdown, when posting{% endtrans %}</h3>
{{ form(form) }} {{ form(form) }}
</div> </div>
{% endblock %} {% endblock %}

View File

@@ -25,15 +25,15 @@ namespace Component\LeftPanel\Controller;
use App\Core\Cache; use App\Core\Cache;
use App\Core\Controller; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Form; use App\Core\Form;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Router\Router; use App\Core\Router;
use App\Entity\Feed; use App\Entity\Feed;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
use App\Util\Exception\RedirectException; use App\Util\Exception\RedirectException;
use Component\Feed\Util\FeedController; use Component\Collection\Util\Controller\FeedController;
use Functional as F; use Functional as F;
use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;

View File

@@ -22,12 +22,11 @@ declare(strict_types = 1);
namespace Component\LeftPanel; namespace Component\LeftPanel;
use App\Core\Cache; use App\Core\Cache;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Core\Router\RouteLoader; use App\Core\Router;
use App\Core\Router\Router;
use App\Entity\Actor; use App\Entity\Actor;
use App\Entity\Feed; use App\Entity\Feed;
use App\Util\Exception\ClientException; use App\Util\Exception\ClientException;
@@ -36,13 +35,18 @@ use Component\LeftPanel\Controller as C;
class LeftPanel extends Component class LeftPanel extends Component
{ {
public function onAddRoute(RouteLoader $r): bool public function onAddRoute(Router $r): bool
{ {
$r->connect('edit_feeds', '/edit-feeds', C\EditFeeds::class); $r->connect('edit_feeds', '/edit-feeds', C\EditFeeds::class);
return Event::next; return Event::next;
} }
public function onAppendFeed(Actor $actor, string $title, string $route, array $route_params) /**
* @throws \App\Util\Exception\DuplicateFoundException
* @throws \App\Util\Exception\ServerException
* @throws ClientException
*/
public function onAppendFeed(Actor $actor, string $title, string $route, array $route_params): bool
{ {
$cache_key = Feed::cacheKey($actor); $cache_key = Feed::cacheKey($actor);
$feeds = Feed::getFeeds($actor); $feeds = Feed::getFeeds($actor);
@@ -67,17 +71,4 @@ class LeftPanel extends Component
return Event::stop; return Event::stop;
} }
} }
/**
* Output our dedicated stylesheet
*
* @param array $styles stylesheets path
*
* @return bool hook value; true means continue processing, false means stop
*/
public function onEndShowStyles(array &$styles, string $route): bool
{
$styles[] = 'components/Left/assets/css/view.css';
return Event::next;
}
} }

View File

@@ -2,38 +2,52 @@
{% block stylesheets %} {% block stylesheets %}
{{ parent() }} {{ parent() }}
<link rel="stylesheet" href="{{ asset('assets/default_theme/css/pages/feeds.css') }}" type="text/css"> <link rel="stylesheet" href="{{ asset('assets/default_theme/pages/feeds.css') }}" type="text/css">
{% endblock stylesheets %} {% endblock stylesheets %}
{% macro edit_feeds_form_row(child) %}
<div class="form-row">
{{ form_label(child) }}
{{ form_widget(child) }}
</div>
{% endmacro %}
{% block body %} {% block body %}
<div class="section-widget"> <div class="frame-section">
<form class="section-form" action="{{ path('edit_feeds') }}" method="post"> <form class="section-form" action="{{ path('edit_feeds') }}" method="post">
<h1 class="frame-section-title">{% trans %}Edit feed navigation links{% endtrans %}</h1>
<fieldset>
<legend class="section-form-legend">{{ "Edit feed navigation links" | trans }}</legend>
{# Since the form is not separated into individual groups, this happened #} {# Since the form is not separated into individual groups, this happened #}
{{ form_start(edit_feeds) }} {{ form_start(edit_feeds) }}
{% for child in edit_feeds.children %} {{ form_errors(edit_feeds) }}
{% if 'row_url' in child.vars.block_prefixes %} <section class="container-grid">
<div class="section-widget section-padding"> {% for child in edit_feeds.children %}
{{ form_label(child) }} {% if 'row_url' in child.vars.block_prefixes %}
{{ form_widget(child) }} <div class="frame-section frame-section-padding">
{% elseif 'row_title' in child.vars.block_prefixes %} {{ _self.edit_feeds_form_row(child) }}
{{ form_label(child) }} {% elseif 'row_title' in child.vars.block_prefixes %}
{{ form_widget(child) }} {{ _self.edit_feeds_form_row(child) }}
{% elseif 'row_order' in child.vars.block_prefixes %} {% elseif 'row_order' in child.vars.block_prefixes %}
{{ form_label(child) }} {{ _self.edit_feeds_form_row(child) }}
{{ form_widget(child) }} {% elseif 'row_remove' in child.vars.block_prefixes %}
{% elseif 'row_remove' in child.vars.block_prefixes %} {{ _self.edit_feeds_form_row(child) }}
{{ form_label(child) }} </div>
{{ form_widget(child) }} {% endif %}
</div> {% endfor %}
{% endif %} </section>
{% endfor %}
<div class="form-row">
{{ form_row(edit_feeds.update_exisiting) }}
{{ form_row(edit_feeds.reset) }}
</div>
<hr>
<section class="frame-section frame-section-padding">
<h2>{% trans %}Add a new feed{% endtrans %}</h2>
{{ form_rest(edit_feeds) }}
</section>
{{ form_end(edit_feeds) }} {{ form_end(edit_feeds) }}
</fieldset>
</form> </form>
</div> </div>

View File

@@ -1,25 +1,24 @@
{% block leftpanel %} {% block leftpanel %}
<label class="panel-left-icon" for="panel-left-toggle" aria-hidden="true" <label class="panel-left-icon" for="toggle-panel-left" tabindex="-1">{{ icon('menu', 'icon icon-left') | raw }}</label>
tabindex="-1">{{ icon('menu', 'icon icon-left') | raw }}</label> <a id="anchor-left-panel" class="anchor-hidden" tabindex="0" title="{% trans %}Press tab followed by a space to access left panel{% endtrans %}"></a>
<input type="checkbox" id="panel-left-toggle" aria-hidden="true" tabindex="-1"> <input type="checkbox" id="toggle-panel-left" tabindex="0" title="{% trans %}Open left panel{% endtrans %}">
<section class="header-panel section-panel-left"> <aside class="section-panel section-panel-left">
<a id="anchor-left-panel" class="anchor-hidden" title="{{ 'Press tab to access selected region!' | trans }}"></a> <section class="panel-content accessibility-target">
<aside class="panel-content accessibility-target"> {% if app.user %}
{% if app.user %} <section class='frame-section frame-section-padding' title="{% trans %}Your profile information{% endtrans %}">
<section class='section-widget section-padding' title="{{ 'Your profile information.' | trans }}"> {% block profile_view %}{% include 'cards/blocks/profile.html.twig' with { actor: current_actor } %}{% endblock profile_view %}
{% block profile_view %}{% include 'cards/profile/view.html.twig' with { actor: current_actor } %}{% endblock profile_view %} {{ block("profile_current_actor", "cards/blocks/navigation.html.twig") }}
{{ block("profile_current_actor", "cards/navigation/view.html.twig") }} </section>
</section> {% else %}
{% else %} <section>
<section> {{ block("profile_security", "cards/blocks/navigation.html.twig") }}
{{ block("profile_security", "cards/navigation/view.html.twig") }} </section>
</section> {% endif %}
{% endif %}
{{ block("feeds", "cards/navigation/view.html.twig") }} {{ block("feeds", "cards/blocks/navigation.html.twig") }}
{{ block("footer", "cards/navigation/view.html.twig") }} {{ block("footer", "cards/blocks/navigation.html.twig") }}
</aside>
</section> </section>
</aside>
{% endblock leftpanel %} {% endblock leftpanel %}

View File

@@ -21,7 +21,7 @@ declare(strict_types = 1);
namespace Component\Link\Entity; namespace Component\Link\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Event; use App\Core\Event;
use App\Core\GSFile; use App\Core\GSFile;
@@ -49,9 +49,9 @@ class Link extends Entity
// {{{ Autocode // {{{ Autocode
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $id; private int $id;
private ?string $url; private ?string $url = null;
private ?string $url_hash; private ?string $url_hash = null;
private ?string $mimetype; private ?string $mimetype = null;
private DateTimeInterface $modified; private DateTimeInterface $modified;
public function setId(int $id): self public function setId(int $id): self
@@ -65,20 +65,20 @@ class Link extends Entity
return $this->id; return $this->id;
} }
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(?string $url): self public function setUrl(?string $url): self
{ {
$this->url = $url; $this->url = $url;
return $this; return $this;
} }
public function getUrl(): ?string
{
return $this->url;
}
public function setUrlHash(?string $url_hash): self public function setUrlHash(?string $url_hash): self
{ {
$this->url_hash = $url_hash; $this->url_hash = \is_null($url_hash) ? null : mb_substr($url_hash, 0, 64);
return $this; return $this;
} }
@@ -89,7 +89,7 @@ class Link extends Entity
public function setMimetype(?string $mimetype): self public function setMimetype(?string $mimetype): self
{ {
$this->mimetype = $mimetype; $this->mimetype = \is_null($mimetype) ? null : mb_substr($mimetype, 0, 50);
return $this; return $this;
} }
@@ -98,18 +98,6 @@ class Link extends Entity
return $this->mimetype; return $this->mimetype;
} }
public function getMimetypeMajor(): ?string
{
$mime = $this->getMimetype();
return \is_null($mime) ? $mime : GSFile::mimetypeMajor($mime);
}
public function getMimetypeMinor(): ?string
{
$mime = $this->getMimetype();
return \is_null($mime) ? $mime : GSFile::mimetypeMinor($mime);
}
public function setModified(DateTimeInterface $modified): self public function setModified(DateTimeInterface $modified): self
{ {
$this->modified = $modified; $this->modified = $modified;
@@ -138,7 +126,7 @@ class Link extends Entity
{ {
if (Common::isValidHttpUrl($url)) { if (Common::isValidHttpUrl($url)) {
// If the URL is a local one, do not create a Link to it // If the URL is a local one, do not create a Link to it
if (parse_url($url, \PHP_URL_HOST) === $_ENV['SOCIAL_DOMAIN']) { if (parse_url($url, \PHP_URL_HOST) === Common::config('site', 'server')) {
Log::warning("It was attempted to create a Link to a local location {$url}."); Log::warning("It was attempted to create a Link to a local location {$url}.");
// Forbidden // Forbidden
throw new InvalidArgumentException(message: "A Link can't point to a local location ({$url}), it must be a remote one", code: 400); throw new InvalidArgumentException(message: "A Link can't point to a local location ({$url}), it must be a remote one", code: 400);
@@ -172,6 +160,18 @@ class Link extends Entity
} }
} }
public function getMimetypeMajor(): ?string
{
$mime = $this->getMimetype();
return \is_null($mime) ? $mime : GSFile::mimetypeMajor($mime);
}
public function getMimetypeMinor(): ?string
{
$mime = $this->getMimetype();
return \is_null($mime) ? $mime : GSFile::mimetypeMinor($mime);
}
public static function schemaDef(): array public static function schemaDef(): array
{ {
return [ return [

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -19,7 +21,7 @@
namespace Component\Link\Entity; namespace Component\Link\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Core\Event; use App\Core\Event;
use DateTimeInterface; use DateTimeInterface;
@@ -40,7 +42,7 @@ class NoteToLink extends Entity
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $link_id; private int $link_id;
private int $note_id; private int $note_id;
private \DateTimeInterface $modified; private DateTimeInterface $modified;
public function setLinkId(int $link_id): self public function setLinkId(int $link_id): self
{ {
@@ -74,6 +76,7 @@ class NoteToLink extends Entity
{ {
return $this->modified; return $this->modified;
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
@@ -81,22 +84,16 @@ class NoteToLink extends Entity
* Create an instance of NoteToLink or fill in the * Create an instance of NoteToLink or fill in the
* properties of $obj with the associative array $args. Doesn't * properties of $obj with the associative array $args. Doesn't
* persist the result * persist the result
*
* @param null|mixed $obj
*/ */
public static function create(array $args, $obj = null) public static function create(array $args, bool $_delegated_call = false): static
{ {
$link = DB::find('link', ['id' => $args['link_id']]); $link = DB::find('link', ['id' => $args['link_id']]);
$note = DB::find('note', ['id' => $args['note_id']]); $note = DB::find('note', ['id' => $args['note_id']]);
Event::handle('NewLinkFromNote', [$link, $note]); Event::handle('NewLinkFromNote', [$link, $note]);
$obj = new self(); $obj = new self();
return parent::create($args, $obj); return parent::createOrUpdate(obj: $obj, args: $args);
} }
/**
* @param int $note_id
* @return mixed
*/
public static function removeWhereNoteId(int $note_id): mixed public static function removeWhereNoteId(int $note_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -108,11 +105,6 @@ class NoteToLink extends Entity
); );
} }
/**
* @param int $link_id
* @param int $note_id
* @return mixed
*/
public static function removeWhere(int $link_id, int $note_id): mixed public static function removeWhere(int $link_id, int $note_id): mixed
{ {
return DB::dql( return DB::dql(
@@ -125,10 +117,6 @@ class NoteToLink extends Entity
); );
} }
/**
* @param int $link_id
* @return mixed
*/
public static function removeWhereLinkId(int $link_id): mixed public static function removeWhereLinkId(int $link_id): mixed
{ {
return DB::dql( return DB::dql(

View File

@@ -23,9 +23,10 @@ declare(strict_types = 1);
namespace Component\Link; namespace Component\Link;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Event; use App\Core\Event;
use App\Core\Modules\Component; use App\Core\Modules\Component;
use App\Entity\Actor;
use App\Entity\Note; use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use App\Util\HTML; use App\Util\HTML;
@@ -34,22 +35,37 @@ use InvalidArgumentException;
class Link extends Component class Link extends Component
{ {
/**
* Note that this persists both a Link and a NoteToLink
*
* @return [Entity\Link, NoteToLink]
*/
public static function maybeCreateLink(string $url, int $note_id): array
{
try {
$link = Entity\Link::getOrCreate($url);
DB::persist($note_link = NoteToLink::create(['link_id' => $link->getId(), 'note_id' => $note_id]));
return ['link' => $link, 'note_to_link' => $note_link];
} catch (InvalidArgumentException) {
return ['link' => null, 'note_to_link' => null];
}
}
/** /**
* Extract URLs from $content and create the appropriate Link and NoteToLink entities * Extract URLs from $content and create the appropriate Link and NoteToLink entities
*/ */
public function onProcessNoteContent(Note $note, string $content): bool public function onProcessNoteContent(Note $note, string $content, string $content_type, array $process_note_content_extra_args = []): bool
{ {
$ignore = $process_note_content_extra_args['ignoreLinks'] ?? [];
if (Common::config('attachments', 'process_links')) { if (Common::config('attachments', 'process_links')) {
$matched_urls = []; $matched_urls = [];
preg_match_all($this->getURLRegex(), $content, $matched_urls); preg_match_all($this->getURLRegex(), $content, $matched_urls);
$matched_urls = array_unique($matched_urls[1]); $matched_urls = array_unique($matched_urls[1]);
foreach ($matched_urls as $match) { foreach ($matched_urls as $match) {
try { if (\in_array($match, $ignore)) {
$link_id = Entity\Link::getOrCreate($match)->getId();
DB::persist(NoteToLink::create(['link_id' => $link_id, 'note_id' => $note->getId()]));
} catch (InvalidArgumentException) {
continue; continue;
} }
self::maybeCreateLink($match, $note_id);
} }
} }
return Event::next; return Event::next;
@@ -259,9 +275,9 @@ class Link extends Component
return HTML::html(['a' => ['attrs' => $attrs, $url]], options: ['indent' => false]); return HTML::html(['a' => ['attrs' => $attrs, $url]], options: ['indent' => false]);
} }
public function onNoteDeleteRelated(Note &$note): bool public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
{ {
NoteToLink::removeWhereNoteId($note->getId()); DB::wrapInTransaction(fn () => NoteToLink::removeWhereNoteId($note->getId()));
return Event::next; return Event::next;
} }
} }

View File

@@ -35,7 +35,7 @@ declare(strict_types = 1);
namespace Component\Notification\Controller; namespace Component\Notification\Controller;
use App\Core\Controller; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Util\Common; use App\Util\Common;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -53,11 +53,11 @@ class Feed extends Controller
WHERE n.id IN ( WHERE n.id IN (
SELECT act.object_id FROM \App\Entity\Activity AS act SELECT act.object_id FROM \App\Entity\Activity AS act
WHERE act.object_type = 'note' AND act.id IN WHERE act.object_type = 'note' AND act.id IN
(SELECT att.activity_id FROM \Component\Notification\Entity\Notification AS att WHERE att.target_id = :id) (SELECT att.activity_id FROM \Component\Notification\Entity\Notification AS att WHERE att.target_id = :target_id)
) )
EOF, ['id' => $user->getId()]); EOF, [':target_id' => $user->getId()]);
return [ return [
'_template' => 'feed/feed.html.twig', '_template' => 'collection/notes.html.twig',
'page_title' => _m('Notifications'), 'page_title' => _m('Notifications'),
'should_format' => true, 'should_format' => true,
'notes' => $notes, 'notes' => $notes,

View File

@@ -0,0 +1,105 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
namespace Component\Notification\Entity;
use App\Core\Entity;
/**
* Entity for object attentions
*
* An attention is a form of persistent notification.
* It exists together and for as long as the object it belongs to.
* Creating an attention requires creating a Notification.
*
* @category DB
* @package GNUsocial
*
* @author Zach Copley <zach@status.net>
* @copyright 2010 StatusNet Inc.
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
* @author Diogo Peralta Cordeiro <@diogo.site>
* @copyright 2021-2022 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Attention extends Entity
{
// {{{ Autocode
// @codeCoverageIgnoreStart
private string $object_type;
private int $object_id;
private int $target_id;
public function setObjectType(string $object_type): self
{
$this->object_type = mb_substr($object_type, 0, 32);
return $this;
}
public function getObjectType(): string
{
return $this->object_type;
}
public function setObjectId(int $object_id): self
{
$this->object_id = $object_id;
return $this;
}
public function getObjectId(): int
{
return $this->object_id;
}
public function setTargetId(int $target_id): self
{
$this->target_id = $target_id;
return $this;
}
public function getTargetId(): int
{
return $this->target_id;
}
// @codeCoverageIgnoreEnd
// }}} Autocode
public static function schemaDef(): array
{
return [
'name' => 'attention',
'description' => 'Attentions to actors (these are not mentions)',
'fields' => [
'object_type' => ['type' => 'varchar', 'length' => 32, 'not null' => true, 'description' => 'the name of the table this object refers to'],
'object_id' => ['type' => 'int', 'not null' => true, 'description' => 'id in the referenced table'],
'target_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Actor.id', 'multiplicity' => 'one to one', 'not null' => true, 'description' => 'actor_id for feed receiver'],
],
'primary key' => ['object_type', 'object_id', 'target_id'],
'indexes' => [
'attention_object_id_idx' => ['object_id'],
'attention_target_id_idx' => ['target_id'],
],
];
}
}

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@@ -19,24 +21,24 @@
namespace Component\Notification\Entity; namespace Component\Notification\Entity;
use App\Core\DB\DB; use App\Core\DB;
use App\Core\Entity; use App\Core\Entity;
use App\Entity\Activity; use App\Entity\Activity;
use App\Entity\Actor; use App\Entity\Actor;
use DateTimeInterface; use DateTimeInterface;
/** /**
* Entity for attentions * Entity for Notifications
*
* A Notification when isolated is a form of transient notification.
* When together with a persistent form of notification such as attentions or mentions,
* it records that the target was notified - which avoids re-notifying upon objects reconstructions.
* *
* @category DB * @category DB
* @package GNUsocial * @package GNUsocial
* *
* @author Zach Copley <zach@status.net> * @author Diogo Peralta Cordeiro <@diogo.site>
* @copyright 2010 StatusNet Inc. * @copyright 2021-2022 Free Software Foundation, Inc http://www.fsf.org
* @author Mikael Nordfeldth <mmn@hethane.se>
* @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
* @author Hugo Sales <hugo@hsal.es>
* @copyright 2020-2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/ */
class Notification extends Entity class Notification extends Entity
@@ -45,9 +47,9 @@ class Notification extends Entity
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
private int $activity_id; private int $activity_id;
private int $target_id; private int $target_id;
private ?string $reason; private ?string $reason = null;
private \DateTimeInterface $created; private DateTimeInterface $created;
private \DateTimeInterface $modified; private DateTimeInterface $modified;
public function setActivityId(int $activity_id): self public function setActivityId(int $activity_id): self
{ {
@@ -73,7 +75,7 @@ class Notification extends Entity
public function setReason(?string $reason): self public function setReason(?string $reason): self
{ {
$this->reason = $reason; $this->reason = \is_null($reason) ? null : mb_substr($reason, 0, 191);
return $this; return $this;
} }
@@ -107,9 +109,6 @@ class Notification extends Entity
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
// }}} Autocode // }}} Autocode
/**
* @return Actor
*/
public function getTarget(): Actor public function getTarget(): Actor
{ {
return Actor::getById($this->getTargetId()); return Actor::getById($this->getTargetId());
@@ -122,21 +121,26 @@ class Notification extends Entity
*/ */
public static function getNotificationTargetIdsByActivity(int|Activity $activity_id): array public static function getNotificationTargetIdsByActivity(int|Activity $activity_id): array
{ {
$notifications = DB::findBy('notification', ['activity_id' => is_int($activity_id) ? $activity_id : $activity_id->getId()]); $notifications = DB::findBy(self::class, ['activity_id' => \is_int($activity_id) ? $activity_id : $activity_id->getId()]);
$targets = []; $targets = [];
foreach ($notifications as $notification) { foreach ($notifications as $notification) {
$targets[] = $notification->getTargetId(); $targets[] = $notification->getTargetId();
} }
return $targets; return $targets;
} }
/**
* @param int|Activity $activity_id
* @return array
*/
public function getNotificationTargetsByActivity(int|Activity $activity_id): array public function getNotificationTargetsByActivity(int|Activity $activity_id): array
{ {
return DB::findBy('actor', ['id' => $this->getNotificationTargetIdsByActivity($activity_id)]); return DB::findBy(Actor::class, ['id' => $this->getNotificationTargetIdsByActivity($activity_id)]);
}
public static function getAllActivitiesTargetedAtActor(Actor $actor): array
{
return DB::dql(<<<'EOF'
SELECT act FROM \App\Entity\Activity AS act
WHERE act.object_type = 'note' AND act.id IN
(SELECT att.activity_id FROM \Component\Notification\Entity\Notification AS att WHERE att.target_id = :id)
EOF, ['id' => $actor->getId()]);
} }
public static function schemaDef(): array public static function schemaDef(): array
@@ -154,7 +158,7 @@ class Notification extends Entity
'primary key' => ['activity_id', 'target_id'], 'primary key' => ['activity_id', 'target_id'],
'indexes' => [ 'indexes' => [
'attention_activity_id_idx' => ['activity_id'], 'attention_activity_id_idx' => ['activity_id'],
'attention_target_id_idx' => ['target_id'], 'attention_target_id_idx' => ['target_id'],
], ],
]; ];
} }

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