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