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