DataModule.pm 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. package Trog::DataModule;
  2. use 5.040;
  3. use re '/aasx';
  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. # Visibility and acls are both stored as tags, so a caller sees a post when it
  127. # holds one of them. admin sees everything.
  128. sub _filter_acls ( $query, @filtered ) {
  129. return @filtered if grep { $_ eq 'admin' } @{ $query->{acls} };
  130. return grep {
  131. my $tags = $_->{tags};
  132. grep {
  133. my $t = $_;
  134. grep { $t eq $_ } @{ $query->{acls} }
  135. } @$tags
  136. } @filtered;
  137. }
  138. =head2 filter($query, @posts) = @filtered
  139. Apply a get() request's filters to a list of posts: tags, exclude_tags, acls,
  140. visibility, id, title, form, search terms and author.
  141. The ACL check is the load bearing one -- a post is only visible if the caller
  142. holds one of its acls, or the post is public or unlisted. Callers holding the
  143. 'admin' acl skip that filter entirely.
  144. =cut
  145. sub filter ( $self, $query, @filtered ) {
  146. $query->{acls} //= [];
  147. $query->{tags} //= [];
  148. $query->{exclude_tags} //= [];
  149. # If an ID or title or acl is passed, just get that (and all it's prior versions),
  150. # if the caller may see it.
  151. foreach my $key (qw{id title aclname}) {
  152. next unless $query->{$key};
  153. return _filter_acls( $query, _filter_param( $query, $key, @filtered ) );
  154. }
  155. @filtered = _dedup_versions( undef, @filtered );
  156. #Filter out posts which are too old
  157. #Coerce older into numeric
  158. if ( $query->{older} ) {
  159. $query->{older} =~ s/[^0-9]//g;
  160. @filtered = grep { $_->{created} < $query->{older} } @filtered;
  161. }
  162. if ( $query->{newer} ) {
  163. $query->{newer} =~ s/[^0-9]//g;
  164. @filtered = grep { $_->{created} > $query->{newer} } @filtered;
  165. }
  166. # Filter posts not matching the passed tag(s), if any
  167. @filtered = grep {
  168. my $tags = $_->{tags};
  169. grep {
  170. my $t = $_;
  171. grep { ( $t // '' ) eq $_ } @{ $query->{tags} }
  172. } @$tags
  173. } @filtered if @{ $query->{tags} };
  174. # Filter posts *matching* the passed exclude_tag(s), if any
  175. @filtered = grep {
  176. my $tags = $_->{tags};
  177. !grep {
  178. my $t = $_;
  179. grep { $t eq $_ } @{ $query->{exclude_tags} }
  180. } @$tags
  181. } @filtered if @{ $query->{exclude_tags} };
  182. @filtered = _filter_acls( $query, @filtered );
  183. @filtered = grep { ( $_->{form} || '' ) eq $query->{form} } @filtered if $query->{form};
  184. @filtered = grep { $_->{title} =~ m/\Q$query->{like}\E/i || $_->{data} =~ m/\Q$query->{like}\E/i } @filtered if $query->{like};
  185. @filtered = grep { $_->{user} eq $query->{author} } @filtered if $query->{author};
  186. return @filtered;
  187. }
  188. =head2 paginate($query, @posts) = @page
  189. The slice of @posts named by the request's page and limit. Both have to be
  190. present to page at all; limit defaults to 25 when computing the offset.
  191. =cut
  192. sub paginate ( $self, $query, @filtered ) {
  193. return @filtered unless $query->{page} && $query->{limit};
  194. my $offset = int( $query->{limit} // 25 );
  195. $offset = @filtered < $offset ? @filtered : $offset;
  196. # splice() warns rather than simply returning nothing when the offset is
  197. # past the end, and a page past the end is what a stale bookmark or a
  198. # walked-off paginator asks for. Empty is the right answer; the warning is
  199. # not part of it.
  200. my $start = ( int( $query->{page} ) - 1 ) * $offset;
  201. return () if $start > scalar(@filtered);
  202. return splice( @filtered, $start, $offset );
  203. }
  204. sub _dedup_versions ( $version = -1, @posts ) {
  205. #ASSUMPTION made here - if we pass version this is direct ID query
  206. if ( defined $version ) {
  207. my $version_max = List::Util::max( map { $_->{version} } @posts );
  208. return map {
  209. $_->{version_max} //= $version_max;
  210. $_
  211. } grep { $_->{version} eq $version } @posts;
  212. }
  213. my @uniqids = List::Util::uniq( map { $_->{id} } @posts );
  214. my %posts_deduped;
  215. for my $id (@uniqids) {
  216. my @ofid = sort { $b->{version} <=> $a->{version} } grep { $_->{id} eq $id } @posts;
  217. my $version_max = List::Util::max( map { $_->{version} } @ofid );
  218. $posts_deduped{$id} = $ofid[0];
  219. $posts_deduped{$id}{version_max} = $version_max;
  220. # Show orig creation date, and original author.
  221. # A modified already present is from an earlier pass, which FlatFile makes
  222. # in read() before get() filters again; validate() never lets one be stored.
  223. $posts_deduped{$id}{modified} = $ofid[0]{modified} // $ofid[0]{created};
  224. $posts_deduped{$id}{created} = $ofid[-1]{created};
  225. $posts_deduped{$id}{author} = $ofid[-1]{author};
  226. }
  227. my @deduped = @posts_deduped{@uniqids};
  228. return @deduped;
  229. }
  230. =head2 count() = INT $num
  231. Returns the total number of posts.
  232. Used to determine paginator parameters.
  233. =cut
  234. =head2 add(@posts) = BOOL $failed_or_not
  235. Add the provided posts to the datastore.
  236. If any post already exists with the same id, a new post with a version higher than it will be added.
  237. Passes an array of new posts to add to the data store module's write() function.
  238. These will have their parameters filtered to those described by the post type's
  239. schema (see schema_for()), and then validated against it. If the post doesn't
  240. hold up, this dies with an ARRAYREF of validation error strings -- a ref rather
  241. than a string so that Carp::Always doesn't staple a stack trace onto something
  242. we intend to show the user.
  243. You probably won't want to override this.
  244. =cut
  245. # The shape of a post, as an OpenAPIv3 object schema.
  246. #
  247. # This covers the fields every post has regardless of which form produced it.
  248. # Anything a *particular* post type ingests lives in that type's JSON sidecar
  249. # next to its template in the forms directory -- see _schema_for().
  250. our %post_schema = (
  251. type => 'object',
  252. properties => {
  253. ## Parameters which must be in every single post
  254. title => { type => 'string' },
  255. callback => { type => 'callback' },
  256. tags => { type => 'array', items => { type => 'string' } },
  257. version => { type => 'integer', minimum => 0 },
  258. visibility => { type => 'string', enum => [qw{public unlisted private}] },
  259. aliases => { type => 'array', items => { type => 'string' } },
  260. # title links here
  261. href => { type => 'string' },
  262. # Link to post locally
  263. local_href => { type => 'string' },
  264. # Post body. Multi-page types (presentations, invoices) send an array.
  265. data => {
  266. oneOf => [
  267. { type => 'string' },
  268. { type => 'array', items => { type => 'string' } },
  269. ],
  270. },
  271. # How do I edit this post?
  272. form => { type => 'string' },
  273. # Post is restricted to visibility to these ACLs if not public/unlisted
  274. acls => { type => 'array', items => { type => 'string' } },
  275. id => { type => 'string' },
  276. # Author of the post
  277. user => { type => 'string' },
  278. created => { type => 'integer' },
  279. # Posts are always GET, but it's stored, so it has to be describable.
  280. method => { type => 'string' },
  281. },
  282. );
  283. # Uploads arrive as an HTTP::Body hashref on the way in, and as the href string
  284. # they were turned into on the way back out of the datastore. Sidecars say
  285. # 'upload' and mean this.
  286. our %upload_schema = (
  287. oneOf => [
  288. { type => 'string' },
  289. { type => 'object' },
  290. ],
  291. );
  292. =head2 schema_for($form)
  293. Return the OpenAPIv3 schema describing what the named post type ingests: the
  294. base post schema above, with the type's JSON sidecar merged over the top.
  295. Sidecars live beside their templates (blog.tx has blog.json) and are written
  296. either by hand or by the Post Type Wizard. A post with no form, or a form with
  297. no sidecar, just gets the base schema.
  298. The canned editor blocks a type includes are merged in too, since a form which
  299. splices in preview.tx collects a preview image no matter what its own sidecar
  300. says -- see includes_for() and include_schema_for(). A type's own declaration
  301. of a field beats the block's, and the base schema beats both.
  302. Cached, but keyed on the mtimes of the component dirs rather than memoized
  303. outright: adding or editing a sidecar bumps one of them, so every forked worker
  304. picks the change up on its very next add() with no restart needed.
  305. =cut
  306. # Stat the forms dirs, and the components dirs holding them: writing blog.json
  307. # bumps the mtime of forms/ and nothing above it, while the sidecar beside a
  308. # canned include (preview.json) lives in components/ itself. Both candidates of
  309. # each, since either one gaining a sidecar changes the answer.
  310. #
  311. # Time::HiRes::stat, because core stat truncates mtime to the second: the post
  312. # type wizard writes a sidecar and something reads it back moments later, and at
  313. # one second of resolution those two are frequently the same generation. The
  314. # reader then answers out of the cache it filled before the write, which is how
  315. # a type saved and used inside the same second validated against the schema it
  316. # had a moment ago. Falls back to whatever stat gives where the filesystem
  317. # carries no sub-second timestamps.
  318. sub _sidecar_generation {
  319. return join( ':', map { ( ( Time::HiRes::stat("$_/forms") )[9] // 0, ( Time::HiRes::stat($_) )[9] // 0 ) } Trog::Themes::template_dirs( 'text/html', 1 ) );
  320. }
  321. # A signature default only covers an absent arg, and plenty of posts have an
  322. # explicitly undef form.
  323. sub _type_of ($form) {
  324. $form = '' if !defined $form || ref $form;
  325. my ($type) = $form =~ m/^([A-Za-z0-9_-]+)\.tx$/;
  326. return $type // '';
  327. }
  328. =head2 type_meta_for($form)
  329. The parts of a post type's sidecar which aren't schema: x-tcms-relations,
  330. x-tcms-post-type and friends.
  331. schema_for() deliberately keeps only properties and required, since everything
  332. else would be noise to the validator -- but the relation tables and the post
  333. type's own metadata live out there and something has to read them.
  334. =cut
  335. sub type_meta_for ( $form = '' ) {
  336. state %cache;
  337. my $generation = _sidecar_generation();
  338. %cache = () unless exists $cache{$generation};
  339. my $type = _type_of($form);
  340. return $cache{$generation}{$type} if exists $cache{$generation}{$type};
  341. my $path = $type ? Trog::Themes::themed_file_in_dir( 'forms', "$type.json", 'text/html', 1 ) : undef;
  342. my $sidecar = $path ? _read_sidecar($path) : undef;
  343. my %meta;
  344. if ($sidecar) {
  345. %meta = map { $_ => $sidecar->{$_} } grep { $_ ne 'properties' && $_ ne 'required' && $_ ne 'type' } keys(%$sidecar);
  346. }
  347. $cache{$generation}{$type} = \%meta;
  348. return $cache{$generation}{$type};
  349. }
  350. =head2 include_schema_for($include)
  351. The schema fragment describing what a canned include collects, read from the
  352. JSON sidecar beside it: preview.tx has preview.json, exactly as blog.tx has
  353. blog.json.
  354. A canned include is a block of editor markup which several post types splice in,
  355. and the fields it collects belong to every type which does. Nothing said so
  356. until this existed, which cost twice over: a hand-written type had to repeat the
  357. declaration in its own sidecar, where the Post Type Wizard could no longer tell
  358. it apart from a field somebody had typed in; and a generated type had no
  359. declaration at all, so validate() dropped the preview image its own editor had
  360. just collected.
  361. Returns an empty hashref for an include which has no sidecar -- which is most of
  362. them, since edit_head.tx and friends collect nothing.
  363. =cut
  364. sub include_schema_for ( $include = '' ) {
  365. state %cache;
  366. my $generation = _sidecar_generation();
  367. %cache = () unless exists $cache{$generation};
  368. # Same shape as a post type, so the same check: a name and nothing else,
  369. # since it is about to be turned into a path.
  370. my $name = _type_of($include);
  371. return {} unless $name;
  372. return $cache{$generation}{$name} if exists $cache{$generation}{$name};
  373. my $path = Trog::Themes::themed_component("$name.json");
  374. my $sidecar = $path ? _read_sidecar($path) : undef;
  375. $cache{$generation}{$name} = $sidecar // {};
  376. return $cache{$generation}{$name};
  377. }
  378. =head2 includes_for($form)
  379. The canned includes a post type splices into its editor, as an arrayref of
  380. template names in the order they appear.
  381. Read out of the template rather than out of the sidecar, because the template is
  382. what actually renders: a hand-written type never recorded the list anywhere, and
  383. a generated one can still be edited by hand afterwards. The list the wizard
  384. recorded is the fallback for a type whose template cannot be read at all.
  385. Everything the template includes is returned, not just the blocks the wizard
  386. offers -- it is include_schema_for() which decides whether a given one collects
  387. anything.
  388. =cut
  389. sub includes_for ( $form = '' ) {
  390. state %cache;
  391. my $generation = _sidecar_generation();
  392. %cache = () unless exists $cache{$generation};
  393. my $type = _type_of($form);
  394. return [] unless $type;
  395. return $cache{$generation}{$type} if exists $cache{$generation}{$type};
  396. $cache{$generation}{$type} = _includes_of($type);
  397. return $cache{$generation}{$type};
  398. }
  399. sub _includes_of ($type) {
  400. my $path = Trog::Themes::themed_file_in_dir( 'forms', "$type.tx", 'text/html', 1 );
  401. my $template = $path ? eval { File::Slurper::read_text($path) } : undef;
  402. if ( !defined $template ) {
  403. my $meta = type_meta_for("$type.tx")->{'x-tcms-post-type'};
  404. my $recorded = Ref::Util::is_hashref($meta) ? $meta->{includes} : undef;
  405. return [] unless Ref::Util::is_arrayref($recorded);
  406. return [ grep { defined && !ref } @$recorded ];
  407. }
  408. # Kolon's line syntax, which is how every include in the tree is written --
  409. # including the ones the wizard generates. Deduped, since a template is
  410. # free to splice the same block in twice.
  411. my %seen;
  412. return [ grep { !$seen{$_}++ } $template =~ m/^\s*:\s*include\s+"([A-Za-z0-9_-]+\.tx)"/gm ];
  413. }
  414. =head2 private_fields_for($form)
  415. The fields of a post type which only an editor may see, as declared by
  416. x-tcms-private in the sidecar.
  417. A field is public unless it says otherwise. The point of declaring it here
  418. rather than guarding it in the template is that the value can then be dropped
  419. before rendering, so no amount of getting a template wrong can leak it.
  420. =cut
  421. sub private_fields_for ( $form = '' ) {
  422. my $properties = schema_for($form)->{properties} // {};
  423. return [ grep { $properties->{$_}{'x-tcms-private'} } keys(%$properties) ];
  424. }
  425. =head2 indexed_fields_for($form)
  426. The custom fields of a post type which the Post Type Wizard was told to index,
  427. as declared by x-tcms-indexed in the sidecar.
  428. A field is unindexed unless it says otherwise. What indexing a field actually
  429. means is up to the data model -- see index_fields(), which most of them ignore.
  430. =cut
  431. sub indexed_fields_for ( $form = '' ) {
  432. my $properties = schema_for($form)->{properties} // {};
  433. # Sorted, unlike private_fields_for(), which is only ever asked whether a
  434. # given field is in it. This list is collected across every post type and
  435. # handed to a data model to act on, and an answer that comes back in a
  436. # different order each run makes a reconciliation impossible to reason about.
  437. return [ sort grep { $properties->{$_}{'x-tcms-indexed'} } keys(%$properties) ];
  438. }
  439. =head2 index_fields(@fields)
  440. Tell the data model which custom fields ought to be queryable, and let it do
  441. whatever that means for it.
  442. The default is to do nothing at all, and that is a perfectly good answer: a
  443. model with no notion of an index has nothing to build, and the wizard should not
  444. have to know which model it is talking to in order to offer the option.
  445. Called with the full set every time rather than with a delta, so a model that
  446. does act on it can bring itself into line in one pass -- including letting go of
  447. what is no longer asked for.
  448. =cut
  449. sub index_fields ( $self, @fields ) { return 0 }
  450. =head2 relations_for($form)
  451. The x-tcms-relations table for a post type, as a hashref keyed on the template
  452. variable the resolved posts land in. Empty when the type declares none.
  453. Each entry is { form => 'other.tx', from => 'field_name' } -- 'from' naming the
  454. field holding a UUID to resolve, or absent to mean every post of that type.
  455. =cut
  456. sub relations_for ( $form = '' ) {
  457. my $relations = type_meta_for($form)->{'x-tcms-relations'};
  458. return {} unless Ref::Util::is_hashref($relations);
  459. return $relations;
  460. }
  461. sub schema_for ( $form = '' ) {
  462. state %cache;
  463. my $generation = _sidecar_generation();
  464. # Only ever keep the current generation around.
  465. %cache = () unless exists $cache{$generation};
  466. my $type = _type_of($form);
  467. return $cache{$generation}{$type} if exists $cache{$generation}{$type};
  468. my %merged = ( %post_schema, properties => { %{ $post_schema{properties} } } );
  469. # Themed like the templates themselves: a theme that overrides blog.tx can
  470. # ship its own blog.json alongside it, and one that doesn't still gets the
  471. # stock schema rather than nothing at all.
  472. my $path = $type ? Trog::Themes::themed_file_in_dir( 'forms', "$type.json", 'text/html', 1 ) : undef;
  473. my $sidecar = $path ? _read_sidecar($path) : undef;
  474. if ($sidecar) {
  475. # The base schema is merged *last*, so a sidecar can add fields but can
  476. # never redefine one of ours. That matters: a sidecar retyping
  477. # 'callback' as a plain string would defeat the check that the sub it
  478. # names actually exists, which is a privilege problem rather than a
  479. # cosmetic one.
  480. %{ $merged{properties} } = ( %{ $sidecar->{properties} // {} }, %{ $merged{properties} } );
  481. # A sidecar may insist on its own fields, but it can't relax anything
  482. # the base schema already demands.
  483. my @required = List::Util::uniq( @{ $post_schema{required} // [] }, @{ $sidecar->{required} // [] } );
  484. # An empty required list isn't legal OpenAPI, so don't emit one.
  485. $merged{required} = \@required if @required;
  486. }
  487. # And what the canned blocks this type's editor splices in collect. A form
  488. # which includes preview.tx collects a preview image whether or not anybody
  489. # wrote that down in its sidecar, and validate() drops every field the schema
  490. # does not describe -- so until this was merged in, a post type generated by
  491. # the wizard threw its own preview upload away on the way to the datastore.
  492. #
  493. # Merged under both of the above: only the properties, since it is the type
  494. # rather than a block it borrows which gets to say what it insists on, and
  495. # last of the three in precedence, so a type declaring one of these itself
  496. # still wins.
  497. foreach my $include ( @{ includes_for($form) } ) {
  498. my $properties = include_schema_for($include)->{properties};
  499. next unless Ref::Util::is_hashref($properties);
  500. %{ $merged{properties} } = ( %$properties, %{ $merged{properties} } );
  501. }
  502. $cache{$generation}{$type} = \%merged;
  503. return $cache{$generation}{$type};
  504. }
  505. sub _read_sidecar ($path) {
  506. # -e, not -f: the question is whether a sidecar exists at all, and most
  507. # post types have none. Letting the read below fail instead would WARN
  508. # about every type that simply does not have one.
  509. return undef unless -e $path;
  510. local $@;
  511. my $spec = eval { JSON::MaybeXS::decode_json( File::Slurper::read_text($path) ) };
  512. if ( !$spec ) {
  513. WARN("Could not parse post type sidecar '$path': $@");
  514. return undef;
  515. }
  516. return undef unless Ref::Util::is_hashref($spec);
  517. _expand_pseudo_types($spec);
  518. return $spec;
  519. }
  520. # A relation is stored as the referenced post's UUID, and resolved into the
  521. # post itself at render time -- see the x-tcms-relations table a sidecar
  522. # declares alongside it, and Trog::Routes::HTML::_enrich_post. The pseudo-type
  523. # exists so a sidecar can say what a field *means* rather than just that it
  524. # happens to be a string.
  525. our %relation_schema = ( type => 'string' );
  526. # Sugar: a sidecar says {"type":"upload"} rather than spelling out the
  527. # string-or-hashref dance every upload field would otherwise need. Uploads are
  528. # a hashref on the way in from the browser and the href string they became on
  529. # the way back out of the datastore.
  530. sub _expand_pseudo_types ($node) {
  531. return unless Ref::Util::is_hashref($node);
  532. my %pseudo = (
  533. upload => \%upload_schema,
  534. relation => \%relation_schema,
  535. );
  536. my $type = $node->{type} // '';
  537. if ( $pseudo{$type} ) {
  538. delete $node->{type};
  539. %$node = ( %$node, %{ $pseudo{$type} } );
  540. return;
  541. }
  542. _expand_pseudo_types($_) foreach values( %{ $node->{properties} // {} } );
  543. _expand_pseudo_types( $node->{items} ) if $node->{items};
  544. foreach my $key (qw{oneOf anyOf allOf}) {
  545. next unless Ref::Util::is_arrayref( $node->{$key} );
  546. _expand_pseudo_types($_) foreach @{ $node->{$key} };
  547. }
  548. return;
  549. }
  550. =head2 validate($post)
  551. Filter a post down to the fields its type actually describes, then run what's
  552. left through the schema.
  553. Returns the list of validation errors, which is empty when the post is good.
  554. Note that filtering happens first and silently: the query hash handed to us by
  555. the router is full of things which aren't post fields at all, and never was
  556. meant to round-trip.
  557. =cut
  558. sub _validator {
  559. state $validator;
  560. $validator //= JSON::Validator::Schema::Troglodyne->new();
  561. return $validator;
  562. }
  563. sub validate ($post) {
  564. my $validator = _validator();
  565. my $schema = schema_for( $post->{form} );
  566. foreach my $key ( keys(%$post) ) {
  567. # Drop everything the schema doesn't describe.
  568. my $property = $schema->{properties}{$key};
  569. if ( !$property ) {
  570. delete $post->{$key};
  571. next;
  572. }
  573. # An untouched form input submits the empty string, which is HTML for
  574. # "I wasn't filled in" rather than a number, a boolean or a file. We
  575. # leave it alone for actual string fields, which is what got stored
  576. # before any of this was typed.
  577. delete $post->{$key}
  578. if defined $post->{$key}
  579. && !ref $post->{$key}
  580. && $post->{$key} eq ''
  581. && ( $property->{type} // '' ) ne 'string';
  582. }
  583. # OpenAPIv3 coerces as it goes, so "4" lands in the datastore as 4 and
  584. # checkbox values land as real booleans.
  585. return $validator->validate( $post, $schema );
  586. }
  587. =head2 validate_built($post)
  588. Check the post that is actually about to be written.
  589. validate() runs on what was submitted. _process() then builds the shape that
  590. gets stored -- it turns a visibility into a tag, folds the acls in, resolves
  591. uploads into hrefs -- and until now nothing looked at the result. That is how
  592. every post saved without a visibility came to carry a null in its tags: the
  593. schema describes tags as an array of strings and would have rejected it on the
  594. spot, but it was never asked.
  595. Checks rather than filters, unlike validate(). _process() adds fields the base
  596. schema has never heard of -- content_type, is_video, attachments -- and dropping
  597. what it does not recognise would throw away the work it just did. So this looks
  598. only at the fields the schema actually describes, on a copy, and changes nothing.
  599. Returns the list of validation errors, empty when the post is fit to store.
  600. =cut
  601. sub validate_built ($post) {
  602. my $schema = schema_for( $post->{form} );
  603. my %described = map { $_ => $post->{$_} } grep { exists $schema->{properties}{$_} } keys(%$post);
  604. return _validator()->validate( \%described, $schema );
  605. }
  606. sub add ( $self, @posts ) {
  607. my @to_write;
  608. foreach my $post (@posts) {
  609. # Filter to what this post type actually describes, then validate it.
  610. my @errors = validate($post);
  611. # An arrayref rather than a string on purpose. These errors get shown
  612. # to whoever submitted the post, and Carp::Always decorates a string
  613. # die with a stack trace they have no use for.
  614. die [ map { "$_" } @errors ] if @errors;
  615. # ||= rather than //= for the identity and routing scalars. An
  616. # untouched hidden input submits the empty string, and validate() keeps
  617. # an empty string for a field the schema types as a string -- which id,
  618. # local_href, callback and method all are. //= then saw a defined value
  619. # and left it, so a post created through any editor arrived here with
  620. # id => '' and the flat file model wrote it to 'data/files/', which is
  621. # the datastore directory rather than a post in it.
  622. $post->{id} ||= Trog::Utils::uuid();
  623. $post->{aliases} //= [];
  624. $post->{aliases} = [ $post->{aliases} ] unless ref $post->{aliases} eq 'ARRAY';
  625. if ( $post->{aclname} ) {
  626. # Then this is a series
  627. $post->{local_href} ||= "/$post->{aclname}";
  628. push( @{ $post->{aliases} }, "/posts/$post->{id}", "/series/$post->{id}" );
  629. }
  630. # Every post needs one: _process pushes it into the tags, and an
  631. # undef there is a tag no query will ever match, which makes the post
  632. # invisible to everyone but an admin. A post type built without a
  633. # visibility selector would otherwise produce exactly that. Private
  634. # rather than public, because guessing wrong in the other direction
  635. # publishes something nobody asked to publish.
  636. $post->{visibility} ||= 'private';
  637. $post->{callback} ||= 'Trog::Routes::HTML::posts';
  638. # If this is a user creation post, add in the /user/ route
  639. if ( $post->{callback} eq 'Trog::Routes::HTML::users' ) {
  640. $post->{local_href} ||= "/users/$post->{display_name}";
  641. $post->{title} ||= $post->{display_name};
  642. }
  643. $post->{local_href} ||= "/posts/$post->{id}";
  644. $post->{method} ||= 'GET';
  645. $post->{created} = time();
  646. my @existing_posts = $self->get( id => $post->{id}, acls => [qw{admin}] );
  647. if (@existing_posts) {
  648. my $existing_post = $existing_posts[0];
  649. $post->{version} = $existing_post->{version};
  650. $post->{version}++;
  651. }
  652. $post->{version} //= 0;
  653. #XXX if local_href has /secure paths in it, fix this. We don't want to save that.
  654. if ( index( $post->{local_href}, '/secure/' ) == 0 ) {
  655. $post->{local_href} =~ s|/secure||gmx;
  656. }
  657. $post = _process($post);
  658. # And check what _process() built, not just what arrived. A post that
  659. # fails here is one this code has made wrong on its way to disk, so it
  660. # is a bug rather than bad input -- but the answer is still to refuse to
  661. # write it, because the alternative is what we did before, which was to
  662. # write it and find out years later.
  663. my @built = validate_built($post);
  664. if (@built) {
  665. WARN( "Refusing to store a post this built wrong: " . join( ', ', map { "$_" } @built ) );
  666. die [ map { "$_" } @built ];
  667. }
  668. push @to_write, $post;
  669. }
  670. $self->write( \@to_write );
  671. return 0;
  672. }
  673. #XXX this level of post-processing seems gross, but may be unavoidable
  674. # Not actually a subprocess, kek
  675. sub _process ($post) {
  676. # Here as well as in add(), because this is the sub that turns a visibility
  677. # into a tag: without one it pushed an undef into tags, which is a tag no
  678. # query ever matches, so the post went invisible to everyone but an admin.
  679. # Nothing complained, and the bunk tag was written to disk and stayed there.
  680. $post->{visibility} ||= 'private';
  681. # If the post is private, make sure it's associated assets are too.
  682. my $is_private_post = $post->{visibility} eq 'private';
  683. $post->{href} = _handle_upload( $post->{file}, $post->{id}, $is_private_post ) if $post->{file};
  684. $post->{preview} = _handle_upload( $post->{preview_file}, $post->{id}, $is_private_post ) if $post->{preview_file};
  685. $post->{wallpaper} = _handle_upload( $post->{wallpaper_file}, $post->{id}, $is_private_post ) if $post->{wallpaper_file};
  686. @{ $post->{attachments} } = map { _handle_upload( $_, $post->{id}, $is_private_post ) } @{ $post->{attachments} } if $post->{attachments};
  687. $post->{preview} = $post->{href} if $post->{app} && $post->{app} eq 'image';
  688. delete $post->{app};
  689. delete $post->{file};
  690. delete $post->{preview_file};
  691. delete $post->{wallpaper_file};
  692. delete $post->{scheme};
  693. delete $post->{route};
  694. delete $post->{domain};
  695. # Handle acls/tags
  696. $post->{tags} //= [];
  697. $post->{acls} //= [];
  698. @{ $post->{tags} } = grep {
  699. my $subj = $_;
  700. !grep { $_ eq $subj } qw{public private unlisted}
  701. } @{ $post->{tags} };
  702. push( @{ $post->{tags} }, grep { defined } @{ $post->{acls} } ) if $is_private_post;
  703. delete $post->{acls};
  704. push( @{ $post->{tags} }, $post->{visibility} );
  705. # Add the 'series' tag if we are in a series, restrict to relevant acl
  706. if ( $post->{series} ) {
  707. push( @{ $post->{tags} }, 'series' );
  708. push( @{ $post->{tags} }, $post->{series} );
  709. }
  710. #Filter adding the same acl twice, and anything that isn't a tag at all --
  711. # an undef here is what every query below compares against, and it warns
  712. # its way through the lot before matching nothing.
  713. @{ $post->{tags} } = List::Util::uniq( grep { defined && length } @{ $post->{tags} } );
  714. @{ $post->{aliases} } = List::Util::uniq( grep { defined && length } @{ $post->{aliases} } );
  715. # Handle multimedia content types
  716. $post->{content_type} = Trog::Utils::mime_type("www/$post->{href}") if $post->{href};
  717. $post->{video_content_type} = Trog::Utils::mime_type("www/$post->{video_href}") if $post->{video_href};
  718. $post->{audio_content_type} = Trog::Utils::mime_type("www/$post->{audio_href}") if $post->{audio_href};
  719. $post->{content_type} ||= 'text/html';
  720. $post->{is_video} = 1 if $post->{content_type} =~ m/^video\//;
  721. $post->{is_audio} = 1 if $post->{content_type} =~ m/^audio\//;
  722. $post->{is_image} = 1 if $post->{content_type} =~ m/^image\//;
  723. $post->{is_profile} = 1 if grep { $_ eq 'about' } @{ $post->{tags} };
  724. return $post;
  725. }
  726. # Browsers try and save time in the event that the same file is sent twice, so handle that.
  727. my %seen_files;
  728. sub _handle_upload ( $file, $uuid, $private = 0 ) {
  729. my $fname;
  730. if ( ref $file ne 'HASH' ) {
  731. use Data::Dumper;
  732. $file =~ s/\\/\//g;
  733. $fname = basename($file);
  734. FATAL("Did not expect bogus file before its real counterpart!") unless $seen_files{$fname};
  735. return $seen_files{$fname};
  736. }
  737. my $f = $file->{tempname};
  738. $fname = basename( $file->{filename} );
  739. my $newname = "$uuid.$file->{filename}";
  740. $newname = "private/$newname" if $private;
  741. File::Copy::move( $f, "www/assets/$newname" );
  742. # Regrettably, we have no control over the perms of the temp file that starman creates for uploads.
  743. chmod( 0755, "www/assets/$newname" );
  744. $seen_files{$fname} = "/assets/$newname";
  745. return $seen_files{$fname};
  746. }
  747. =head2 delete(@posts)
  748. Delete the following posts.
  749. Will remove all versions of said post.
  750. You should override this, it is a stub here.
  751. =cut
  752. sub delete ($self) { die 'stub' }
  753. =head2 routes() = HASH
  754. Returns the routes to each post.
  755. You should override this for performance reasons, as it's just a wrapper around get() by defualt.
  756. =cut
  757. sub routes ($self) {
  758. my %routes = map { $_->{local_href} => { method => $_->{method}, callback => \&{ $_->{callback} } } } ( $self->get( limit => 0, acls => ['admin'] ) );
  759. return %routes;
  760. }
  761. =head2 aliases() = HASH
  762. Returns the aliases for each post, indexed by aliases.
  763. You should override this for performance reasons, as it's just a wrapper around get() by defualt.
  764. =cut
  765. sub aliases ($self) {
  766. my @posts = $self->get( limit => 0, acls => ['admin'] );
  767. my %aliases;
  768. foreach my $post (@posts) {
  769. $aliases{$_} = $post->{local_href} for @{ $post->{aliases} // [] };
  770. }
  771. return %aliases;
  772. }
  773. 1;