DataModule.pm 37 KB

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