weekly release 2.3dev (blame stronk7 for 0202 mistake)
[moodle.git] / lib / portfolio / formats / leap2a / lib.php
CommitLineData
59dd457e
PL
1<?php
2/**
3 * Moodle - Modular Object-Oriented Dynamic Learning Environment
4 * http://moodle.org
5 * Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
0972665f 20 * @package core
59dd457e
PL
21 * @subpackage portfolio
22 * @author Penny Leach <penny@liip.ch>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL
24 * @copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com
25 *
26 * This file contains the LEAP2a writer used by portfolio_format_leap2a
27 */
28
0972665f
PS
29defined('MOODLE_INTERNAL') || die();
30
59dd457e
PL
31/**
32 * object to encapsulate the writing of leap2a.
33 * should be used like:
34 *
35 * $writer = portfolio_format_leap2a::leap2a_writer($USER);
ebb7e782 36 * $entry = new portfolio_format_leap2a_entry('forumpost6', $title, 'leap2', 'somecontent')
59dd457e
PL
37 * $entry->add_link('something', 'has_part')->add_link('somethingelse', 'has_part');
38 * .. etc
39 * $writer->add_entry($entry);
40 * $xmlstr = $writer->to_xml();
41 *
42 * @TODO find a way to ensure that all referenced files are included
43 */
44class portfolio_format_leap2a_writer {
45
46 /** the domdocument object used to create elements */
47 private $dom;
48 /** the top level feed element */
49 private $feed;
50 /** the user exporting data */
51 private $user;
52 /** the id of the feed - this is unique to the user and date and used for portfolio ns as well as feed id */
53 private $id;
54 /** the entries for the feed - keyed on id */
55 private $entries = array();
56
57 /**
58 * constructor - usually generated from portfolio_format_leap2a::leap2a_writer($USER);
59 *
60 * @param stdclass $user the user exporting (almost always $USER)
61 *
62 */
63 public function __construct(stdclass $user) { // todo something else - exporter, format, etc
64 global $CFG;
65 $this->user = $user;
66 $this->exporttime = time();
67 $this->id = $CFG->wwwroot . '/portfolio/export/leap2a/' . $this->user->id . '/' . $this->exporttime;
68
69 $this->dom = new DomDocument('1.0', 'utf-8');
70
71 $this->feed = $this->dom->createElement('feed');
72 $this->feed->setAttribute('xmlns', 'http://www.w3.org/2005/Atom');
73 $this->feed->setAttribute('xmlns:rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
ebb7e782
PL
74 $this->feed->setAttribute('xmlns:leap2', 'http://terms.leapspecs.org/');
75 $this->feed->setAttribute('xmlns:categories', 'http://wiki.leapspecs.org/2A/categories');
59dd457e
PL
76 $this->feed->setAttribute('xmlns:portfolio', $this->id); // this is just a ns for ids of elements for convenience
77
78 $this->dom->appendChild($this->feed);
79
80 $this->feed->appendChild($this->dom->createElement('id', $this->id));
8e642e1f 81 $this->feed->appendChild($this->dom->createElement('title', get_string('leap2a_feedtitle', 'portfolio', fullname($this->user))));
ebb7e782
PL
82 $this->feed->appendChild($this->dom->createElement('leap2:version', 'http://www.leapspecs.org/2010-07/2A/'));
83
59dd457e
PL
84
85 $generator = $this->dom->createElement('generator', 'Moodle');
86 $generator->setAttribute('uri', $CFG->wwwroot);
87 $generator->setAttribute('version', $CFG->version);
88
89 $this->feed->appendChild($generator);
90
91 $author = $this->dom->createElement('author');
92 $author->appendChild($this->dom->createElement('name', fullname($this->user)));
93 $author->appendChild($this->dom->createElement('email', $this->user->email));
94 $author->appendChild($this->dom->CreateElement('uri', $CFG->wwwroot . '/user/view.php?id=' . $this->user->id));
95
96 $this->feed->appendChild($author);
97 // header done, we can start appending entry elements now
98 }
99
100 /**
101 * adds a entry to the feed ready to be exported
102 *
103 * @param portfolio_format_leap2a_entry $entry the entry to add
104 */
105 public function add_entry(portfolio_format_leap2a_entry $entry) {
106 if (array_key_exists($entry->id, $this->entries)) {
ebb7e782
PL
107 if (!($entry instanceof portfolio_format_leap2a_file)) {
108 throw new portfolio_format_leap2a_exception('leap2a_entryalreadyexists', 'portfolio', '', $entry->id);
109 }
59dd457e
PL
110 }
111 $this->entries[$entry->id] = $entry;
112 return $entry;
113 }
114
115 /**
116 * make an entry that has previously been added into the feed into a selection.
117 *
118 * @param mixed $selectionentry the entry to make a selection (id or entry object)
119 * @param array $ids array of ids this selection includes
120 * @param string $selectiontype http://wiki.cetis.ac.uk/2009-03/LEAP2A_categories/selection_type
121 */
122 public function make_selection($selectionentry, $ids, $selectiontype) {
123 $selectionid = null;
124 if ($selectionentry instanceof portfolio_format_leap2a_entry) {
125 $selectionid = $selectionentry->id;
126 } else if (is_string($selectionentry)) {
127 $selectionid = $selectionentry;
128 }
129 if (!array_key_exists($selectionid, $this->entries)) {
8e642e1f 130 throw new portfolio_format_leap2a_exception('leap2a_invalidentryid', 'portfolio', '', $selectionid);
59dd457e
PL
131 }
132 foreach ($ids as $entryid) {
133 if (!array_key_exists($entryid, $this->entries)) {
8e642e1f 134 throw new portfolio_format_leap2a_exception('leap2a_invalidentryid', 'portfolio', '', $entryid);
59dd457e
PL
135 }
136 $this->entries[$selectionid]->add_link($entryid, 'has_part');
137 $this->entries[$entryid]->add_link($selectionid, 'is_part_of');
138 }
139 $this->entries[$selectionid]->add_category($selectiontype, 'selection_type');
140 if ($this->entries[$selectionid]->type != 'selection') {
8e642e1f 141 debugging(get_string('leap2a_overwritingselection', 'portfolio', $this->entries[$selectionid]->type));
59dd457e
PL
142 $this->entries[$selectionid]->type = 'selection';
143 }
144 }
145
ebb7e782
PL
146 /**
147 * helper function to link some stored_files into the feed and link them to a particular entry
148 *
149 * @param portfolio_format_leap2a_entry $entry the entry to link the files into
150 * @param array $files array of stored_files to link
151 */
152 public function link_files($entry, $files) {
153 foreach ($files as $file) {
154 $fileentry = new portfolio_format_leap2a_file($file->get_filename(), $file);
155 $this->add_entry($fileentry);
156 $entry->add_link($fileentry, 'related');
157 $fileentry->add_link($entry, 'related');
158 }
159 }
160
59dd457e
PL
161 /**
162 * validate the feed and all entries
163 */
164 private function validate() {
165 foreach ($this->entries as $entry) {
166 // first call the entry's own validation method
167 // which will throw an exception if there's anything wrong
168 $entry->validate();
169 // now make sure that all links are in place
170 foreach ($entry->links as $linkedid => $rel) {
171 // the linked to entry exists
172 if (!array_key_exists($linkedid, $this->entries)) {
173 $a = (object)array('rel' => $rel->type, 'to' => $linkedid, 'from' => $entry->id);
8e642e1f 174 throw new portfolio_format_leap2a_exception('leap2a_nonexistantlink', 'portfolio', '', $a);
59dd457e
PL
175 }
176 // and contains a link back to us
177 if (!array_key_exists($entry->id, $this->entries[$linkedid]->links)) {
178
179 }
180 // we could later check that the reltypes were properly inverse, but nevermind for now.
181 }
182 }
183 }
184
185 /**
186 * return the entire feed as a string
187 * calls validate() first on everything
188 *
189 * @return string
190 */
191 public function to_xml() {
192 $this->validate();
193 foreach ($this->entries as $entry) {
491fff64 194 $entry->id = 'portfolio:' . $entry->id;
59dd457e
PL
195 $this->feed->appendChild($entry->to_dom($this->dom, $this->user));
196 }
197 return $this->dom->saveXML();
198 }
199}
200
201/**
202 * this class represents a single leap2a entry.
203 * you can create these directly and then add them to the main leap feed object
204 */
205class portfolio_format_leap2a_entry {
206
207 /** entry id - something like forumpost6, must be unique to the feed **/
208 public $id;
209 /** title of the entry **/
210 public $title;
211 /** leap2a entry type **/
212 public $type;
213 /** optional author (only if different to feed author) **/
214 public $author;
215 /** summary - for split long content **/
216 public $summary;
ebb7e782 217 /** main content of the entry. can be html,text,or xhtml. for a stored_file, use portfolio_format_leap2a_file **/
59dd457e
PL
218 public $content;
219 /** updated date - unix timestamp */
220 public $updated;
221 /** published date (ctime) - unix timestamp */
222 public $published;
223
59dd457e
PL
224 /** the required fields for a leap2a entry */
225 private $requiredfields = array( 'id', 'title', 'type');
226
227 /** extra fields which usually should be set (except author) but are not required */
228 private $optionalfields = array('author', 'updated', 'published', 'content', 'summary');
229
230 /** links from this entry to other entries */
231 public $links = array();
232
233 /** attachments to this entry */
234 public $attachments = array();
235
236 /** categories for this entry */
237 private $categories = array();
238
239 /**
240 * constructor. All arguments are required (and will be validated)
241 * http://wiki.cetis.ac.uk/2009-03/LEAP2A_types
242 *
243 * @param string $id unique id of this entry.
244 * could be something like forumpost6 for example.
245 * This <b>must</b> be unique to the entire feed.
246 * @param string $title title of the entry. This is pure atom.
247 * @param string $type the leap type of this entry.
ebb7e782 248 * @param mixed $content the content of the entry. string (xhtml/html/text)
59dd457e
PL
249 */
250 public function __construct($id, $title, $type, $content=null) {
251 $this->id = $id;
252 $this->title = $title;
253 $this->type = $type;
254 $this->content = $this->__set('content', $content);
255
256 }
257
258 /**
259 * override __set to do proper dispatching for different things
260 * only allows the optional and required leap2a entry fields to be set
261 */
262 public function __set($field, $value) {
263 // detect the case where content is being set to be a file directly
264 if ($field == 'content' && $value instanceof stored_file) {
ebb7e782 265 throw new portfolio_format_leap2a_exception('leap2a_filecontent', 'portfolio');
59dd457e
PL
266 }
267 if (in_array($field, $this->requiredfields) || in_array($field, $this->optionalfields)) {
268 return $this->{$field} = $value;
269 }
8e642e1f 270 throw new portfolio_format_leap2a_exception('leap2a_invalidentryfield', 'portfolio', '', $field);
59dd457e
PL
271 }
272
59dd457e
PL
273
274 /**
275 * validate this entry.
276 * at the moment this just makes sure required fields exist
277 * but it could also check things against a list, for example
278 */
279 public function validate() {
280 foreach ($this->requiredfields as $key) {
281 if (empty($this->{$key})) {
8e642e1f 282 throw new portfolio_format_leap2a_exception('leap2a_missingfield', 'portfolio', '', $key);
59dd457e
PL
283 }
284 }
285 if ($this->type == 'selection') {
286 if (count($this->links) == 0) {
8e642e1f 287 throw new portfolio_format_leap2a_exception('leap2a_emptyselection', 'portfolio');
59dd457e
PL
288 }
289 //TODO make sure we have a category with a scheme 'selection_type'
290 }
291 }
292
293 /**
294 * add a link from this entry to another one
295 * these will be collated at the end of the export (during to_xml)
296 * and validated at that point. This function does no validation
297 * http://wiki.cetis.ac.uk/2009-03/LEAP2A_relationships
298 *
299 * @param mixed $otherentry portfolio_format_leap2a_entry or its id
ebb7e782 300 * @param string $reltype (no leap2: ns required)
59dd457e
PL
301 *
302 * @return the current entry object. This is so that these calls can be chained
303 * eg $entry->add_link('something6', 'has_part')->add_link('something7', 'has_part');
304 *
305 */
306 public function add_link($otherentry, $reltype, $displayorder=null) {
307 if ($otherentry instanceof portfolio_format_leap2a_entry) {
308 $otherentry = $otherentry->id;
309 }
310 if ($otherentry == $this->id) {
8e642e1f 311 throw new portfolio_format_leap2a_exception('leap2a_selflink', 'portfolio', '', (object)array('rel' => $reltype, 'id' => $this->id));
59dd457e 312 }
ebb7e782 313 // add on the leap2: ns if required
59dd457e 314 if (!in_array($reltype, array('related', 'alternate', 'enclosure'))) {
ebb7e782 315 $reltype = 'leap2:' . $reltype;
59dd457e
PL
316 }
317
318 $this->links[$otherentry] = (object)array('rel' => $reltype, 'order' => $displayorder);
319
320 return $this;
321 }
322
ed986e00 323 /**
59dd457e
PL
324 * add a category to this entry
325 * http://wiki.cetis.ac.uk/2009-03/LEAP2A_categories
326 *
327 * @param string $term eg 'Offline'
328 * @param string $scheme (optional) eg resource_type
329 * @param string $label (optional) eg File
330 *
331 * "tags" should just pass a term here and no scheme or label.
332 * they will be automatically normalised if they have spaces.
333 */
334 public function add_category($term, $scheme=null, $label=null) {
335 // "normalise" terms and set their label if they have spaces
336 // see http://wiki.cetis.ac.uk/2009-03/LEAP2A_categories#Plain_tags for more information
337 if (empty($scheme) && strpos($term, ' ') !== false) {
338 $label = $term;
339 $term = str_replace(' ', '-', $term);
340 }
341 $this->categories[] = (object)array(
342 'term' => $term,
343 'scheme' => $scheme,
344 'label' => $label,
345 );
346 }
347
348 /**
349 * Create an entry element and append all the children
350 * And return it rather than adding it to the dom.
351 * This is handled by the main writer object.
352 *
353 * @param DomDocument $dom use this to create elements
354 *
355 * @return DomElement
356 */
357 public function to_dom(DomDocument $dom, $feedauthor) {
358 $entry = $dom->createElement('entry');
359 $entry->appendChild($dom->createElement('id', $this->id));
360 $entry->appendChild($dom->createElement('title', $this->title));
361 if ($this->author && $this->author->id != $feedauthor->id) {
362 $author = $dom->createElement('author');
363 $author->appendChild($dom->createElement('name', fullname($this->author)));
364 $entry->appendChild($author);
365 }
366 // selectively add uncomplicated optional elements
367 foreach (array('updated', 'published') as $field) {
368 if ($this->{$field}) {
bce9a819
PL
369 $date = date(DATE_ATOM, $this->{$field});
370 $entry->appendChild($dom->createElement($field, $date));
59dd457e
PL
371 }
372 }
ebb7e782 373 if (empty($this->content)) {
59dd457e
PL
374 $entry->appendChild($dom->createElement('content'));
375 } else {
376 $content = $this->create_xhtmlish_element($dom, 'content', $this->content);
377 $entry->appendChild($content);
378 }
379
380 if (!empty($this->summary)) {
381 $summary = $this->create_xhtmlish_element($dom, 'summary', $this->summary);
382 $entry->appendChild($summary);
383 }
384
385 $type = $dom->createElement('rdf:type');
ebb7e782 386 $type->setAttribute('rdf:resource', 'leap2:' . $this->type);
59dd457e
PL
387 $entry->appendChild($type);
388
389 foreach ($this->links as $otherentry => $l) {
390 $link = $dom->createElement('link');
391 $link->setAttribute('rel', $l->rel);
491fff64 392 $link->setAttribute('href', 'portfolio:' . $otherentry);
59dd457e 393 if ($l->order) {
ebb7e782 394 $link->setAttribute('leap2:display_order', $l->order);
59dd457e
PL
395 }
396 $entry->appendChild($link);
397 }
ebb7e782
PL
398
399 $this->add_extra_links($dom, $entry); // hook for subclass
400
59dd457e
PL
401 foreach ($this->categories as $category) {
402 $cat = $dom->createElement('category');
403 $cat->setAttribute('term', $category->term);
404 if ($category->scheme) {
29fc57af 405 $cat->setAttribute('scheme', 'categories:' .$category->scheme . '#');
59dd457e
PL
406 }
407 if ($category->label && $category->label != $category->term) {
408 $cat->setAttribute('label', $category->label);
409 }
410 $entry->appendChild($cat);
411 }
412 return $entry;
413 }
414
415 /**
416 * try to load whatever is in $content into xhtml and add it to the dom.
417 * failing that, load the html, escape it, and set it as the body of the tag
418 * either way it sets the type attribute of the top level element
419 * moodle should always provide xhtml content, but user-defined content can't be trusted
420 *
421 * @param DomDocument $dom the dom doc to use
422 * @param string $tagname usually 'content' or 'summary'
423 * @param string $content the content to use, either xhtml or html.
424 *
425 * @return DomElement
426 */
427 private function create_xhtmlish_element(DomDocument $dom, $tagname, $content) {
428 $topel = $dom->createElement($tagname);
429 $maybexml = true;
430 if (strpos($content, '<') === false && strpos($content, '>') === false) {
431 $maybexml = false;
432 }
433 // try to load content as xml
434 $tmp = new DomDocument();
435 if ($maybexml && @$tmp->loadXML('<div>' . $content . '</div>')) {
436 $topel->setAttribute('type', 'xhtml');
437 $content = $dom->importNode($tmp->documentElement, true);
438 $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
439 $topel->appendChild($content);
440 // if that fails, it could still be html
441 } else if ($maybexml && @$tmp->loadHTML($content)) {
442 $topel->setAttribute('type', 'html');
443 $topel->nodeValue = $content;
444 // TODO figure out how to convert this to xml
445 // TODO because we end up with <html><body> </body></html> wrapped around it
446 // which is annoying
447 // either we already know it's text from the first check
448 // or nothing else has worked anyway
449 } else {
450 $topel->nodeValue = $content;
451 $topel->setAttribute('type', 'text');
452 return $topel;
453 }
454 return $topel;
455 }
ebb7e782
PL
456
457 /**
458 * hook function for subclasses to add extra links (like for files)
459 */
460 protected function add_extra_links() {}
461}
462
463
464/**
465 * subclass of entry, purely for dealing with files
466 */
467class portfolio_format_leap2a_file extends portfolio_format_leap2a_entry {
468
469 protected $referencedfile;
470
471 /**
472 * overridden constructor to set up the file.
473 *
474 */
475 public function __construct($title, stored_file $file) {
476 $id = portfolio_format_leap2a::file_id_prefix() . $file->get_id();
477 parent::__construct($id, $title, 'resource');
478 $this->referencedfile = $file;
479 $this->published = $this->referencedfile->get_timecreated();
480 $this->updated = $this->referencedfile->get_timemodified();
481 $this->add_category('offline', 'resource_type');
482 }
483
484 /**
485 * implement the hook to add extra links to attach the file in an enclosure
486 */
487 protected function add_extra_links($dom, $entry) {
488 $link = $dom->createElement('link');
489 $link->setAttribute('rel', 'enclosure');
490 $link->setAttribute('href', portfolio_format_leap2a::get_file_directory() . $this->referencedfile->get_filename());
491 $link->setAttribute('length', $this->referencedfile->get_filesize());
492 $link->setAttribute('type', $this->referencedfile->get_mimetype());
493 $entry->appendChild($link);
494 }
59dd457e 495}
ebb7e782 496