framework now supports displaying the results of queries
[myslice.git] / manifold / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
21 Object.toType = (function toType(global) {
22   return function(obj) {
23     if (obj === global) {
24       return "global";
25     }
26     return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
27   }
28 })(this);
29
30 /* ------------------------------------------------------------ */
31
32 // Constants that should be somehow moved to a plugin.js file
33 var FILTER_ADDED   = 1;
34 var FILTER_REMOVED = 2;
35 var CLEAR_FILTERS  = 3;
36 var FIELD_ADDED    = 4;
37 var FIELD_REMOVED  = 5;
38 var CLEAR_FIELDS   = 6;
39 var NEW_RECORD     = 7;
40 var CLEAR_RECORDS  = 8;
41 var FIELD_STATE_CHANGED = 9;
42
43 var IN_PROGRESS    = 101;
44 var DONE           = 102;
45
46 /* Update requests related to subqueries */
47 var SET_ADD        = 201;
48 var SET_REMOVED    = 202;
49
50 // request
51 var FIELD_REQUEST_CHANGE  = 301;
52 var FIELD_REQUEST_ADD     = 302;
53 var FIELD_REQUEST_REMOVE  = 303;
54 var FIELD_REQUEST_RESET   = 304;
55 // status
56 var FIELD_REQUEST_PENDING = 401;
57 var FIELD_REQUEST_SUCCESS = 402;
58 var FIELD_REQUEST_FAILURE = 403;
59
60 /* Query status */
61 var STATUS_NONE               = 500; // Query has not been started yet
62 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
63 var STATUS_GET_RECEIVED       = 502; // Success
64 var STATUS_GET_ERROR          = 503; // Error
65 var STATUS_UPDATE_PENDING     = 504;
66 var STATUS_UPDATE_IN_PROGRESS = 505;
67 var STATUS_UPDATE_RECEIVED    = 506;
68 var STATUS_UPDATE_ERROR       = 507;
69
70 /* Requests for query cycle */
71 var RUN_UPDATE     = 601;
72
73 /* MANIFOLD types */
74 var TYPE_VALUE  = 1;
75 var TYPE_RECORD = 2;
76 var TYPE_LIST_OF_VALUES = 3;
77 var TYPE_LIST_OF_RECORDS = 4;
78
79
80 // A structure for storing queries
81
82 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
83
84     /* Constructor */
85     if (typeof query == "undefined")
86         throw "Must pass a query in QueryExt constructor";
87     this.query                 = query;
88     this.parent_query_ext      = (typeof parent_query_ext      == "undefined") ? null  : parent_query_ext;
89     this.main_query_ext        = (typeof main_query_ext        == "undefined") ? null  : main_query_ext;
90     this.update_query_ext      = (typeof update_query_ext      == "undefined") ? null  : update_query_ext;
91     this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null  : update_query_orig_ext;
92     this.disabled              = (typeof update_query_ext      == "undefined") ? false : disabled;
93     
94     this.status       = null;
95     this.results      = null;
96     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
97 }
98
99 function QueryStore() {
100
101     this.main_queries     = {};
102     this.analyzed_queries = {};
103
104     /* Insertion */
105
106     this.insert = function(query)
107     {
108         // We expect only main_queries are inserted
109
110         /* If the query has not been analyzed, then we analyze it */
111         if (query.analyzed_query == null) {
112             query.analyze_subqueries();
113         }
114
115         /* We prepare the update query corresponding to the main query and store both */
116         /* Note: they have the same UUID */
117
118         // XXX query.change_action() should become deprecated
119         update_query = query.clone();
120         update_query.action = 'update';
121         update_query.analyzed_query.action = 'update';
122         update_query.params = {};
123         update_query_ext = new QueryExt(update_query);
124
125         /* We remember the original query to be able to reset it */
126         update_query_orig_ext = new QueryExt(update_query.clone());
127
128
129         /* We store the main query */
130         query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
131         manifold.query_store.main_queries[query.query_uuid] = query_ext;
132         /* Note: the update query does not have an entry! */
133
134
135         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
136         // XXX unless we have no subqueries ???
137         // we will complete with params when records are received... this has to be done by the manager
138         // SET_ADD, SET_REMOVE will change the status of the elements of the set
139         // UPDATE will change also, etc.
140         // XXX We need a proper structure to store this information...
141
142         // We also need to insert all queries and subqueries from the analyzed_query
143         // XXX We need the root of all subqueries
144         query.iter_subqueries(function(sq, data, parent_query) {
145             if (parent_query)
146                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
147             else
148                 parent_query_ext = null;
149             // XXX parent_query_ext == false
150             // XXX main.subqueries = {} # Normal, we need analyzed_query
151             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
152             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
153         });
154
155         // XXX We have spurious update queries...
156     }
157
158     /* Searching */
159
160     this.find_query_ext = function(query_uuid)
161     {
162         return this.main_queries[query_uuid];
163     }
164
165     this.find_query = function(query_uuid)
166     {
167         return this.find_query_ext(query_uuid).query;
168     }
169
170     this.find_analyzed_query_ext = function(query_uuid)
171     {
172         return this.analyzed_queries[query_uuid];
173     }
174
175     this.find_analyzed_query = function(query_uuid)
176     {
177         return this.find_analyzed_query_ext(query_uuid).query;
178     }
179 }
180
181 /*!
182  * This namespace holds functions for globally managing query objects
183  * \Class Manifold
184  */
185 var manifold = {
186
187     /************************************************************************** 
188      * Helper functions
189      **************************************************************************/ 
190
191     separator: '__',
192
193     spin_presets: {},
194
195     spin: function(locator, active /*= true */) {
196         active = typeof active !== 'undefined' ? active : true;
197         try {
198             if (active) {
199                 $(locator).spin(manifold.spin_presets);
200             } else {
201                 $(locator).spin(false);
202             }
203         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
204     },
205
206     get_type: function(variable)
207     {
208         switch(Object.toType(variable)) {
209             case 'number':
210             case 'string':
211                 return TYPE_VALUE;
212             case 'object':
213                 return TYPE_RECORD;
214             case 'array':
215                 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
216                     return TYPE_LIST_OF_RECORDS;
217                 else
218                     return TYPE_LIST_OF_VALUES;
219         }
220     },
221
222     /************************************************************************** 
223      * Metadata management
224      **************************************************************************/ 
225
226      metadata: {
227
228         get_table: function(method)
229         {
230             var table = MANIFOLD_METADATA[method];
231             return (typeof table === 'undefined') ? null : table;
232         },
233
234         get_columns: function(method)
235         {
236             var table = this.get_table(method);
237             if (!table) {
238                 return null;
239             }
240
241             return (typeof table.column === 'undefined') ? null : table.column;
242         },
243
244         get_key: function(method)
245         {
246             var table = this.get_table(method);
247             if (!table)
248                 return null;
249
250             return (typeof table.key === 'undefined') ? null : table.key;
251         },
252
253
254         get_column: function(method, name)
255         {
256             var columns = this.get_columns(method);
257             if (!columns)
258                 return null;
259
260             $.each(columns, function(i, c) {
261                 if (c.name == name)
262                     return c
263             });
264             return null;
265         },
266
267         get_type: function(method, name)
268         {
269             var table = this.get_table(method);
270             if (!table)
271                 return null;
272
273             return (typeof table.type === 'undefined') ? null : table.type;
274         }
275
276      },
277
278     /************************************************************************** 
279      * Query management
280      **************************************************************************/ 
281
282     query_store: new QueryStore(),
283
284     // XXX Remaining functions are deprecated since they are replaced by the query store
285
286     /*!
287      * Associative array storing the set of queries active on the page
288      * \memberof Manifold
289      */
290     all_queries: {},
291
292     /*!
293      * Insert a query in the global hash table associating uuids to queries.
294      * If the query has no been analyzed yet, let's do it.
295      * \fn insert_query(query)
296      * \memberof Manifold
297      * \param ManifoldQuery query Query to be added
298      */
299     insert_query : function (query) { 
300         // NEW API
301         manifold.query_store.insert(query);
302
303         // FORMER API
304         if (query.analyzed_query == null) {
305             query.analyze_subqueries();
306         }
307         manifold.all_queries[query.query_uuid]=query;
308     },
309
310     /*!
311      * Returns the query associated to a UUID
312      * \fn find_query(query_uuid)
313      * \memberof Manifold
314      * \param string query_uuid The UUID of the query to be returned
315      */
316     find_query : function (query_uuid) { 
317         return manifold.all_queries[query_uuid];
318     },
319
320     /************************************************************************** 
321      * Query execution
322      **************************************************************************/ 
323
324     // trigger a query asynchroneously
325     proxy_url : '/manifold/proxy/json/',
326
327     asynchroneous_debug : true,
328
329     /**
330      * \brief We use js function closure to be able to pass the query (array)
331      * to the callback function used when data is received
332      */
333     success_closure: function(query, publish_uuid, callback /*domid*/)
334     {
335         return function(data, textStatus) {
336             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
337         }
338     },
339
340     run_query: function(query, callback)
341     {
342         // default value for callback = null
343         if (typeof callback === 'undefined')
344             callback = null; 
345
346         var query_json = JSON.stringify(query);
347
348         /* Nothing related to pubsub here... for the moment at least. */
349         //query.iter_subqueries(function (sq) {
350         //    manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
351         //});
352
353         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback /*domid*/));
354     },
355
356     // Executes all async. queries
357     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
358     asynchroneous_exec : function (query_publish_dom_tuples) {
359         // start spinners
360
361         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
362         //try {
363         //    if (manifold.asynchroneous_debug) 
364         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
365         //    jQuery('.need-spin').spin(manifold.spin_presets);
366         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
367         
368         // Loop through input array, and use publish_uuid to publish back results
369         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
370             var query=manifold.find_query(tuple.query_uuid);
371             var query_json=JSON.stringify (query);
372             var publish_uuid=tuple.publish_uuid;
373             // by default we publish using the same uuid of course
374             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
375             if (manifold.asynchroneous_debug) {
376                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
377                 messages.debug("... ctd... with actual query= " + query.__repr());
378             }
379
380             query.iter_subqueries(function (sq) {
381                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
382             });
383
384             // not quite sure what happens if we send a string directly, as POST data is named..
385             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
386                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
387         })
388     },
389
390     /**
391      * \brief Forward a query to the manifold backend
392      * \param query (dict) the query to be executed asynchronously
393      * \param callback (function) the function to be called when the query terminates
394      * Deprecated:
395      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
396      */
397     forward: function(query, callback /*domid*/) {
398         var query_json = JSON.stringify(query);
399         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
400     },
401
402     /*!
403      * Returns whether a query expects a unique results.
404      * This is the case when the filters contain a key of the object
405      * \fn query_expects_unique_result(query)
406      * \memberof Manifold
407      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
408      */
409     query_expects_unique_result: function(query) {
410         /* XXX we need functions to query metadata */
411         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
412         /* TODO requires keys in metadata */
413         return true;
414     },
415
416     /*!
417      * Publish result
418      * \fn publish_result(query, results)
419      * \memberof Manifold
420      * \param ManifoldQuery query Query which has received results
421      * \param array results results corresponding to query
422      */
423     publish_result: function(query, result) {
424         if (typeof result === 'undefined')
425             result = [];
426
427         // NEW PLUGIN API
428         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
429         $.each(result, function(i, record) {
430             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
431         });
432         manifold.raise_record_event(query.query_uuid, DONE);
433
434         // OLD PLUGIN API BELOW
435         /* Publish an update announce */
436         var channel="/results/" + query.query_uuid + "/changed";
437         if (manifold.asynchroneous_debug)
438             messages.debug("publishing result on " + channel);
439         jQuery.publish(channel, [result, query]);
440     },
441
442     /*!
443      * Recursively publish result
444      * \fn publish_result_rec(query, result)
445      * \memberof Manifold
446      * \param ManifoldQuery query Query which has received result
447      * \param array result result corresponding to query
448      */
449     publish_result_rec: function(query, result) {
450         /* If the result is not unique, only publish the top query;
451          * otherwise, publish the main object as well as subqueries
452          * XXX how much recursive are we ?
453          */
454         if (manifold.query_expects_unique_result(query)) {
455             /* Also publish subqueries */
456             jQuery.each(query.subqueries, function(object, subquery) {
457                 manifold.publish_result_rec(subquery, result[0][object]);
458                 /* TODO remove object from result */
459             });
460         }
461         manifold.publish_result(query, result);
462     },
463
464     process_get_query_records: function(query, records)
465     {
466         /* This consists in managing the update query */
467
468         // We don't prepare an update query if the result has more than 1 entry
469         if (records.length == 1) {
470             var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
471
472             var record = records[0];
473
474             var update_query_ext = query_ext.update_query_ext;
475             var update_query = update_query_ext.query;
476             var update_query_ext = query_ext.update_query_ext;
477             var update_query_orig = query_ext.update_query_orig_ext.query;
478
479             // Testing whether the result has subqueries (one level deep only)
480             // iif the query has subqueries
481             var count = 0;
482             var obj = query.analyzed_query.subqueries;
483             for (method in obj) {
484                 if (obj.hasOwnProperty(method)) {
485                     var key = manifold.metadata.get_key(method);
486                     if (!key)
487                         continue;
488                     if (key.length > 1)
489                         continue;
490                     key = key[0];
491                     var sq_keys = [];
492                     var subrecords = record[method];
493                     if (!subrecords)
494                         continue
495                     $.each(subrecords, function (i, subrecord) {
496                         sq_keys.push(subrecord[key]);
497                     });
498                     update_query.params[method] = sq_keys;
499                     update_query_orig.params[method] = sq_keys.slice();
500                     count++;
501                 }
502             }
503
504             if (count > 0) {
505                 update_query_ext.disabled = false;
506                 update_query_orig_ext.disabled = false;
507             }
508         }
509
510         /* Publish results */
511         // NOTE: this is redundant only for Get queries
512         tmp_query = manifold.find_query(query.query_uuid);
513         manifold.publish_result_rec(tmp_query.analyzed_query, records);
514     },
515
516     /**
517      * 
518      * What we need to do when receiving results from an update query:
519      * - differences between what we had, what we requested, and what we obtained
520      *    . what we had : update_query_orig (simple fields and set fields managed differently)
521      *    . what we requested : update_query
522      *    . what we received : records
523      * - raise appropriate events
524      *
525      * The normal process is that results similar to Get will be pushed in the
526      * pubsub mechanism, thus repopulating everything while we only need
527      * diff's. This means we need to move the publish functionalities in the
528      * previous 'process_get_query_records' function.
529      */
530     process_update_query_records: function(query, records)
531     {
532         // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
533         var query_uuid        = query.query_uuid;
534         var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
535         var update_query      = query_ext.main_query_ext.update_query_ext.query;
536         var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
537         
538         // Since we update objects one at a time, we can get the first record
539         var record = records[0];
540
541         // Let's iterate over the object properties
542         for (var field in record) {
543             switch (this.get_type(record[field])) {
544                 case TYPE_VALUE:
545                     // Did we ask for a change ?
546                     var update_value = update_query[field];
547                     if (!update_value)
548                         // Not requested, if it has changed: OUT OF SYNC
549                         // How we can know ?
550                         // We assume it won't have changed
551                         continue;
552
553                     var result_value = record[field];
554                     if (!result_value)
555                         throw "Internal error";
556
557                     data = {
558                         request: FIELD_REQUEST_CHANGE,
559                         key   : field,
560                         value : update_value,
561                         status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
562                     }
563                     manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
564
565                     break;
566                 case TYPE_RECORD:
567                     throw "Not implemented";
568                     break;
569
570                 case TYPE_LIST_OF_VALUES:
571                     // Same as list of records, but we don't have to extract keys
572                     var result_keys  = record[field]
573                     
574                     // The rest of exactly the same (XXX factorize)
575                     var update_keys  = update_query_orig.params[field];
576                     var query_keys   = update_query.params[field];
577                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
578                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
579
580
581                     $.each(added_keys, function(i, key) {
582                         if ($.inArray(key, result_keys) == -1) {
583                             data = {
584                                 request: FIELD_REQUEST_ADD,
585                                 key   : field,
586                                 value : key,
587                                 status: FIELD_REQUEST_FAILURE,
588                             }
589                         } else {
590                             data = {
591                                 request: FIELD_REQUEST_ADD,
592                                 key   : field,
593                                 value : key,
594                                 status: FIELD_REQUEST_SUCCESS,
595                             }
596                         }
597                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
598                     });
599                     $.each(removed_keys, function(i, key) {
600                         if ($.inArray(key, result_keys) == -1) {
601                             data = {
602                                 request: FIELD_REQUEST_REMOVE,
603                                 key   : field,
604                                 value : key,
605                                 status: FIELD_REQUEST_SUCCESS,
606                             }
607                         } else {
608                             data = {
609                                 request: FIELD_REQUEST_REMOVE,
610                                 key   : field,
611                                 value : key,
612                                 status: FIELD_REQUEST_FAILURE,
613                             }
614                         }
615                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
616                     });
617
618
619                     break;
620                 case TYPE_LIST_OF_RECORDS:
621                     // example: slice.resource
622                     //  - update_query_orig.params.resource = resources in slice before update
623                     //  - update_query.params.resource = resource requested in slice
624                     //  - keys from field = resources obtained
625                     var key = manifold.metadata.get_key(field);
626                     if (!key)
627                         continue;
628                     if (key.length > 1) {
629                         throw "Not implemented";
630                         continue;
631                     }
632                     key = key[0];
633
634                     /* XXX should be modified for multiple keys */
635                     var result_keys  = $.map(record[field], function(x) { return x[key]; });
636
637                     var update_keys  = update_query_orig.params[field];
638                     var query_keys   = update_query.params[field];
639                     var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
640                     var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
641
642
643                     $.each(added_keys, function(i, key) {
644                         if ($.inArray(key, result_keys) == -1) {
645                             data = {
646                                 request: FIELD_REQUEST_ADD,
647                                 key   : field,
648                                 value : key,
649                                 status: FIELD_REQUEST_FAILURE,
650                             }
651                         } else {
652                             data = {
653                                 request: FIELD_REQUEST_ADD,
654                                 key   : field,
655                                 value : key,
656                                 status: FIELD_REQUEST_SUCCESS,
657                             }
658                         }
659                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
660                     });
661                     $.each(removed_keys, function(i, key) {
662                         if ($.inArray(key, result_keys) == -1) {
663                             data = {
664                                 request: FIELD_REQUEST_REMOVE,
665                                 key   : field,
666                                 value : key,
667                                 status: FIELD_REQUEST_SUCCESS,
668                             }
669                         } else {
670                             data = {
671                                 request: FIELD_REQUEST_REMOVE,
672                                 key   : field,
673                                 value : key,
674                                 status: FIELD_REQUEST_FAILURE,
675                             }
676                         }
677                         manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
678                     });
679
680
681                     break;
682             }
683         }
684     },
685
686     process_query_records: function(query, records)
687     {
688         if (query.action == 'get') {
689             this.process_get_query_records(query, records);
690         } else if (query.action == 'update') {
691             this.process_update_query_records(query, records);
692         }
693     },
694
695     // if set domid allows the result to be directed to just one plugin
696     // most of the time publish_uuid will be query.query_uuid
697     // however in some cases we wish to publish the result under a different uuid
698     // e.g. an updater wants to publish its result as if from the original (get) query
699     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
700         // xxx should have a nicer declaration of that enum in sync with the python code somehow
701
702         /* If a callback has been specified, we redirect results to it */
703         if (!!callback) { callback(data); return; }
704
705         if (data.code == 2) { // ERROR
706             // We need to make sense of error codes here
707             alert("Your session has expired, please log in again");
708             window.location="/logout/";
709             return;
710         }
711         if (data.code == 1) { // WARNING
712             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
713             // publish error code and text message on a separate channel for whoever is interested
714             if (publish_uuid)
715                 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
716
717             $("#notifications").notify("create", "sticky", {
718               title: 'Warning',
719               text: data.description
720             },{
721               expires: false,
722               speed: 1000
723             });
724             
725         }
726         // once everything is checked we can use the 'value' part of the manifoldresult
727         var result=data.value;
728         if (result) {
729             /* Eventually update the content of related queries (update, etc) */
730             this.process_query_records(query, result);
731
732             /* Publish results: disabled here, done in the previous call */
733             //tmp_query = manifold.find_query(query.query_uuid);
734             //manifold.publish_result_rec(tmp_query.analyzed_query, result);
735         }
736     },
737
738     /************************************************************************** 
739      * Plugin API helpers
740      **************************************************************************/ 
741
742     raise_event_handler: function(type, query_uuid, event_type, value)
743     {
744         if ((type != 'query') && (type != 'record'))
745             throw 'Incorrect type for manifold.raise_event()';
746
747         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
748
749         $.each(channels, function(i, channel) {
750             if (value === undefined)
751                 $('.plugin').trigger(channel, [event_type]);
752             else
753                 $('.plugin').trigger(channel, [event_type, value]);
754         });
755     },
756
757     raise_query_event: function(query_uuid, event_type, value)
758     {
759         manifold.raise_event_handler('query', query_uuid, event_type, value);
760     },
761
762     raise_record_event: function(query_uuid, event_type, value)
763     {
764         manifold.raise_event_handler('record', query_uuid, event_type, value);
765     },
766
767
768     raise_event: function(query_uuid, event_type, value)
769     {
770         // Query uuid has been updated with the key of a new element
771         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
772         query = query_ext.query;
773
774         switch(event_type) {
775             case FIELD_STATE_CHANGED:
776                 // value is an object (request, key, value, status)
777                 // update is only possible is the query is not pending, etc
778                 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
779                 // we should map SET_ADD on this...
780
781                 // 1. Update internal query store about the change in status
782
783                 // 2. Update the update query
784                 update_query      = query_ext.main_query_ext.update_query_ext.query;
785                 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
786
787                 switch(value.request) {
788                     case FIELD_REQUEST_CHANGE:
789                         update_query.params[value.key] = value.value;
790                         break;
791                     case FIELD_REQUEST_ADD:
792                         if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
793                             value.request = FIELD_REQUEST_RESET;
794                         update_query.params[value.key].push(value.value);
795                         break;
796                     case FIELD_REQUEST_REMOVE:
797                         if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
798                             value.request = FIELD_REQUEST_RESET;
799
800                         var arr = update_query.params[value.key];
801                         arr = $.grep(arr, function(x) { return x != value.value; });
802                         update_query.params[value.key] = arr;
803
804                         break;
805                     case FIELD_REQUEST_RESET:
806                         // XXX We would need to keep track of the original query
807                         throw "Not implemented";
808                         break;
809                 }
810
811                 // 3. Inform others about the change
812                 // a) the main query...
813                 manifold.raise_record_event(query_uuid, event_type, value);
814
815                 // b) subqueries eventually (dot in the key)
816                 // XXX make this DOT a global variable... could be '/'
817                 break;
818
819             case SET_ADD:
820             case SET_REMOVED:
821     
822                 // update is only possible is the query is not pending, etc
823                 // CHECK status !
824
825                 // XXX we can only update subqueries of the main query. Check !
826                 // assert query_ext.parent_query == query_ext.main_query
827                 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
828
829                 // This SET_ADD is called on a subquery, so we have to
830                 // recontruct the path of the key in the main_query
831                 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
832
833                 var path = "";
834                 var sq = query_ext;
835                 while (sq.parent_query_ext) {
836                     if (path != "")
837                         path = '.' + path;
838                     path = sq.query.object + path;
839                     sq = sq.parent_query_ext;
840                 }
841
842                 main_query = query_ext.main_query_ext.query;
843                 data = {
844                     request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
845                     key   : path,
846                     value : value,
847                     status: FIELD_REQUEST_PENDING,
848                 };
849                 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
850
851                 // old //update_query.params[path].push(value);
852                 // old // console.log('Updated query params', update_query);
853                 // NOTE: update might modify the fields in Get
854                 // NOTE : we have to modify all child queries
855                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
856
857                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
858                 // object = the same as get
859                 // filter = key : update a single object for now
860                 // fields = the same as get
861                 manifold.raise_query_event(query_uuid, event_type, value);
862
863                 break;
864
865             case RUN_UPDATE:
866                 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
867                 break;
868
869             case FILTER_ADDED:
870                 manifold.raise_query_event(query_uuid, event_type, value);
871                 break;
872             case FILTER_REMOVED:
873                 manifold.raise_query_event(query_uuid, event_type, value);
874                 break;
875             case FIELD_ADDED:
876                 main_query = query_ext.main_query_ext.query;
877                 main_update_query = query_ext.main_query_ext.update_query;
878                 query.select(value);
879
880                 // Here we need the full path through all subqueries
881                 path = ""
882                 // XXX We might need the query name in the QueryExt structure
883                 main_query.select(value);
884
885                 // XXX When is an update query associated ?
886                 // XXX main_update_query.select(value);
887
888                 manifold.raise_query_event(query_uuid, event_type, value);
889                 break;
890
891             case FIELD_REMOVED:
892                 query = query_ext.query;
893                 main_query = query_ext.main_query_ext.query;
894                 main_update_query = query_ext.main_query_ext.update_query;
895                 query.unselect(value);
896                 main_query.unselect(value);
897
898                 // We need to inform about changes in these queries to the respective plugins
899                 // Note: query & main_query have the same UUID
900                 manifold.raise_query_event(query_uuid, event_type, value);
901                 break;
902         }
903         // We need to inform about changes in these queries to the respective plugins
904         // Note: query, main_query & update_query have the same UUID
905         manifold.raise_query_event(query_uuid, event_type, value);
906         // We are targeting the same object with get and update
907         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
908         // NOTE: Editing a subquery == editing a local view on the destination
909
910         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
911         // For the time being, we will collect all columns during the first query
912     },
913
914     /* Publish/subscribe channels for internal use */
915     get_channel: function(type, query_uuid) 
916     {
917         if ((type !== 'query') && (type != 'record'))
918             return null;
919         return '/' + type + '/' + query_uuid;
920     },
921
922 }; // manifold object
923 /* ------------------------------------------------------------ */
924
925 (function($) {
926
927     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
928     // https://gist.github.com/661855
929     var o = $({});
930     $.subscribe = function( channel, selector, data, fn) {
931       /* borrowed from jQuery */
932       if ( data == null && fn == null ) {
933           // ( channel, fn )
934           fn = selector;
935           data = selector = undefined;
936       } else if ( fn == null ) {
937           if ( typeof selector === "string" ) {
938               // ( channel, selector, fn )
939               fn = data;
940               data = undefined;
941           } else {
942               // ( channel, data, fn )
943               fn = data;
944               data = selector;
945               selector = undefined;
946           }
947       }
948       /* </ugly> */
949   
950       /* We use an indirection function that will clone the object passed in
951        * parameter to the subscribe callback 
952        * 
953        * FIXME currently we only clone query objects which are the only ones
954        * supported and editable, we might have the same issue with results but
955        * the page load time will be severely affected...
956        */
957       o.on.apply(o, [channel, selector, data, function() { 
958           for(i = 1; i < arguments.length; i++) {
959               if ( arguments[i].constructor.name == 'ManifoldQuery' )
960                   arguments[i] = arguments[i].clone();
961           }
962           fn.apply(o, arguments);
963       }]);
964     };
965   
966     $.unsubscribe = function() {
967       o.off.apply(o, arguments);
968     };
969   
970     $.publish = function() {
971       o.trigger.apply(o, arguments);
972     };
973   
974 }(jQuery));
975
976 /* ------------------------------------------------------------ */
977
978 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
979 //make sure to expose csrf in our outcoming ajax/post requests
980 $.ajaxSetup({ 
981      beforeSend: function(xhr, settings) {
982          function getCookie(name) {
983              var cookieValue = null;
984              if (document.cookie && document.cookie != '') {
985                  var cookies = document.cookie.split(';');
986                  for (var i = 0; i < cookies.length; i++) {
987                      var cookie = jQuery.trim(cookies[i]);
988                      // Does this cookie string begin with the name we want?
989                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
990                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
991                      break;
992                  }
993              }
994          }
995          return cookieValue;
996          }
997          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
998              // Only send the token to relative URLs i.e. locally.
999              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
1000          }
1001      } 
1002 });
1003