#1557: colouring ampersand breaks XML
[redakcja.git] / redakcja / static / js / wiki / wikiapi.js
1 (function($) {
2         $.wikiapi = {};
3         var noop = function() {
4         };
5         var noops = {
6                 success: noop,
7                 failure: noop
8         };
9         /*
10          * Return absolute reverse path of given named view. (at least he have it
11          * hard-coded in one place)
12          *
13          * TODO: think of a way, not to hard-code it here ;)
14          *
15          */
16         function reverse() {
17                 var vname = arguments[0];
18                 var base_path = "/documents";
19
20                 if (vname == "ajax_document_text") {
21                         var path = "/" + arguments[1] + "/text";
22
23                 if (arguments[2] !== undefined)
24                                 path += "/" + arguments[2];
25
26                         return base_path + path;
27                 }
28
29         if (vname == "ajax_document_revert") {
30             return base_path + "/" + arguments[1] + "/revert";
31         }
32
33
34                 if (vname == "ajax_document_history") {
35
36                         return base_path + "/" + arguments[1] + "/history";
37                 }
38
39                 if (vname == "ajax_document_gallery") {
40
41                         return base_path + "/" + arguments[1] + "/gallery";
42                 }
43
44                 if (vname == "ajax_document_diff")
45                         return base_path + "/" + arguments[1] + "/diff";
46
47         if (vname == "ajax_document_rev")
48             return base_path + "/" + arguments[1] + "/rev";
49
50                 if (vname == "ajax_document_addtag")
51                         return base_path + "/" + arguments[1] + "/tags";
52
53                 if (vname == "ajax_publish")
54                         return base_path + "/" + arguments[1] + "/publish";
55
56                 console.log("Couldn't reverse match:", vname);
57                 return "/404.html";
58         };
59
60         /*
61          * Document Abstraction
62          */
63         function WikiDocument(element_id) {
64                 var meta = $('#' + element_id);
65                 this.id = meta.attr('data-document-name');
66
67                 this.revision = $("*[data-key='revision']", meta).text();
68                 this.readonly = !!$("*[data-key='readonly']", meta).text();
69
70                 this.galleryLink = $("*[data-key='gallery']", meta).text();
71                 this.galleryImages = [];
72                 this.text = null;
73                 this.has_local_changes = false;
74                 this._lock = -1;
75                 this._context_lock = -1;
76                 this._lock_count = 0;
77         };
78
79         WikiDocument.prototype.triggerDocumentChanged = function() {
80                 $(document).trigger('wlapi_document_changed', this);
81         };
82         /*
83          * Fetch text of this document.
84          */
85         WikiDocument.prototype.fetch = function(params) {
86                 params = $.extend({}, noops, params);
87                 var self = this;
88                 $.ajax({
89                         method: "GET",
90                         url: reverse("ajax_document_text", self.id),
91                         data: {"revision": self.revision},
92                         dataType: 'json',
93                         success: function(data) {
94                                 var changed = false;
95
96                                 if (self.text === null || self.revision !== data.revision) {
97                                         self.text = data.text;
98                                         self.revision = data.revision;
99                                         self.gallery = data.gallery;
100                                         changed = true;
101                                         self.triggerDocumentChanged();
102                                 };
103
104                                 self.has_local_changes = false;
105                                 params['success'](self, changed);
106                         },
107                         error: function() {
108                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
109                         }
110                 });
111         };
112         /*
113          * Fetch history of this document.
114          *
115          * from - First revision to fetch (default = 0) upto - Last revision to
116          * fetch (default = tip)
117          *
118          */
119         WikiDocument.prototype.fetchHistory = function(params) {
120                 /* this doesn't modify anything, so no locks */
121                 params = $.extend({}, noops, params);
122                 var self = this;
123                 $.ajax({
124                         method: "GET",
125                         url: reverse("ajax_document_history", self.id),
126                         dataType: 'json',
127                         data: {
128                                 "from": params['from'],
129                                 "upto": params['upto']
130                         },
131                         success: function(data) {
132                                 params['success'](self, data);
133                         },
134                         error: function() {
135                                 params['failure'](self, "Nie udało się wczytać historii dokumentu.");
136                         }
137                 });
138         };
139         WikiDocument.prototype.fetchDiff = function(params) {
140                 /* this doesn't modify anything, so no locks */
141                 var self = this;
142                 params = $.extend({
143                         'from': self.revision,
144                         'to': self.revision
145                 }, noops, params);
146                 $.ajax({
147                         method: "GET",
148                         url: reverse("ajax_document_diff", self.id),
149                         dataType: 'html',
150                         data: {
151                                 "from": params['from'],
152                                 "to": params['to']
153                         },
154                         success: function(data) {
155                                 params['success'](self, data);
156                         },
157                         error: function() {
158                                 params['failure'](self, "Nie udało się wczytać porównania wersji.");
159                         }
160                 });
161         };
162
163     WikiDocument.prototype.checkRevision = function(params) {
164         /* this doesn't modify anything, so no locks */
165         var self = this;
166         $.ajax({
167             method: "GET",
168             url: reverse("ajax_document_rev", self.id),
169             dataType: 'text',
170             success: function(data) {
171                 if (data == '') {
172                     if (params.error)
173                         params.error();
174                 }
175                 else if (data != self.revision)
176                     params.outdated();
177             }
178         });
179     };
180
181         /*
182          * Fetch gallery
183          */
184         WikiDocument.prototype.refreshGallery = function(params) {
185                 params = $.extend({}, noops, params);
186                 var self = this;
187                 $.ajax({
188                         method: "GET",
189                         url: reverse("ajax_document_gallery", self.galleryLink),
190                         dataType: 'json',
191                         // data: {},
192                         success: function(data) {
193                                 self.galleryImages = data;
194                                 params['success'](self, data);
195                         },
196                         error: function() {
197                                 self.galleryImages = [];
198                                 params['failure'](self, "<p>Nie udało się wczytać galerii pod nazwą: '" + self.galleryLink + "'.</p>");
199                         }
200                 });
201         };
202
203         /*
204          * Set document's text
205          */
206         WikiDocument.prototype.setText = function(text) {
207                 this.text = text;
208                 this.has_local_changes = true;
209         };
210
211         /*
212          * Set document's gallery link
213          */
214         WikiDocument.prototype.setGalleryLink = function(gallery) {
215                 this.galleryLink = gallery;
216                 this.has_local_changes = true;
217         };
218
219         /*
220          * Save text back to the server
221          */
222         WikiDocument.prototype.save = function(params) {
223                 params = $.extend({}, noops, params);
224                 var self = this;
225
226                 if (!self.has_local_changes) {
227                         console.log("Abort: no changes.");
228                         return params['success'](self, false, "Nie ma zmian do zapisania.");
229                 };
230
231                 // Serialize form to dictionary
232                 var data = {};
233                 $.each(params['form'].serializeArray(), function() {
234                         data[this.name] = this.value;
235                 });
236
237                 var metaComment = '<!--';
238                 metaComment += '\n\tgallery:' + self.galleryLink;
239                 metaComment += '\n-->\n'
240
241                 data['textsave-text'] = metaComment + self.text;
242
243                 $.ajax({
244                         url: reverse("ajax_document_text", self.id),
245                         type: "POST",
246                         dataType: "json",
247                         data: data,
248                         success: function(data) {
249                                 var changed = false;
250
251                 $('#header').removeClass('saving');
252
253                                 if (data.text) {
254                                         self.text = data.text;
255                                         self.revision = data.revision;
256                                         self.gallery = data.gallery;
257                                         changed = true;
258                                         self.triggerDocumentChanged();
259                                 };
260
261                                 params['success'](self, changed, ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna"));
262                         },
263                         error: function(xhr) {
264                 if ($('#header').hasClass('saving')) {
265                     $('#header').removeClass('saving');
266                     $.blockUI({
267                         message: "<p>Nie udało się zapisać zmian. <br/><button onclick='$.unblockUI()'>OK</button></p>"
268                     })
269                 }
270                 else {
271                     try {
272                         params['failure'](self, $.parseJSON(xhr.responseText));
273                     }
274                     catch (e) {
275                         params['failure'](self, {
276                             "__message": "<p>Nie udało się zapisać - błąd serwera.</p>"
277                         });
278                     };
279                 }
280
281                         }
282                 });
283
284         $('#save-hide').click(function(){
285             $('#header').addClass('saving');
286             $.unblockUI();
287             $.wiki.blocking.unblock();
288         });
289         }; /* end of save() */
290
291     WikiDocument.prototype.revertToVersion = function(params) {
292         var self = this;
293         params = $.extend({}, noops, params);
294
295         if (params.revision >= this.revision) {
296             params.failure(self, 'Proszę wybrać rewizję starszą niż aktualna.');
297             return;
298         }
299
300         // Serialize form to dictionary
301         var data = {};
302         $.each(params['form'].serializeArray(), function() {
303             data[this.name] = this.value;
304         });
305
306         $.ajax({
307             url: reverse("ajax_document_revert", self.id),
308             type: "POST",
309             dataType: "json",
310             data: data,
311             success: function(data) {
312                 if (data.text) {
313                     self.text = data.text;
314                     self.revision = data.revision;
315                     self.gallery = data.gallery;
316                     self.triggerDocumentChanged();
317
318                     params.success(self, "Udało się przywrócić wersję :)");
319                 }
320                 else {
321                     params.failure(self, "Przywracana wersja identyczna z aktualną. Anulowano przywracanie.");
322                 }
323             },
324             error: function(xhr) {
325                 params.failure(self, "Nie udało się przywrócić wersji - błąd serwera.");
326             }
327         });
328     };
329
330         WikiDocument.prototype.publish = function(params) {
331                 params = $.extend({}, noops, params);
332                 var self = this;
333                 $.ajax({
334                         url: reverse("ajax_publish", self.id),
335                         type: "POST",
336                         dataType: "json",
337                         success: function(data) {
338                                 params.success(self, data);
339                         },
340                         error: function(xhr) {
341                                 if (xhr.status == 403 || xhr.status == 401) {
342                                         params.failure(self, "Nie masz uprawnień lub nie jesteś zalogowany.");
343                                 }
344                                 else {
345                                         try {
346                                                 params.failure(self, xhr.responseText);
347                                         }
348                                         catch (e) {
349                                                 params.failure(self, "Nie udało się - błąd serwera.");
350                                         };
351                                 };
352
353                         }
354                 });
355         };
356         WikiDocument.prototype.setTag = function(params) {
357                 params = $.extend({}, noops, params);
358                 var self = this;
359                 var data = {
360                         "addtag-id": self.id,
361                 };
362
363                 /* unpack form */
364                 $.each(params.form.serializeArray(), function() {
365                         data[this.name] = this.value;
366                 });
367
368                 $.ajax({
369                         url: reverse("ajax_document_addtag", self.id),
370                         type: "POST",
371                         dataType: "json",
372                         data: data,
373                         success: function(data) {
374                                 params.success(self, data.message);
375                         },
376                         error: function(xhr) {
377                                 if (xhr.status == 403 || xhr.status == 401) {
378                                         params.failure(self, {
379                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
380                                         });
381                                 }
382                                 else {
383                                         try {
384                                                 params.failure(self, $.parseJSON(xhr.responseText));
385                                         }
386                                         catch (e) {
387                                                 params.failure(self, {
388                                                         "__all__": ["Nie udało się - błąd serwera."]
389                                                 });
390                                         };
391                                 };
392                         }
393                 });
394         };
395
396     WikiDocument.prototype.getLength = function(params) {
397         var xml = this.text.replace(/\/(\s+)/g, '<br />$1');
398         var parser = new DOMParser();
399         var doc = parser.parseFromString(xml, 'text/xml');
400         var error = $('parsererror', doc);
401
402         if (error.length > 0) {
403             throw "Not an XML document.";
404         }
405         $.xmlns["rdf"] = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; 
406         $('rdf|RDF, motyw, pa, pe, pr, pt', doc).remove();
407         var text = $(doc).text();
408         text = $.trim(text.replace(/\s{2,}/g, ' '));
409         return text.length;
410     }
411
412
413         $.wikiapi.WikiDocument = WikiDocument;
414 })(jQuery);