DataModule.pm 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. package Trog::DataModule;
  2. use v5.36;
  3. use re '/aa';
  4. use FindBin::libs;
  5. use List::Util;
  6. use File::Copy;
  7. use Path::Tiny();
  8. use Ref::Util();
  9. use File::Basename qw{basename};
  10. use File::Slurper();
  11. use JSON::MaybeXS();
  12. use JSON::Validator::Schema::Troglodyne();
  13. use Time::HiRes();
  14. use Trog::Themes();
  15. use Trog::Log qw{:all};
  16. use Trog::Utils;
  17. use Trog::Auth();
  18. =head1 QUERY FORMAT
  19. The $query_language and $query_help variables are presented to the user as to how to use the search box in the tCMS header.
  20. =head1 POST STRUCTURE
  21. Posts generally need to have the following:
  22. data: Brief description of content, or the content itself.
  23. content_type: What this content actually is. Used to filter into the appropriate pages.
  24. href: Primary link. This is the subject of a news post, or a link to the item itself. Can be local or remote.
  25. local_href: Backup link. Automatically created link to a static cache of the content.
  26. title: Title of the content. Used as link name for the 'href' attribute.
  27. user: User was banned for this post
  28. id: Internal identifier in datastore for the post.
  29. tags: array ref of appropriate tags.
  30. created: timestamp of creation of this version of the post
  31. version: revision # of this post.
  32. =head1 CONSTRUCTOR
  33. =head2 new(Config::Simple $config)
  34. Try not to do expensive things here.
  35. =cut
  36. sub new ( $class, $config ) {
  37. $config = $config->vars();
  38. return bless( $config, $class );
  39. }
  40. =head1 ABSTRACT METHODS
  41. Subclasses must implement all of these; the stubs here do nothing but die.
  42. count() belongs to this set as well, and is documented with the rest of the
  43. querying interface below.
  44. =head2 lang() = STRING $language
  45. The name of the query language this data model understands, shown to the user
  46. beside the search bar.
  47. =head2 help() = STRING $help
  48. Documentation for that query language, shown to the user alongside it.
  49. =head2 read($query) = ARRAYREF $posts
  50. Every post the data model holds, as an arrayref of hashrefs. Filtering is
  51. get()'s job unless your storage engine can do it more cheaply itself, in which
  52. case honour $query here and override get() too.
  53. =head2 write($posts)
  54. Commit an arrayref of posts to storage. Called by add() once the posts have
  55. been filtered and validated; don't validate again here.
  56. =head2 tags() = ARRAYREF $tags
  57. Every tag known to the datastore, for building tag pickers.
  58. =cut
  59. #It is required that subclasses implement this
  60. sub lang ($self) { ... }
  61. sub help ($self) { ... }
  62. sub read ( $self, $query = {} ) { ... }
  63. sub write ($self) { ... }
  64. sub count ($self) { ... }
  65. sub tags ($self) { ... }
  66. =head1 METHODS
  67. =head2 get(%request)
  68. Queries the data model. Should return the following:
  69. id => Filter down to just the post by ID. May be subsequently filtered by ACL, resulting in a 404 (which is good, as it does not disclose info).
  70. version => if id is passed, return the provided post version rather than the most recent one
  71. tags => ARRAYREF of tags, any one of which is required to give a result. If none are passed, no filtering is performed.
  72. acls => ARRAYREF of acl tags, any one of which is required to give result. Filter applies after tags. 'admin' ACL being present skips this filter.
  73. page => Offset multiplier for pagination.
  74. limit => Offset for pagination.
  75. like => Search query, as might be passed in the search bar.
  76. author => filter by post author
  77. If it is more efficient to filter within your data storage engine, you probably should override this method.
  78. As implemented, this takes the data as a given and filters in post.
  79. =cut
  80. sub get ( $self, %request ) {
  81. my $posts = $self->read( \%request );
  82. return @$posts if $request{raw};
  83. my @filtered = $self->filter( \%request, @$posts );
  84. @filtered = $self->_fixup(@filtered);
  85. @filtered = $self->paginate( \%request, @filtered );
  86. return @filtered;
  87. }
  88. sub _fixup ( $self, @filtered ) {
  89. my %user2display;
  90. # urlencode spaces in filenames
  91. @filtered = map {
  92. my $subj = $_;
  93. foreach my $param (qw{href preview video_href audio_href local_href wallpaper}) {
  94. next unless exists $subj->{$param};
  95. #XXX I don't remember what this fixes, but it also breaks things. URI::Escape usage instead is indicated.
  96. $subj->{$param} =~ s/ /%20/g;
  97. }
  98. $user2display{ $subj->{user} } //= Trog::Auth::username2display( $subj->{user} );
  99. $subj->{display_name} = $user2display{ $subj->{user} };
  100. #XXX Add dynamic routing data for posts which don't have them (/posts/$id) and (/users/$user)
  101. my $is_user_page = List::Util::any { ( $_ // '' ) eq 'about' } @{ $subj->{tags} };
  102. if ( !exists $subj->{local_href} ) {
  103. $subj->{local_href} = "/posts/$subj->{id}";
  104. #XXX this needs to be correctly populated in the form?
  105. if ($is_user_page) {
  106. my $display_name = $user2display{ $subj->{user} };
  107. die "No display name for user!" unless $display_name;
  108. $subj->{local_href} = "/users/$display_name";
  109. }
  110. }
  111. if ( !exists $subj->{callback} ) {
  112. $subj->{callback} = "Trog::Routes::HTML::posts";
  113. $subj->{callback} = "Trog::Routes::HTML::users" if $is_user_page;
  114. }
  115. $subj->{method} = 'GET' unless exists( $subj->{method} );
  116. $subj->{user_class} = Trog::Auth::username2classname( $subj->{user} );
  117. $subj
  118. } @filtered;
  119. return @filtered;
  120. }
  121. sub _filter_param ( $query, $param, @filtered ) {
  122. @filtered = grep { ( $_->{$param} || '' ) eq $query->{$param} } @filtered;
  123. @filtered = _dedup_versions( $query->{version}, @filtered );
  124. return @filtered;
  125. }
  126. =head2 filter($query, @posts) = @filtered
  127. Apply a get() request's filters to a list of posts: tags, exclude_tags, acls,
  128. visibility, id, title, form, search terms and author.
  129. The ACL check is the load bearing one -- a post is only visible if the caller
  130. holds one of its acls, or the post is public or unlisted. Callers holding the
  131. 'admin' acl skip that filter entirely.
  132. =cut
  133. sub filter ( $self, $query, @filtered ) {
  134. $query->{acls} //= [];
  135. $query->{tags} //= [];
  136. $query->{exclude_tags} //= [];
  137. # If an ID or title or acl is passed, just get that (and all it's prior versions)
  138. foreach my $key (qw{id title aclname}) {
  139. next unless $query->{$key};
  140. return _filter_param( $query, $key, @filtered );
  141. }
  142. @filtered = _dedup_versions( undef, @filtered );
  143. #Filter out posts which are too old
  144. #Coerce older into numeric
  145. if ( $query->{older} ) {
  146. $query->{older} =~ s/[^0-9]//g;
  147. @filtered = grep { $_->{created} < $query->{older} } @filtered;
  148. }
  149. if ( $query->{newer} ) {
  150. $query->{newer} =~ s/[^0-9]//g;
  151. @filtered = grep { $_->{created} > $query->{newer} } @filtered;
  152. }
  153. # Filter posts not matching the passed tag(s), if any
  154. @filtered = grep {
  155. my $tags = $_->{tags};
  156. grep {
  157. my $t = $_;
  158. grep { ( $t // '' ) eq $_ } @{ $query->{tags} }
  159. } @$tags
  160. } @filtered if @{ $query->{tags} };
  161. # Filter posts *matching* the passed exclude_tag(s), if any
  162. @filtered = grep {
  163. my $tags = $_->{tags};
  164. !grep {
  165. my $t = $_;
  166. grep { $t eq $_ } @{ $query->{exclude_tags} }
  167. } @$tags
  168. } @filtered if @{ $query->{exclude_tags} };
  169. # Filter posts without the proper ACLs
  170. @filtered = grep {
  171. my $tags = $_->{tags};
  172. grep {
  173. my $t = $_;
  174. grep { $t eq $_ } @{ $query->{acls} }
  175. } @$tags
  176. } @filtered unless grep { $_ eq 'admin' } @{ $query->{acls} };
  177. @filtered = grep { ( $_->{form} || '' ) eq $query->{form} } @filtered if $query->{form};
  178. @filtered = grep { $_->{title} =~ m/\Q$query->{like}\E/i || $_->{data} =~ m/\Q$query->{like}\E/i } @filtered if $query->{like};
  179. @filtered = grep { $_->{user} eq $query->{author} } @filtered if $query->{author};
  180. return @filtered;
  181. }
  182. =head2 paginate($query, @posts) = @page
  183. The slice of @posts named by the request's page and limit. Both have to be
  184. present to page at all; limit defaults to 25 when computing the offset.
  185. =cut
  186. sub paginate ( $self, $query, @filtered ) {
  187. return @filtered unless $query->{page} && $query->{limit};
  188. my $offset = int( $query->{limit} // 25 );
  189. $offset = @filtered < $offset ? @filtered : $offset;
  190. # splice() warns rather than simply returning nothing when the offset is
  191. # past the end, and a page past the end is what a stale bookmark or a
  192. # walked-off paginator asks for. Empty is the right answer; the warning is
  193. # not part of it.
  194. my $start = ( int( $query->{page} ) - 1 ) * $offset;
  195. return () if $start > scalar(@filtered);
  196. return splice( @filtered, $start, $offset );
  197. }
  198. sub _dedup_versions ( $version = -1, @posts ) {
  199. #ASSUMPTION made here - if we pass version this is direct ID query
  200. if ( defined $version ) {
  201. my $version_max = List::Util::max( map { $_->{version} } @posts );
  202. return map {
  203. $_->{version_max} //= $version_max;
  204. $_
  205. } grep { $_->{version} eq $version } @posts;
  206. }
  207. my @uniqids = List::Util::uniq( map { $_->{id} } @posts );
  208. my %posts_deduped;
  209. for my $id (@uniqids) {
  210. my @ofid = sort { $b->{version} <=> $a->{version} } grep { $_->{id} eq $id } @posts;
  211. my $version_max = List::Util::max( map { $_->{version} } @ofid );
  212. $posts_deduped{$id} = $ofid[0];
  213. $posts_deduped{$id}{version_max} = $version_max;
  214. # Show orig creation date, and original author.
  215. # XXX this doesn't show the mtime correctly for whatever reason, so I'm omitting it from the interface
  216. $posts_deduped{$id}{modified} = $ofid[0]{created};
  217. $posts_deduped{$id}{created} = $ofid[-1]{created};
  218. $posts_deduped{$id}{author} = $ofid[-1]{author};
  219. }
  220. my @deduped = @posts_deduped{@uniqids};
  221. return @deduped;
  222. }
  223. =head2 count() = INT $num
  224. Returns the total number of posts.
  225. Used to determine paginator parameters.
  226. =cut
  227. =head2 add(@posts) = BOOL $failed_or_not
  228. Add the provided posts to the datastore.
  229. If any post already exists with the same id, a new post with a version higher than it will be added.
  230. Passes an array of new posts to add to the data store module's write() function.
  231. These will have their parameters filtered to those described by the post type's
  232. schema (see schema_for()), and then validated against it. If the post doesn't
  233. hold up, this dies with an ARRAYREF of validation error strings -- a ref rather
  234. than a string so that Carp::Always doesn't staple a stack trace onto something
  235. we intend to show the user.
  236. You probably won't want to override this.
  237. =cut
  238. # The shape of a post, as an OpenAPIv3 object schema.
  239. #
  240. # This covers the fields every post has regardless of which form produced it.
  241. # Anything a *particular* post type ingests lives in that type's JSON sidecar
  242. # next to its template in the forms directory -- see _schema_for().
  243. our %post_schema = (
  244. type => 'object',
  245. properties => {
  246. ## Parameters which must be in every single post
  247. title => { type => 'string' },
  248. callback => { type => 'callback' },
  249. tags => { type => 'array', items => { type => 'string' } },
  250. version => { type => 'integer', minimum => 0 },
  251. visibility => { type => 'string', enum => [qw{public unlisted private}] },
  252. aliases => { type => 'array', items => { type => 'string' } },
  253. # title links here
  254. href => { type => 'string' },
  255. # Link to post locally
  256. local_href => { type => 'string' },
  257. # Post body. Multi-page types (presentations, invoices) send an array.
  258. data => {
  259. oneOf => [
  260. { type => 'string' },
  261. { type => 'array', items => { type => 'string' } },
  262. ],
  263. },
  264. # How do I edit this post?
  265. form => { type => 'string' },
  266. # Post is restricted to visibility to these ACLs if not public/unlisted
  267. acls => { type => 'array', items => { type => 'string' } },
  268. id => { type => 'string' },
  269. # Author of the post
  270. user => { type => 'string' },
  271. created => { type => 'integer' },
  272. # Posts are always GET, but it's stored, so it has to be describable.
  273. method => { type => 'string' },
  274. },
  275. );
  276. # Uploads arrive as an HTTP::Body hashref on the way in, and as the href string
  277. # they were turned into on the way back out of the datastore. Sidecars say
  278. # 'upload' and mean this.
  279. our %upload_schema = (
  280. oneOf => [
  281. { type => 'string' },
  282. { type => 'object' },
  283. ],
  284. );
  285. =head2 schema_for($form)
  286. Return the OpenAPIv3 schema describing what the named post type ingests: the
  287. base post schema above, with the type's JSON sidecar merged over the top.
  288. Sidecars live beside their templates (blog.tx has blog.json) and are written
  289. either by hand or by the Post Type Wizard. A post with no form, or a form with
  290. no sidecar, just gets the base schema.
  291. Cached, but keyed on the mtimes of the component dirs rather than memoized
  292. outright: adding or editing a sidecar bumps one of them, so every forked worker
  293. picks the change up on its very next add() with no restart needed.
  294. =cut
  295. # Stat the forms dirs, not their parents -- writing blog.json bumps the mtime
  296. # of forms/, and nothing above it. Both candidates, since either one gaining a
  297. # sidecar changes the answer.
  298. #
  299. # Time::HiRes::stat, because core stat truncates mtime to the second: the post
  300. # type wizard writes a sidecar and something reads it back moments later, and at
  301. # one second of resolution those two are frequently the same generation. The
  302. # reader then answers out of the cache it filled before the write, which is how
  303. # a type saved and used inside the same second validated against the schema it
  304. # had a moment ago. Falls back to whatever stat gives where the filesystem
  305. # carries no sub-second timestamps.
  306. sub _sidecar_generation {
  307. return join( ':', map { ( Time::HiRes::stat("$_/forms") )[9] // 0 } Trog::Themes::template_dirs( 'text/html', 1 ) );
  308. }
  309. # A signature default only covers an absent arg, and plenty of posts have an
  310. # explicitly undef form.
  311. sub _type_of ($form) {
  312. $form = '' if !defined $form || ref $form;
  313. my ($type) = $form =~ m/^([A-Za-z0-9_-]+)\.tx$/;
  314. return $type // '';
  315. }
  316. =head2 type_meta_for($form)
  317. The parts of a post type's sidecar which aren't schema: x-tcms-relations,
  318. x-tcms-post-type and friends.
  319. schema_for() deliberately keeps only properties and required, since everything
  320. else would be noise to the validator -- but the relation tables and the post
  321. type's own metadata live out there and something has to read them.
  322. =cut
  323. sub type_meta_for ( $form = '' ) {
  324. state %cache;
  325. my $generation = _sidecar_generation();
  326. %cache = () unless exists $cache{$generation};
  327. my $type = _type_of($form);
  328. return $cache{$generation}{$type} if exists $cache{$generation}{$type};
  329. my $path = $type ? Trog::Themes::themed_file_in_dir( 'forms', "$type.json", 'text/html', 1 ) : undef;
  330. my $sidecar = $path ? _read_sidecar($path) : undef;
  331. my %meta;
  332. if ($sidecar) {
  333. %meta = map { $_ => $sidecar->{$_} } grep { $_ ne 'properties' && $_ ne 'required' && $_ ne 'type' } keys(%$sidecar);
  334. }
  335. $cache{$generation}{$type} = \%meta;
  336. return $cache{$generation}{$type};
  337. }
  338. =head2 private_fields_for($form)
  339. The fields of a post type which only an editor may see, as declared by
  340. x-tcms-private in the sidecar.
  341. A field is public unless it says otherwise. The point of declaring it here
  342. rather than guarding it in the template is that the value can then be dropped
  343. before rendering, so no amount of getting a template wrong can leak it.
  344. =cut
  345. sub private_fields_for ( $form = '' ) {
  346. my $properties = schema_for($form)->{properties} // {};
  347. return [ grep { $properties->{$_}{'x-tcms-private'} } keys(%$properties) ];
  348. }
  349. =head2 indexed_fields_for($form)
  350. The custom fields of a post type which the Post Type Wizard was told to index,
  351. as declared by x-tcms-indexed in the sidecar.
  352. A field is unindexed unless it says otherwise. What indexing a field actually
  353. means is up to the data model -- see index_fields(), which most of them ignore.
  354. =cut
  355. sub indexed_fields_for ( $form = '' ) {
  356. my $properties = schema_for($form)->{properties} // {};
  357. # Sorted, unlike private_fields_for(), which is only ever asked whether a
  358. # given field is in it. This list is collected across every post type and
  359. # handed to a data model to act on, and an answer that comes back in a
  360. # different order each run makes a reconciliation impossible to reason about.
  361. return [ sort grep { $properties->{$_}{'x-tcms-indexed'} } keys(%$properties) ];
  362. }
  363. =head2 index_fields(@fields)
  364. Tell the data model which custom fields ought to be queryable, and let it do
  365. whatever that means for it.
  366. The default is to do nothing at all, and that is a perfectly good answer: a
  367. model with no notion of an index has nothing to build, and the wizard should not
  368. have to know which model it is talking to in order to offer the option.
  369. Called with the full set every time rather than with a delta, so a model that
  370. does act on it can bring itself into line in one pass -- including letting go of
  371. what is no longer asked for.
  372. =cut
  373. sub index_fields ( $self, @fields ) { return 0 }
  374. =head2 relations_for($form)
  375. The x-tcms-relations table for a post type, as a hashref keyed on the template
  376. variable the resolved posts land in. Empty when the type declares none.
  377. Each entry is { form => 'other.tx', from => 'field_name' } -- 'from' naming the
  378. field holding a UUID to resolve, or absent to mean every post of that type.
  379. =cut
  380. sub relations_for ( $form = '' ) {
  381. my $relations = type_meta_for($form)->{'x-tcms-relations'};
  382. return {} unless Ref::Util::is_hashref($relations);
  383. return $relations;
  384. }
  385. sub schema_for ( $form = '' ) {
  386. state %cache;
  387. my $generation = _sidecar_generation();
  388. # Only ever keep the current generation around.
  389. %cache = () unless exists $cache{$generation};
  390. my $type = _type_of($form);
  391. return $cache{$generation}{$type} if exists $cache{$generation}{$type};
  392. my %merged = ( %post_schema, properties => { %{ $post_schema{properties} } } );
  393. # Themed like the templates themselves: a theme that overrides blog.tx can
  394. # ship its own blog.json alongside it, and one that doesn't still gets the
  395. # stock schema rather than nothing at all.
  396. my $path = $type ? Trog::Themes::themed_file_in_dir( 'forms', "$type.json", 'text/html', 1 ) : undef;
  397. my $sidecar = $path ? _read_sidecar($path) : undef;
  398. if ($sidecar) {
  399. # The base schema is merged *last*, so a sidecar can add fields but can
  400. # never redefine one of ours. That matters: a sidecar retyping
  401. # 'callback' as a plain string would defeat the check that the sub it
  402. # names actually exists, which is a privilege problem rather than a
  403. # cosmetic one.
  404. %{ $merged{properties} } = ( %{ $sidecar->{properties} // {} }, %{ $merged{properties} } );
  405. # A sidecar may insist on its own fields, but it can't relax anything
  406. # the base schema already demands.
  407. my @required = List::Util::uniq( @{ $post_schema{required} // [] }, @{ $sidecar->{required} // [] } );
  408. # An empty required list isn't legal OpenAPI, so don't emit one.
  409. $merged{required} = \@required if @required;
  410. }
  411. $cache{$generation}{$type} = \%merged;
  412. return $cache{$generation}{$type};
  413. }
  414. sub _read_sidecar ($path) {
  415. # -e, not -f: the question is whether a sidecar exists at all, and most
  416. # post types have none. Letting the read below fail instead would WARN
  417. # about every type that simply does not have one.
  418. return undef unless -e $path;
  419. local $@;
  420. my $spec = eval { JSON::MaybeXS::decode_json( File::Slurper::read_text($path) ) };
  421. if ( !$spec ) {
  422. WARN("Could not parse post type sidecar '$path': $@");
  423. return undef;
  424. }
  425. return undef unless Ref::Util::is_hashref($spec);
  426. _expand_pseudo_types($spec);
  427. return $spec;
  428. }
  429. # A relation is stored as the referenced post's UUID, and resolved into the
  430. # post itself at render time -- see the x-tcms-relations table a sidecar
  431. # declares alongside it, and Trog::Routes::HTML::_enrich_post. The pseudo-type
  432. # exists so a sidecar can say what a field *means* rather than just that it
  433. # happens to be a string.
  434. our %relation_schema = ( type => 'string' );
  435. # Sugar: a sidecar says {"type":"upload"} rather than spelling out the
  436. # string-or-hashref dance every upload field would otherwise need. Uploads are
  437. # a hashref on the way in from the browser and the href string they became on
  438. # the way back out of the datastore.
  439. sub _expand_pseudo_types ($node) {
  440. return unless Ref::Util::is_hashref($node);
  441. my %pseudo = (
  442. upload => \%upload_schema,
  443. relation => \%relation_schema,
  444. );
  445. my $type = $node->{type} // '';
  446. if ( $pseudo{$type} ) {
  447. delete $node->{type};
  448. %$node = ( %$node, %{ $pseudo{$type} } );
  449. return;
  450. }
  451. _expand_pseudo_types($_) foreach values( %{ $node->{properties} // {} } );
  452. _expand_pseudo_types( $node->{items} ) if $node->{items};
  453. foreach my $key (qw{oneOf anyOf allOf}) {
  454. next unless Ref::Util::is_arrayref( $node->{$key} );
  455. _expand_pseudo_types($_) foreach @{ $node->{$key} };
  456. }
  457. return;
  458. }
  459. =head2 validate($post)
  460. Filter a post down to the fields its type actually describes, then run what's
  461. left through the schema.
  462. Returns the list of validation errors, which is empty when the post is good.
  463. Note that filtering happens first and silently: the query hash handed to us by
  464. the router is full of things which aren't post fields at all, and never was
  465. meant to round-trip.
  466. =cut
  467. sub _validator {
  468. state $validator;
  469. $validator //= JSON::Validator::Schema::Troglodyne->new();
  470. return $validator;
  471. }
  472. sub validate ($post) {
  473. my $validator = _validator();
  474. my $schema = schema_for( $post->{form} );
  475. foreach my $key ( keys(%$post) ) {
  476. # Drop everything the schema doesn't describe.
  477. my $property = $schema->{properties}{$key};
  478. if ( !$property ) {
  479. delete $post->{$key};
  480. next;
  481. }
  482. # An untouched form input submits the empty string, which is HTML for
  483. # "I wasn't filled in" rather than a number, a boolean or a file. We
  484. # leave it alone for actual string fields, which is what got stored
  485. # before any of this was typed.
  486. delete $post->{$key}
  487. if defined $post->{$key}
  488. && !ref $post->{$key}
  489. && $post->{$key} eq ''
  490. && ( $property->{type} // '' ) ne 'string';
  491. }
  492. # OpenAPIv3 coerces as it goes, so "4" lands in the datastore as 4 and
  493. # checkbox values land as real booleans.
  494. return $validator->validate( $post, $schema );
  495. }
  496. =head2 validate_built($post)
  497. Check the post that is actually about to be written.
  498. validate() runs on what was submitted. _process() then builds the shape that
  499. gets stored -- it turns a visibility into a tag, folds the acls in, resolves
  500. uploads into hrefs -- and until now nothing looked at the result. That is how
  501. every post saved without a visibility came to carry a null in its tags: the
  502. schema describes tags as an array of strings and would have rejected it on the
  503. spot, but it was never asked.
  504. Checks rather than filters, unlike validate(). _process() adds fields the base
  505. schema has never heard of -- content_type, is_video, attachments -- and dropping
  506. what it does not recognise would throw away the work it just did. So this looks
  507. only at the fields the schema actually describes, on a copy, and changes nothing.
  508. Returns the list of validation errors, empty when the post is fit to store.
  509. =cut
  510. sub validate_built ($post) {
  511. my $schema = schema_for( $post->{form} );
  512. my %described = map { $_ => $post->{$_} } grep { exists $schema->{properties}{$_} } keys(%$post);
  513. return _validator()->validate( \%described, $schema );
  514. }
  515. sub add ( $self, @posts ) {
  516. my @to_write;
  517. foreach my $post (@posts) {
  518. # Filter to what this post type actually describes, then validate it.
  519. my @errors = validate($post);
  520. # An arrayref rather than a string on purpose. These errors get shown
  521. # to whoever submitted the post, and Carp::Always decorates a string
  522. # die with a stack trace they have no use for.
  523. die [ map { "$_" } @errors ] if @errors;
  524. $post->{id} //= Trog::Utils::uuid();
  525. $post->{aliases} //= [];
  526. $post->{aliases} = [ $post->{aliases} ] unless ref $post->{aliases} eq 'ARRAY';
  527. if ( $post->{aclname} ) {
  528. # Then this is a series
  529. $post->{local_href} //= "/$post->{aclname}";
  530. push( @{ $post->{aliases} }, "/posts/$post->{id}", "/series/$post->{id}" );
  531. }
  532. # Every post needs one: _process pushes it into the tags, and an
  533. # undef there is a tag no query will ever match, which makes the post
  534. # invisible to everyone but an admin. A post type built without a
  535. # visibility selector would otherwise produce exactly that. Private
  536. # rather than public, because guessing wrong in the other direction
  537. # publishes something nobody asked to publish.
  538. $post->{visibility} //= 'private';
  539. $post->{callback} //= 'Trog::Routes::HTML::posts';
  540. # If this is a user creation post, add in the /user/ route
  541. if ( $post->{callback} eq 'Trog::Routes::HTML::users' ) {
  542. $post->{local_href} //= "/users/$post->{display_name}";
  543. $post->{title} //= $post->{display_name};
  544. }
  545. $post->{local_href} //= "/posts/$post->{id}";
  546. $post->{method} //= 'GET';
  547. $post->{created} = time();
  548. my @existing_posts = $self->get( id => $post->{id} );
  549. if (@existing_posts) {
  550. my $existing_post = $existing_posts[0];
  551. $post->{version} = $existing_post->{version};
  552. $post->{version}++;
  553. }
  554. $post->{version} //= 0;
  555. #XXX if local_href has /secure paths in it, fix this. We don't want to save that.
  556. if ( index( $post->{local_href}, '/secure/' ) == 0 ) {
  557. $post->{local_href} =~ s|/secure||gmx;
  558. }
  559. $post = _process($post);
  560. # And check what _process() built, not just what arrived. A post that
  561. # fails here is one this code has made wrong on its way to disk, so it
  562. # is a bug rather than bad input -- but the answer is still to refuse to
  563. # write it, because the alternative is what we did before, which was to
  564. # write it and find out years later.
  565. my @built = validate_built($post);
  566. if (@built) {
  567. WARN( "Refusing to store a post this built wrong: " . join( ', ', map { "$_" } @built ) );
  568. die [ map { "$_" } @built ];
  569. }
  570. push @to_write, $post;
  571. }
  572. $self->write( \@to_write );
  573. return 0;
  574. }
  575. #XXX this level of post-processing seems gross, but may be unavoidable
  576. # Not actually a subprocess, kek
  577. sub _process ($post) {
  578. # Here as well as in add(), because this is the sub that turns a visibility
  579. # into a tag: without one it pushed an undef into tags, which is a tag no
  580. # query ever matches, so the post went invisible to everyone but an admin.
  581. # Nothing complained, and the bunk tag was written to disk and stayed there.
  582. $post->{visibility} //= 'private';
  583. # If the post is private, make sure it's associated assets are too.
  584. my $is_private_post = $post->{visibility} eq 'private';
  585. $post->{href} = _handle_upload( $post->{file}, $post->{id}, $is_private_post ) if $post->{file};
  586. $post->{preview} = _handle_upload( $post->{preview_file}, $post->{id}, $is_private_post ) if $post->{preview_file};
  587. $post->{wallpaper} = _handle_upload( $post->{wallpaper_file}, $post->{id}, $is_private_post ) if $post->{wallpaper_file};
  588. @{ $post->{attachments} } = map { _handle_upload( $_, $post->{id}, $is_private_post ) } @{ $post->{attachments} } if $post->{attachments};
  589. $post->{preview} = $post->{href} if $post->{app} && $post->{app} eq 'image';
  590. delete $post->{app};
  591. delete $post->{file};
  592. delete $post->{preview_file};
  593. delete $post->{wallpaper_file};
  594. delete $post->{scheme};
  595. delete $post->{route};
  596. delete $post->{domain};
  597. # Handle acls/tags
  598. $post->{tags} //= [];
  599. $post->{acls} //= [];
  600. @{ $post->{tags} } = grep {
  601. my $subj = $_;
  602. !grep { $_ eq $subj } qw{public private unlisted}
  603. } @{ $post->{tags} };
  604. push( @{ $post->{tags} }, grep { defined } @{ $post->{acls} } ) if $is_private_post;
  605. delete $post->{acls};
  606. push( @{ $post->{tags} }, $post->{visibility} );
  607. # Add the 'series' tag if we are in a series, restrict to relevant acl
  608. if ( $post->{series} ) {
  609. push( @{ $post->{tags} }, 'series' );
  610. push( @{ $post->{tags} }, $post->{series} );
  611. }
  612. #Filter adding the same acl twice, and anything that isn't a tag at all --
  613. # an undef here is what every query below compares against, and it warns
  614. # its way through the lot before matching nothing.
  615. @{ $post->{tags} } = List::Util::uniq( grep { defined && length } @{ $post->{tags} } );
  616. @{ $post->{aliases} } = List::Util::uniq( grep { defined && length } @{ $post->{aliases} } );
  617. # Handle multimedia content types
  618. $post->{content_type} = Trog::Utils::mime_type("www/$post->{href}") if $post->{href};
  619. $post->{video_content_type} = Trog::Utils::mime_type("www/$post->{video_href}") if $post->{video_href};
  620. $post->{audio_content_type} = Trog::Utils::mime_type("www/$post->{audio_href}") if $post->{audio_href};
  621. $post->{content_type} ||= 'text/html';
  622. $post->{is_video} = 1 if $post->{content_type} =~ m/^video\//;
  623. $post->{is_audio} = 1 if $post->{content_type} =~ m/^audio\//;
  624. $post->{is_image} = 1 if $post->{content_type} =~ m/^image\//;
  625. $post->{is_profile} = 1 if grep { $_ eq 'about' } @{ $post->{tags} };
  626. return $post;
  627. }
  628. # Browsers try and save time in the event that the same file is sent twice, so handle that.
  629. my %seen_files;
  630. sub _handle_upload ( $file, $uuid, $private = 0 ) {
  631. my $fname;
  632. if ( ref $file ne 'HASH' ) {
  633. use Data::Dumper;
  634. $file =~ s/\\/\//g;
  635. $fname = basename($file);
  636. FATAL("Did not expect bogus file before its real counterpart!") unless $seen_files{$fname};
  637. return $seen_files{$fname};
  638. }
  639. my $f = $file->{tempname};
  640. $fname = basename( $file->{filename} );
  641. my $newname = "$uuid.$file->{filename}";
  642. $newname = "private/$newname" if $private;
  643. File::Copy::move( $f, "www/assets/$newname" );
  644. # Regrettably, we have no control over the perms of the temp file that starman creates for uploads.
  645. chmod( 0755, "www/assets/$newname" );
  646. $seen_files{$fname} = "/assets/$newname";
  647. return $seen_files{$fname};
  648. }
  649. =head2 delete(@posts)
  650. Delete the following posts.
  651. Will remove all versions of said post.
  652. You should override this, it is a stub here.
  653. =cut
  654. sub delete ($self) { die 'stub' }
  655. =head2 routes() = HASH
  656. Returns the routes to each post.
  657. You should override this for performance reasons, as it's just a wrapper around get() by defualt.
  658. =cut
  659. sub routes ($self) {
  660. my %routes = map { $_->{local_href} => { method => $_->{method}, callback => \&{ $_->{callback} } } } ( $self->get( limit => 0, acls => ['admin'] ) );
  661. return %routes;
  662. }
  663. =head2 aliases() = HASH
  664. Returns the aliases for each post, indexed by aliases.
  665. You should override this for performance reasons, as it's just a wrapper around get() by defualt.
  666. =cut
  667. sub aliases ($self) {
  668. my @posts = $self->get( limit => 0, acls => ['admin'] );
  669. my %aliases;
  670. foreach my $post (@posts) {
  671. @aliases{ @{ $post->{aliases} } } = $post->{local_href};
  672. }
  673. return %aliases;
  674. }
  675. 1;