DataModule.pm 37 KB

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