]> sipb.mit.edu Git - ikiwiki.git/blob - doc/todo/structured_page_data.mdwn
Continuing discussion about reverting via the web interface.
[ikiwiki.git] / doc / todo / structured_page_data.mdwn
1 This is an idea from [[JoshTriplett]].  --[[Joey]]
2
3 * See further discussion at [[forum/an_alternative_approach_to_structured_data]].
4
5 Some uses of ikiwiki, such as for a bug-tracking system (BTS), move a bit away from the wiki end
6 of the spectrum, and toward storing structured data about a page or instead
7 of a page. 
8
9 For example, in a bug report you might want to choose a severity from a
10 list, enter a version number, and have a bug submitter or owner recorded,
11 etc. When editing online, it would be nice if these were separate fields on
12 the form, rather than the data being edited in the big edit form.
13
14 There's a tension here between remaining a wiki with human-editable source
15 files, containing freeform markup, and more structured data storage. I
16 think that it would be best to include the structured data in the page,
17 using a directive. Something like:
18
19         part of page content
20         \[[data yaml="<arbitrary yaml here>"]]
21         rest of page content 
22
23 As long as the position of the directive is not significant, it could be
24 stripped out when web editing, the yaml used to generate/populate form fields, 
25 and then on save, the directive regenerated and inserted at top/bottom of
26 the page.
27
28 Josh thinks that yaml is probably a good choice, but the source could be a
29 `.yaml` file that contains no directives, and just yaml. An addition
30 complication in this scenario is, if the yaml included wiki page formatted content,
31 ikiwiki would have to guess or be told what markup language it used.
32
33 Either way, the yaml on the page would encode fields and their current content.
34 Information about data types would be encoded elsewhere, probably on a
35 parent page (using a separate directive). That way, all child pages could
36 be forced to have the same fields.
37
38 There would be some simple types like select, boolean, multiselect, string, wiki markup.
39 Probably lists of these (ie, list of strings). Possibly more complex data
40 structures.
41
42 It should also be possible for plugins to define new types, and the type
43 definitions should include validation of entered data, and how to prompt
44 the user for the data.
45
46 This seems conceptually straightforward, if possibly quite internally
47 complex to handle the more complicated types and validation.
48
49 One implementation wrinkle is how to build the html form. The editpage.tmpl
50 currently overrides the standard [[!cpan CGI::FormBuilder]] generated form,
51 which was done to make the edit page be laid out in a nice way. This,
52 however, means that new fields cannot be easily added to it using
53 [[!cpan CGI::FormBuilder]]. The attachment plugin uses the hack of bouilding
54 up html by hand and dumping it into the form via a template variable. 
55
56 It would be nice if the type implementation code could just use
57 FormBuilder, since its automatic form generation, and nice field validation
58 model is a perfect match for structured data. But this problem with
59 editpage.tmpl would have to be sorted out to allow that.
60
61 Additional tie-ins:
62
63 * Pagespecs that can select pages with a field with a given value, etc.
64   This should use a pagespec function like field(fieldname, value).  The
65   semantics of this will depend on the type of the field; text fields will
66   match value against the text, and link fields will check for a link
67   matching the pagespec value.
68 * The search plugin could allow searching for specific fields with specific
69   content. (xapian term search is a good fit).
70
71 See also:
72
73 [[tracking_bugs_with_dependencies]]
74
75 > I was also thinking about this for bug tracking.  I'm not sure what
76 > sort of structured data is wanted in a page, so I decided to brainstorm
77 > use cases:
78 >
79 > * You just want the page to be pretty.
80 > * You want to access the data from another page.  This would be almost like
81 >     like a database lookup, or the OpenOffice Calc [VLookup](http://wiki.services.openoffice.org/wiki/Documentation/How_Tos/Calc:_VLOOKUP_function) function.
82 > * You want to make a pagespec depend upon the data.  This could be used
83 >    for dependancy tracking - you could match against pages listed as dependencies,
84 >    rather than all pages linked from a given page.
85 >
86 >The first use case is handled by having a template in the page creation.  You could
87
88
89
90
91 >have some type of form to edit the data, but that's just sugar on top of the template.
92 >If you were going to have a web form to edit the data, I can imagine a few ways to do it:
93 >
94 > * Have a special page type which gets compiled into the form.  The page type would
95 >    need to define the form as well as hold the stored data.
96 > * Have special directives that allow you to insert form elements into a normal page.
97 >
98 >I'm happy with template based page creation as a first pass...
99 >
100 >The second use case could be handled by a regular expression directive. eg:
101 >
102 > \[[regex spec="myBug" regex="Depends: ([^\s]+)"]]
103 >
104 > The directive would be replaced with the match from the regex on the 'myBug' page... or something.
105 >
106 >The third use case requires a pagespec function.  One that matched a regex in the page might work.
107 >Otherwise, another option would be to annotate links with a type, and then check the type of links in
108 >a pagespec.  e.g. you could have `depends` links and normal links.
109 >
110 >Anyway, I just wanted to list the thoughts.  In none of these use cases is straight yaml or json the
111 >obvious answer.  -- [[Will]]
112
113 >> Okie.  I've had a play with this.  A 'form' plugin is included inline below, but it is only a rough first pass to
114 >> get a feel for the design space.
115 >>
116 >> The current design defines a new type of page - a 'form'.  The type of page holds YAML data
117 >> defining a FormBuilder form.  For example, if we add a file to the wiki source `test.form`:
118
119     ---
120     fields:
121       age:
122         comment: This is a test
123         validate: INT
124         value: 15
125
126 >> The YAML content is a series of nested hashes.  The outer hash is currently checked for two keys:
127 >> 'template', which specifies a parameter to pass to the FromBuilder as the template for the
128 >> form, and 'fields', which specifies the data for the fields on the form.
129 >> each 'field' is itself a hash.  The keys and values are arguments to the formbuilder form method.
130 >> The most important one is 'value', which specifies the value of that field.
131 >>
132 >> Using this, the plugin below can output a form when asked to generate HTML.  The Formbuilder
133 >> arguments are sanitized (need a thorough security audit here - I'm sure I've missed a bunch of
134 >> holes).  The form is generated with default values as supplied in the YAML data.  It also has an
135 >> 'Update Form' button at the bottom.
136 >>
137 >>  The 'Update Form' button in the generated HTML submits changed values back to IkiWiki.  The
138 >> plugin captures these new values, updates the YAML and writes it out again.  The form is
139 >> validated when edited using this method.  This method can only edit the values in the form.
140 >> You cannot add new fields this way.
141 >>
142 >> It is still possible to edit the YAML directly using the 'edit' button.  This allows adding new fields
143 >> to the form, or adding other formbuilder data to change how the form is displayed.
144 >>
145 >> One final part of the plugin is a new pagespec function.  `form_eq()` is a pagespec function that
146 >> takes two arguments (separated by a ',').  The first argument is a field name, the second argument
147 >> a value for that field.  The function matches forms (and not other page types) where the named
148 >> field exists and holds the value given in the second argument.  For example:
149     
150     \[[!inline pages="form_eq(age,15)" archive="yes"]]
151     
152 >> will include a link to the page generated above.
153
154 >>> Okie, I've just made another plugin to try and do things in a different way.
155 >>> This approach adds a 'data' directive.  There are two arguments, `key` and `value`.
156 >>> The directive is replaced by the value.  There is also a match function, which is similar
157 >>> to the one above.  It also takes two arguments, a key and a value.  It returns true if the
158 >>> page has that key/value pair in a data directive.  e.g.:
159
160     \[[!data key="age" value="15"]]
161
162 >>> then, in another page:
163
164     \[[!inline pages="data_eq(age,15)" archive="yes"]]
165
166 >>> I expect that we could have more match functions for each type of structured data,
167 >>> I just wanted to implement a rough prototype to get a feel for how it behaves.  -- [[Will]]
168
169 >> Anyway, here are the plugins.  As noted above these are only preliminary, exploratory, attempts. -- [[Will]]
170
171 >>>> I've just updated the second of the two patches below.  The two patches are not mutually
172 >>>> exclusive, but I'm leaning towards the second as more useful (for the things I'm doing). -- [[Will]]
173
174 I think it's awesome that you're writing this code to explore the problem
175 space, [[Will]] -- and these plugins are good stabs at at least part of it.
176 Let me respond to a few of your comments.. --[[Joey]]
177
178 On use cases, one use case is a user posting a bug report with structured
179 data in it. A template is one way, but then the user has to deal with the
180 format used to store the structured data. This is where a edit-time form
181 becomes essential.
182
183 > This was the idea with the 'form' plugin.  With the 'data' plugin I was exploring
184 > a different approach: try to keep the markup simple enough that the user can edit
185 > the markup directly, and still have that be ok.  I admit it is a stretch, but I thought
186 > it worth exploring.
187
188 Another use case is, after many such bugs have been filed,
189 wanting to add a new field to each bug report. To avoid needing to edit
190 every bug report it would be good if the fields in a bug report were
191 defined somewhere else, so that just that one place can be edited to add
192 the new field, and it will show up in each bug report (and in each bug
193 report's edit page, as a new form field).
194
195 > If I was going to do that, I'd use a perl script on a checked out
196 > workspace.  I think you're describing a rare operation and
197 > so I'd be happy not having a web interface for it.  Having said that,
198 > if you just wanted to change the form for *new* pages, then you
199 > can just edit the template used to create new pages.
200
201 Re the form plugin, I'm uncomfortable with tying things into
202 [[!cpan CGI::FormBuilder]] quite so tightly as you have.
203
204 > Yeah :).  But I wanted to explore the space and that was the
205 > easiest way to start.
206
207 CGI::FormBuilder
208 could easily change in a way that broke whole wikis full of pages. Also,
209 needing to sanitize FormBuilder fields with security implications is asking
210 for trouble, since new FormBuilder features could add new fields, or
211 add new features to existing fields (FormBuilder is very DWIM) that open
212 new security holes. 
213
214 > There is a list of allowed fields.  I only interpret those.
215
216 I think that having a type system, that allows defining specific types,
217 like "email address", by writing code (that in turn can use FormBuilder),
218 is a better approach, since it should avoid becoming a security problem.
219
220 > That would be possible.  I think an extension to the 'data' plugin might
221 > work here.
222
223 One specific security hole, BTW, is that if you allow the `validate` field,
224 FormBuilder will happily treat it as a regexp, and we don't want to expose
225 arbitrary perl regexps, since they can at least DOS a system, and can
226 probably be used to run arbitrary perl code.
227
228 > I validate the validate field :).  It only allows validate fields that match
229 > `/^[\w\s]+$/`.  This means you can really only use the pre-defined
230 > validation types in FormBuilder.
231
232 The data plugin only deals with a fairly small corner of the problem space,
233 but I think does a nice job at what it does. And could probably be useful
234 in a large number of other cases.
235
236 > I think the data plugin is more likely to be useful than the form plugin.
237 > I was thinking of extending the data directive by allowing an 'id' parameter.
238 > When you have an id parameter, then you can display a small form for that
239 > data element.  The submission handler would look through the page source
240 > for the data directive with the right id parameter and edit it.  This would
241 > make the data directive more like the current 'form' plugin.
242
243 > That is making things significantly more complex for less significant gain though. --[[Will]]
244
245 > Oh, one quick other note.  The data plugin below was designed to handle multiple
246 > data elements in a single directive.  e.g.
247
248     \[[!data key="Depends on" link="bugs/bugA" link="bugs/bugB" value=6]]
249
250 > would match `data_eq(Depends on,6)`, `data_link(Depends on,bugs/bugA)`, `data_link(Depends on,bugs/bugB)`
251 > or, if you applied the patch in [[todo/tracking_bugs_with_dependencies]] then you can use 'defined pagespecs'
252 > such as `data_link(Depends on,~openBugs)`. <a id="another_kind_of_links" />The ability to label links like this allows separation of
253 > dependencies between bugs from arbitrary links.
254 >> This issue (the need for distinguished kinds of links) has also been brought up in other discussions: [[tracking_bugs_with_dependencies#another_kind_of_links]] (deps vs. links) and [[tag_pagespec_function]] (tags vs. links). --Ivan Z.
255
256 >>> And multiple link types are now supported; plugins can set the link
257 >>> type when registering a link, and pagespec functions can match on them. --[[Joey]] 
258
259 ----
260
261     #!/usr/bin/perl
262     # Interpret YAML data to make a web form
263     package IkiWiki::Plugin::form;
264     
265     use warnings;
266     use strict;
267     use CGI::FormBuilder;
268     use IkiWiki 2.00;
269     
270     sub import {
271         hook(type => "getsetup", id => "form", call => \&getsetup);
272         hook(type => "htmlize", id => "form", call => \&htmlize);
273         hook(type => "sessioncgi", id => "form", call => \&cgi_submit);
274     }
275     
276     sub getsetup () {
277         return
278                 plugin => {
279                         safe => 1,
280                         rebuild => 1, # format plugin
281                 },
282     }
283     
284     sub makeFormFromYAML ($$$) {
285         my $page = shift;
286         my $YAMLString = shift;
287         my $q = shift;
288     
289         eval q{use YAML};
290         error($@) if $@;
291         eval q{use CGI::FormBuilder};
292         error($@) if $@;
293         
294         my ($dataHashRef) = YAML::Load($YAMLString);
295         
296         my @fields = keys %{ $dataHashRef->{fields} };
297         
298         unshift(@fields, 'do');
299         unshift(@fields, 'page');
300         unshift(@fields, 'rcsinfo');
301         
302         # print STDERR "Fields: @fields\n";
303         
304         my $submittedPage;
305         
306         $submittedPage = $q->param('page') if defined $q;
307         
308         if (defined $q && defined $submittedPage && ! ($submittedPage eq $page)) {
309                 error("Submitted page doensn't match current page: $page, $submittedPage");
310         }
311         
312         error("Page not backed by file") unless defined $pagesources{$page};
313         my $file = $pagesources{$page};
314         
315         my $template;
316         
317         if (defined $dataHashRef->{template}) {
318                 $template = $dataHashRef->{template};
319         } else {
320                 $template = "form.tmpl";
321         }
322         
323         my $form = CGI::FormBuilder->new(
324                 fields => \@fields,
325                 charset => "utf-8",
326                 method => 'POST',
327                 required => [qw{page}],
328                 params => $q,
329                 action => $config{cgiurl},
330                 template => scalar IkiWiki::template_params($template),
331                 wikiname => $config{wikiname},
332                 header => 0,
333                 javascript => 0,
334                 keepextras => 0,
335                 title => $page,
336         );
337         
338         $form->field(name => 'do', value => 'Update Form', required => 1, force => 1, type => 'hidden');
339         $form->field(name => 'page', value => $page, required => 1, force => 1, type => 'hidden');
340         $form->field(name => 'rcsinfo', value => IkiWiki::rcs_prepedit($file), required => 1, force => 0, type => 'hidden');
341         
342         my %validkey;
343         foreach my $x (qw{label type multiple value fieldset growable message other required validate cleanopts columns comment disabled linebreaks class}) {
344                 $validkey{$x} = 1;
345         }
346     
347         while ( my ($name, $data) = each(%{ $dataHashRef->{fields} }) ) {
348                 next if $name eq 'page';
349                 next if $name eq 'rcsinfo';
350                 
351                 while ( my ($key, $value) = each(%{ $data }) ) {
352                         next unless $validkey{$key};
353                         next if $key eq 'validate' && !($value =~ /^[\w\s]+$/);
354                 
355                         # print STDERR "Adding to field $name: $key => $value\n";
356                         $form->field(name => $name, $key => $value);
357                 }
358         }
359         
360         # IkiWiki::decode_form_utf8($form);
361         
362         return $form;
363     }
364     
365     sub htmlize (@) {
366         my %params=@_;
367         my $content = $params{content};
368         my $page = $params{page};
369     
370         my $form = makeFormFromYAML($page, $content, undef);
371     
372         return $form->render(submit => 'Update Form');
373     }
374     
375     sub cgi_submit ($$) {
376         my $q=shift;
377         my $session=shift;
378         
379         my $do=$q->param('do');
380         return unless $do eq 'Update Form';
381         IkiWiki::decode_cgi_utf8($q);
382     
383         eval q{use YAML};
384         error($@) if $@;
385         eval q{use CGI::FormBuilder};
386         error($@) if $@;
387         
388         my $page = $q->param('page');
389         
390         return unless exists $pagesources{$page};
391         
392         return unless $pagesources{$page} =~ m/\.form$/ ;
393         
394         return unless IkiWiki::check_canedit($page, $q, $session);
395     
396         my $file = $pagesources{$page};
397         my $YAMLString = readfile(IkiWiki::srcfile($file));
398         my $form = makeFormFromYAML($page, $YAMLString, $q);
399     
400         my ($dataHashRef) = YAML::Load($YAMLString);
401     
402         if ($form->submitted eq 'Update Form' && $form->validate) {
403                 
404                 #first update our data structure
405                 
406                 while ( my ($name, $data) = each(%{ $dataHashRef->{fields} }) ) {
407                         next if $name eq 'page';
408                         next if $name eq 'rcs-data';
409                         
410                         if (defined $q->param($name)) {
411                                 $data->{value} = $q->param($name);
412                         }
413                 }
414                 
415                 # now write / commit the data
416                 
417                 writefile($file, $config{srcdir}, YAML::Dump($dataHashRef));
418     
419                 my $message = "Web form submission";
420     
421                 IkiWiki::disable_commit_hook();
422                 my $conflict=IkiWiki::rcs_commit($file, $message,
423                         $form->field("rcsinfo"),
424                         $session->param("name"), $ENV{REMOTE_ADDR});
425                 IkiWiki::enable_commit_hook();
426                 IkiWiki::rcs_update();
427     
428                 require IkiWiki::Render;
429                 IkiWiki::refresh();
430     
431                 IkiWiki::redirect($q, "$config{url}/".htmlpage($page)."?updated");
432     
433         } else {
434                 error("Invalid data!");
435         }
436     
437         exit;
438     }
439     
440     package IkiWiki::PageSpec;
441     
442     sub match_form_eq ($$;@) {
443         my $page=shift;
444         my $argSet=shift;
445         my @args=split(/,/, $argSet);
446         my $field=shift @args;
447         my $value=shift @args;
448     
449         my $file = $IkiWiki::pagesources{$page};
450         
451         if ($file !~ m/\.form$/) {
452                 return IkiWiki::FailReason->new("page is not a form");
453         }
454         
455         my $YAMLString = IkiWiki::readfile(IkiWiki::srcfile($file));
456     
457         eval q{use YAML};
458         error($@) if $@;
459     
460         my ($dataHashRef) = YAML::Load($YAMLString);
461     
462         if (! defined $dataHashRef->{fields}->{$field}) {
463                 return IkiWiki::FailReason->new("field '$field' not defined in page");
464         }
465     
466         my $formVal = $dataHashRef->{fields}->{$field}->{value};
467     
468         if ($formVal eq $value) {
469                 return IkiWiki::SuccessReason->new("field value matches");
470         } else {
471                 return IkiWiki::FailReason->new("field value does not match");
472         }
473     }
474     
475     1
476
477 ----
478
479     #!/usr/bin/perl
480     # Allow data embedded in a page to be checked for
481     package IkiWiki::Plugin::data;
482     
483     use warnings;
484     use strict;
485     use IkiWiki 2.00;
486     
487     my $inTable = 0;
488     
489     sub import {
490         hook(type => "getsetup", id => "data", call => \&getsetup);
491         hook(type => "needsbuild", id => "data", call => \&needsbuild);
492         hook(type => "preprocess", id => "data", call => \&preprocess, scan => 1);
493         hook(type => "preprocess", id => "datatable", call => \&preprocess_table, scan => 1);   # does this need scan?
494     }
495     
496     sub getsetup () {
497         return
498                 plugin => {
499                         safe => 1,
500                         rebuild => 1, # format plugin
501                 },
502     }
503     
504     sub needsbuild (@) {
505         my $needsbuild=shift;
506         foreach my $page (keys %pagestate) {
507                 if (exists $pagestate{$page}{data}) {
508                         if (exists $pagesources{$page} &&
509                             grep { $_ eq $pagesources{$page} } @$needsbuild) {
510                                 # remove state, it will be re-added
511                                 # if the preprocessor directive is still
512                                 # there during the rebuild
513                                 delete $pagestate{$page}{data};
514                         }
515                 }
516         }
517     }
518     
519     sub preprocess (@) {
520         my @argslist = @_;
521         my %params=@argslist;
522         
523         my $html = '';
524         my $class = defined $params{class}
525                         ? 'class="'.$params{class}.'"'
526                         : '';
527         
528         if ($inTable) {
529                 $html = "<th $class >$params{key}:</th><td $class >";
530         } else {
531                 $html = "<span $class >$params{key}:";
532         }
533         
534         while (scalar(@argslist) > 1) {
535                 my $type = shift @argslist;
536                 my $data = shift @argslist;
537                 if ($type eq 'link') {
538                         # store links raw
539                         $pagestate{$params{page}}{data}{$params{key}}{link}{$data} = 1;
540                         my $link=IkiWiki::linkpage($data);
541                         add_depends($params{page}, $link);
542                         $html .= ' ' . htmllink($params{page}, $params{destpage}, $link);
543                 } elsif ($type eq 'data') {
544                         $data = IkiWiki::preprocess($params{page}, $params{destpage}, 
545                                 IkiWiki::filter($params{page}, $params{destpage}, $data));
546                         $html .= ' ' . $data;
547                         # store data after processing - allows pagecounts to be stored, etc.
548                         $pagestate{$params{page}}{data}{$params{key}}{data}{$data} = 1;
549                 }
550         }
551                 
552         if ($inTable) {
553                 $html .= "</td>";
554         } else {
555                 $html .= "</span>";
556         }
557         
558         return $html;
559     }
560     
561     sub preprocess_table (@) {
562         my %params=@_;
563     
564         my @lines;
565         push @lines, defined $params{class}
566                         ? "<table class=\"".$params{class}.'">'
567                         : '<table>';
568     
569         $inTable = 1;
570     
571         foreach my $line (split(/\n/, $params{datalist})) {
572                 push @lines, "<tr>" . IkiWiki::preprocess($params{page}, $params{destpage}, 
573                         IkiWiki::filter($params{page}, $params{destpage}, $line)) . "</tr>";
574         }
575     
576         $inTable = 0;
577     
578         push @lines, '</table>';
579     
580         return join("\n", @lines);
581     }
582     
583     package IkiWiki::PageSpec;
584     
585     sub match_data_eq ($$;@) {
586         my $page=shift;
587         my $argSet=shift;
588         my @args=split(/,/, $argSet);
589         my $key=shift @args;
590         my $value=shift @args;
591     
592         if (! exists $IkiWiki::pagestate{$page}{data}) {
593                 return IkiWiki::FailReason->new("page does not contain any data directives");
594         }
595         
596         if (! exists $IkiWiki::pagestate{$page}{data}{$key}) {
597                 return IkiWiki::FailReason->new("page does not contain data key '$key'");
598         }
599         
600         if ($IkiWiki::pagestate{$page}{data}{$key}{data}{$value}) {
601                 return IkiWiki::SuccessReason->new("value matches");
602         } else {
603                 return IkiWiki::FailReason->new("value does not match");
604         }
605     }
606     
607     sub match_data_link ($$;@) {
608         my $page=shift;
609         my $argSet=shift;
610         my @params=@_;
611         my @args=split(/,/, $argSet);
612         my $key=shift @args;
613         my $value=shift @args;
614     
615         if (! exists $IkiWiki::pagestate{$page}{data}) {
616                 return IkiWiki::FailReason->new("page $page does not contain any data directives and so cannot match a link");
617         }
618         
619         if (! exists $IkiWiki::pagestate{$page}{data}{$key}) {
620                 return IkiWiki::FailReason->new("page $page does not contain data key '$key'");
621         }
622         
623         foreach my $link (keys %{ $IkiWiki::pagestate{$page}{data}{$key}{link} }) {
624                 # print STDERR "Checking if $link matches glob $value\n";
625                 if (match_glob($link, $value, @params)) {
626                         return IkiWiki::SuccessReason->new("Data link on page $page with key $key matches glob $value: $link");
627                 }
628         }
629     
630         return IkiWiki::FailReason->new("No data link on page $page with key $key matches glob $value");
631     }
632     
633     1