2 function debug_dict_keys (msg, o) {
4 for (var k in o) keys.push(k);
5 messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
7 function debug_dict (msg, o) {
8 for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
10 function debug_value (msg, value) {
11 messages.debug ("debug_value: " + msg + " " + value);
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);
20 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
21 Object.toType = (function toType(global) {
22 return function(obj) {
26 return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
30 /* ------------------------------------------------------------ */
32 // Constants that should be somehow moved to a plugin.js file
34 var FILTER_REMOVED = 2;
35 var CLEAR_FILTERS = 3;
37 var FIELD_REMOVED = 5;
40 var CLEAR_RECORDS = 8;
43 * event: FIELD_STATE_CHANGED
47 * .request : ???? used to be FIELD_REQUEST_ADD / FIELD_REQUEST_REMOVE
48 * .key : ??? the key fields of the record
49 * .value : the key of the record who has received an update
50 * .status : the new state of the record
51 * TODO rename to state, and use values from STATE_SET
53 var FIELD_STATE_CHANGED = 9;
55 var IN_PROGRESS = 101;
58 /* Update requests related to subqueries */
64 * string : The key of the element being added
72 * string : The key of the element being removed
74 var SET_REMOVED = 202;
78 var FIELD_REQUEST_CHANGE = 301;
79 var FIELD_REQUEST_ADD = 302;
80 var FIELD_REQUEST_REMOVE = 303;
81 var FIELD_REQUEST_ADD_RESET = 304;
82 var FIELD_REQUEST_REMOVE_RESET = 305;
83 // status (XXX Should be deprecated)
84 var FIELD_REQUEST_PENDING = 401;
85 var FIELD_REQUEST_SUCCESS = 402;
86 var FIELD_REQUEST_FAILURE = 403;
87 var STATUS_OKAY = 404;
88 var STATUS_SET_WARNING = 405;
89 var STATUS_ADD_WARNING = 406;
90 var STATUS_REMOVE_WARNING = 407;
91 var STATUS_RESET = 408;
93 /* Requests for query cycle */
99 var TYPE_LIST_OF_VALUES = 3;
100 var TYPE_LIST_OF_RECORDS = 4;
102 /******************************************************************************
103 * QUERY STATUS (for manifold events)
104 ******************************************************************************/
106 var STATUS_NONE = 500; // Query has not been started yet
107 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
108 var STATUS_GET_RECEIVED = 502; // Success
109 var STATUS_GET_ERROR = 503; // Error
110 var STATUS_UPDATE_PENDING = 504;
111 var STATUS_UPDATE_IN_PROGRESS = 505;
112 var STATUS_UPDATE_RECEIVED = 506;
113 var STATUS_UPDATE_ERROR = 507;
115 /******************************************************************************
116 * QUERY STATE (for query_store)
117 ******************************************************************************/
119 // XXX Rendundant with query status ?
121 var QUERY_STATE_INIT = 0;
122 var QUERY_STATE_INPROGRESS = 1;
123 var QUERY_STATE_DONE = 2;
125 /******************************************************************************
126 * RECORD STATES (for query_store)
127 ******************************************************************************/
130 var STATE_WARNINGS = 1;
131 var STATE_VISIBLE = 2;
134 var STATE_SET_IN = 0;
135 var STATE_SET_OUT = 1;
136 var STATE_SET_IN_PENDING = 2;
137 var STATE_SET_OUT_PENDING = 3;
138 var STATE_SET_IN_SUCCESS = 4;
139 var STATE_SET_OUT_SUCCESS = 5;
140 var STATE_SET_IN_FAILURE = 6;
141 var STATE_SET_OUT_FAILURE = 7;
143 // STATE_WARNINGS : dict
145 // STATE_VISIBLE : boolean
147 /******************************************************************************
149 ******************************************************************************/
151 var CONSTRAINT_RESERVABLE_LEASE = 0;
153 // A structure for storing queries
155 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled, domain_query_ext) {
158 if (typeof query == "undefined")
159 throw "Must pass a query in QueryExt constructor";
161 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext;
162 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext;
163 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext;
164 this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null : update_query_orig_ext;
165 this.disabled = (typeof disabled == "undefined") ? false : disabled;
167 // A domain query is a query that is issued to retrieve all possible values for a set
168 // eg. all resources that can be attached to a slice
169 // It is null unless we are a subquery for which a domain query has been issued
170 this.domain_query_ext = (typeof domain_query_ext == "undefined") ? null : domain_query_ext;
172 // Set members to buffer until the domain query is completed
174 this.set_members = [];
176 // The set query is the query for which the domain query has been issued.
177 // It is null unless the query is a domain query
178 this.set_query_ext = (typeof set_query_ext == "undefined") ? null : domain_query_ext;
180 this.query_state = QUERY_STATE_INIT;
182 // Results from a query consists in a dict that maps keys to records
183 this.records = new Hashtable();
185 // Status is a dict that maps keys to record status
186 this.state = new Hashtable();
188 // Filters that impact visibility in the local interface
191 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
194 function QueryStore() {
196 this.main_queries = {};
197 this.analyzed_queries = {};
201 this.insert = function(query) {
202 // We expect only main_queries are inserted
204 /* If the query has not been analyzed, then we analyze it */
205 if (query.analyzed_query == null) {
206 query.analyze_subqueries();
209 /* We prepare the update query corresponding to the main query and store both */
210 /* Note: they have the same UUID */
212 // XXX query.change_action() should become deprecated
213 update_query = query.clone();
214 update_query.action = 'update';
215 update_query.analyzed_query.action = 'update';
216 update_query.params = {};
217 update_query_ext = new QueryExt(update_query);
219 /* We remember the original query to be able to reset it */
220 update_query_orig_ext = new QueryExt(update_query.clone());
223 /* We store the main query */
224 query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
225 manifold.query_store.main_queries[query.query_uuid] = query_ext;
226 /* Note: the update query does not have an entry! */
229 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
230 // XXX unless we have no subqueries ???
231 // we will complete with params when records are received... this has to be done by the manager
232 // SET_ADD, SET_REMOVE will change the status of the elements of the set
233 // UPDATE will change also, etc.
234 // XXX We need a proper structure to store this information...
236 // We also need to insert all queries and subqueries from the analyzed_query
237 // XXX We need the root of all subqueries
238 query.iter_subqueries(function(sq, data, parent_query) {
239 var parent_query_ext;
241 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
243 parent_query_ext = null;
245 // XXX parent_query_ext == false
246 // XXX main.subqueries = {} # Normal, we need analyzed_query
247 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
250 /* Let's issue a query for the subquery domain. This query will not need any update etc.
251 eg. for resources in a slice, we also query all resources */
252 var all_fields = manifold.metadata.get_field_names(sq.object);
253 var domain_query = new ManifoldQuery('get', sq.object, 'now', [], {}, all_fields);
254 //var domain_query = new ManifoldQuery('get', sq.object);
256 console.log("Created domain query", domain_query);
257 var domain_query_ext = new QueryExt(domain_query);
259 domain_query_ext.set_query_ext = sq_ext;
260 sq_ext.domain_query_ext = domain_query_ext;
262 // One of these two is useless ?
263 manifold.query_store.main_queries[domain_query.query_uuid] = domain_query_ext;
264 manifold.query_store.analyzed_queries[domain_query.query_uuid] = domain_query_ext;
266 // XXX This query is run before the plugins are initialized and listening
267 manifold.run_query(domain_query);
270 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
273 // XXX We have spurious update queries...
278 this.find_query_ext = function(query_uuid)
280 return this.main_queries[query_uuid];
283 this.find_query = function(query_uuid)
285 return this.find_query_ext(query_uuid).query;
288 this.find_analyzed_query_ext = function(query_uuid)
290 return this.analyzed_queries[query_uuid];
293 this.find_analyzed_query = function(query_uuid)
295 return this.find_analyzed_query_ext(query_uuid).query;
298 this.state_dict_create = function(default_set)
300 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
302 // We cannot use constants in literal definition, so...
303 state_dict[STATE_WARNINGS] = {};
304 state_dict[STATE_SET] = default_set;
305 state_dict[STATE_VISIBLE] = true;
311 this.set_records = function(query_uuid, records, default_set)
313 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
316 var query_ext = this.find_analyzed_query_ext(query_uuid);
317 var record_key = manifold.metadata.get_key(query_ext.query.object);
318 $.each(records, function(i, record) {
319 var key = manifold.metadata.get_key(query_ext.query.object);
320 // ["start_time", "resource", "end_time"]
323 var record_key_value = manifold.record_get_value(record, record_key);
324 query_ext.records.put(record_key_value, record);
326 if (!(query_ext.state.get(record_key_value)))
327 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
331 this.get_records = function(query_uuid)
333 var query_ext = this.find_analyzed_query_ext(query_uuid);
334 return query_ext.records.values();
337 this.get_record = function(query_uuid, record_key)
339 var query_ext = this.find_analyzed_query_ext(query_uuid);
340 return query_ext.records.get(record_key);
343 this.add_record = function(query_uuid, record, new_state)
345 var query_ext = this.find_analyzed_query_ext(query_uuid);
347 var key = manifold.metadata.get_key(query_ext.query.object);
348 var record_key = manifold.record_get_value(record, key);
350 var record_entry = query_ext.records.get(record_key);
352 query_ext.records.put(record_key, record);
354 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
357 this.remove_record = function(query_uuid, record, new_state)
359 var query_ext = this.find_analyzed_query_ext(query_uuid);
361 var key = manifold.metadata.get_key(query_ext.query.object);
362 var record_key = manifold.record_get_value(record, key);
364 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
367 this.iter_records = function(query_uuid, callback)
369 var query_ext = this.find_analyzed_query_ext(query_uuid);
370 query_ext.records.each(callback);
371 //callback = function(record_key, record)
374 this.iter_visible_records = function(query_uuid, callback)
376 var query_ext = this.find_analyzed_query_ext(query_uuid);
377 query_ext.records.each(function(record_key, record) {
378 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
379 callback(record_key, record);
381 //callback = function(record_key, record)
387 this.set_record_state = function(query_uuid, result_key, state, value)
389 var query_ext = this.find_analyzed_query_ext(query_uuid);
390 var state_dict = query_ext.state.get(result_key);
392 state_dict = this.state_dict_create();
394 state_dict[state] = value;
396 query_ext.state.put(result_key, state_dict);
399 this.get_record_state = function(query_uuid, result_key, state)
401 var query_ext = this.find_analyzed_query_ext(query_uuid);
402 var state_dict = query_ext.state.get(result_key);
405 return state_dict[state];
410 this.add_filter = function(query_uuid, filter)
412 var query_ext = this.find_analyzed_query_ext(query_uuid);
413 // XXX When we update a filter
414 query_ext.filters.push(filter);
416 this.apply_filters(query_uuid);
420 this.update_filter = function(query_uuid, filter)
424 this.apply_filters(query_uuid);
427 this.remove_filter = function(query_uuid, filter)
429 var query_ext = this.find_analyzed_query_ext(query_uuid);
430 query_ext.filters = $.grep(query_ext.filters, function(x) {
434 this.apply_filters(query_uuid);
437 this.get_filters = function(query_uuid)
439 var query_ext = this.find_analyzed_query_ext(query_uuid);
440 return query_ext.filters;
443 this.apply_filters = function(query_uuid)
445 // Toggle visibility of records according to the different filters.
448 var filters = this.get_filters(query_uuid);
451 // Adapted from querytable._querytable_filter()
453 this.iter_records(query_uuid, function(record_key, record) {
456 // We go through each filter and decide whether it affects the visibility of the record
457 $.each(filters, function(index, filter) {
460 var value = filter[2];
463 /* We do some special handling for the manifold:status filter
466 if (key == 'manifold:status') {
467 if (op != '=' && op != '==') {
468 // Unsupported filter, let's ignore it
469 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
470 return true; // ~ continue
473 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
474 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
478 visible = (record_state == STATE_SET_IN)
479 || (record_state == STATE_SET_OUT_PENDING)
480 || (record_state == STATE_SET_IN_SUCCESS)
481 || (record_state == STATE_SET_OUT_FAILURE);
482 // visible = true => ~ continue
483 // visible = false => ~ break
487 var in_set = (record_state == STATE_SET_IN) // should not have warnings
488 || (record_state == STATE_SET_IN_PENDING)
489 || (record_state == STATE_SET_IN_SUCCESS)
490 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
491 visible = (in_set && !$.isEmptyObject(record_warnings));
495 visible = (record_state == STATE_SET_IN_PENDING)
496 || (record_state == STATE_SET_OUT_PENDING);
499 return false; // ~ break
502 /* Normal filtering behaviour (according to the record content) follows... */
503 col_value = manifold.record_get_value(record, record_key);
505 // When the filter does not match, we hide the column by default
506 if (col_value === 'undefined') {
508 return false; // ~ break
511 // XXX This should accept pluggable filtering functions.
514 /* Test whether current filter is compatible with the column */
515 if (op == '=' || op == '==') {
516 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
518 }else if (op == 'included') {
519 $.each(value, function(i,x) {
522 return false; // ~ break
527 }else if (op == '!=') {
528 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
531 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
534 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
536 } else if(op=='<=' || op=='≤') {
537 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
539 } else if(op=='>=' || op=='≥') {
540 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
543 // How to break out of a loop ?
544 alert("filter not supported");
545 return false; // break
550 // Set the visibility status in the query store
551 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
559 * This namespace holds functions for globally managing query objects
564 /**************************************************************************
566 **************************************************************************/
570 get_type: function(variable) {
571 switch(Object.toType(variable)) {
578 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
579 return TYPE_LIST_OF_RECORDS;
581 return TYPE_LIST_OF_VALUES;
587 * fields: A String instance (field name), or a set of String instances
588 * (field names) # XXX tuple !!
590 * If fields is a String, return the corresponding value.
591 * If fields is a set, return a tuple of corresponding value.
594 * KeyError if at least one of the fields is not found
596 record_get_value: function(record, fields)
598 if (typeof(fields) === 'string') {
599 if (fields.indexOf('.') != -1) {
600 key_subkey = key.split('.', 2);
602 subkey = key_subkey[1];
604 if (record.indexOf(key) == -1) {
607 // Tests if the following is an array (typeof would give object)
608 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
610 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
611 } else if (typeof(record) == 'object') {
613 return manifold.record_get_value(record[key], subkey);
615 console.log('Unknown field');
618 return record[fields];
621 // see. get_map_entries
622 if (fields.length == 1)
623 return manifold.record_get_value(record, fields[0])
625 // Build a new record
627 $.each(fields, function(i, field) {
628 ret[field] = manifold.record_get_value(record, field);
630 ret.hashCode = record.hashCode;
631 ret.equals = record.equals;
633 // this was an array, we want a dictionary
634 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
639 record_hashcode: function(key_fields)
643 for (i=0; i < key_fields.length; i++)
644 ret += "@@" + this[key_fields[i]];
649 record_equals: function(key_fields)
653 return function(other) {
654 for (i=0; i < key_fields.length; i++) {
655 var this_value = this[key_fields[i]];
656 var other_value = other[key_fields[i]];
658 var this_type = self.get_type(this_value);
659 var other_type = self.get_type(other_value);
660 if (this_type != other_type)
665 case TYPE_LIST_OF_VALUES:
666 if (this_value != other_value)
670 if (!(record_equals(this_value, other_value)))
673 case TYPE_LIST_OF_RECORDS:
674 if (this_value.length != other_value.length)
676 for (i = 0; i < this_value.length; i++)
677 if (!(record_equals(this_value, other_value)))
687 /**************************************************************************
688 * Metadata management
689 **************************************************************************/
693 get_table: function(method) {
694 var table = MANIFOLD_METADATA[method];
695 return (typeof table === 'undefined') ? null : table;
698 get_columns: function(method) {
699 var table = this.get_table(method);
704 return (typeof table.column === 'undefined') ? null : table.column;
707 get_field_names: function(method)
709 var columns = this.get_columns(method);
712 return $.map(columns, function (x) { return x.name });
715 get_key: function(method) {
716 var table = this.get_table(method);
720 return (typeof table.key === 'undefined') ? null : table.key;
724 get_column: function(method, name) {
725 var columns = this.get_columns(method);
729 $.each(columns, function(i, c) {
736 get_type: function(method, name) {
737 var table = this.get_table(method);
741 var match = $.grep(table.column, function(x) { return x.name == name });
742 if (match.length == 0) {
745 return match[0].type;
747 return (typeof table.type === 'undefined') ? null : table.type;
752 /**************************************************************************
754 **************************************************************************/
756 query_store: new QueryStore(),
758 // XXX Remaining functions are deprecated since they are replaced by the query store
761 * Associative array storing the set of queries active on the page
767 * Insert a query in the global hash table associating uuids to queries.
768 * If the query has no been analyzed yet, let's do it.
769 * \fn insert_query(query)
771 * \param ManifoldQuery query Query to be added
773 insert_query : function (query) {
775 manifold.query_store.insert(query);
778 manifold.run_query(query);
781 if (query.analyzed_query == null) {
782 query.analyze_subqueries();
784 manifold.all_queries[query.query_uuid]=query;
788 * Returns the query associated to a UUID
789 * \fn find_query(query_uuid)
791 * \param string query_uuid The UUID of the query to be returned
793 find_query : function (query_uuid) {
794 return manifold.all_queries[query_uuid];
797 /**************************************************************************
799 **************************************************************************/
801 // trigger a query asynchroneously
802 proxy_url : '/manifold/proxy/json/',
804 // reasonably low-noise, shows manifold requests coming in and out
805 asynchroneous_debug : true,
806 // print our more details on result publication and related callbacks
807 pubsub_debug : false,
810 * \brief We use js function closure to be able to pass the query (array)
811 * to the callback function used when data is received
813 success_closure: function(query, publish_uuid, callback) {
814 return function(data, textStatus) {
815 manifold.asynchroneous_success(data, query, publish_uuid, callback);
819 run_query: function(query, callback)
821 // default value for callback = null
822 if (typeof callback === 'undefined')
825 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
826 query_ext.query_state = QUERY_STATE_INPROGRESS;
828 var query_json = JSON.stringify(query);
830 // Inform plugins about the progress
831 query.iter_subqueries(function (sq) {
832 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
833 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
835 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
839 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
843 // Executes all async. queries - intended for the javascript header to initialize queries
844 // input queries are specified as a list of {'query_uuid': <query_uuid> }
845 // each plugin is responsible for managing its spinner through on_query_in_progress
846 asynchroneous_exec : function (query_exec_tuples) {
848 // Loop through input array, and use publish_uuid to publish back results
849 $.each(query_exec_tuples, function(index, tuple) {
850 var query=manifold.find_query(tuple.query_uuid);
851 var query_json=JSON.stringify (query);
852 var publish_uuid=tuple.publish_uuid;
853 // by default we publish using the same uuid of course
854 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
855 if (manifold.pubsub_debug) {
856 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
859 query.iter_subqueries(function (sq) {
860 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
863 // not quite sure what happens if we send a string directly, as POST data is named..
864 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
865 $.post(manifold.proxy_url, {'json':query_json},
866 manifold.success_closure(query, publish_uuid, tuple.callback));
871 * \brief Forward a query to the manifold backend
872 * \param query (dict) the query to be executed asynchronously
873 * \param callback (function) the function to be called when the query terminates
875 forward: function(query, callback) {
876 var query_json = JSON.stringify(query);
877 $.post(manifold.proxy_url, {'json': query_json} ,
878 manifold.success_closure(query, query.query_uuid, callback));
882 * Returns whether a query expects a unique results.
883 * This is the case when the filters contain a key of the object
884 * \fn query_expects_unique_result(query)
886 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
888 query_expects_unique_result: function(query) {
889 /* XXX we need functions to query metadata */
890 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
891 /* TODO requires keys in metadata */
897 * \fn publish_result(query, results)
899 * \param ManifoldQuery query Query which has received results
900 * \param array results results corresponding to query
902 publish_result: function(query, result) {
903 if (typeof result === 'undefined')
907 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
908 if (manifold.pubsub_debug)
909 messages.debug(".. publish_result (1) ");
911 $.each(result, function(i, record) {
912 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
915 if (manifold.pubsub_debug)
916 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
917 manifold.raise_record_event(query.query_uuid, DONE);
918 if (manifold.pubsub_debug)
919 messages.debug(".. publish_result (3) has used NEW API to say DONE");
921 // OLD PLUGIN API BELOW
922 /* Publish an update announce */
923 var channel="/results/" + query.query_uuid + "/changed";
924 if (manifold.pubsub_debug)
925 messages.debug(".. publish_result (4) OLD API on channel" + channel);
927 $.publish(channel, [result, query]);
929 if (manifold.pubsub_debug)
930 messages.debug(".. publish_result (5) END q=" + query.__repr());
933 store_records: function(query, records) {
935 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
936 if (query_ext.set_query_ext) {
937 // We have a domain query
938 // The results are stored in the corresponding set_query
939 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records)
941 } else if (query_ext.domain_query_ext) {
942 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
943 // Has it a domain query, and has it completed ?
944 $.each(records, function(i, record) {
945 var key = manifold.metadata.get_key(query.object);
946 var record_key = manifold.record_get_value(record, key);
947 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
951 // We have a normal query
952 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
957 * Recursively publish result
958 * \fn publish_result_rec(query, result)
960 * \param ManifoldQuery query Query which has received result
961 * \param array result result corresponding to query
963 * Note: this function works on the analyzed query
965 publish_result_rec: function(query, records) {
966 /* If the result is not unique, only publish the top query;
967 * otherwise, publish the main object as well as subqueries
968 * XXX how much recursive are we ?
970 if (manifold.pubsub_debug)
971 messages.debug (">>>>> publish_result_rec " + query.object);
972 if (manifold.query_expects_unique_result(query)) {
973 /* Also publish subqueries */
974 $.each(query.subqueries, function(object, subquery) {
975 manifold.publish_result_rec(subquery, records[0][object]);
976 /* TODO remove object from result */
979 if (manifold.pubsub_debug)
980 messages.debug ("===== publish_result_rec " + query.object);
982 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
983 query_ext.query_state = QUERY_STATE_DONE;
985 this.store_records(query, records);
989 if (query_ext.set_query_ext) {
990 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
992 pub_query = query_ext.set_query_ext.query;
993 } else if (query_ext.domain_query_ext) {
994 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1000 // We can only publish results if the query (and its related domain query) is complete
1001 manifold.publish_result(pub_query, records);
1003 if (manifold.pubsub_debug)
1004 messages.debug ("<<<<< publish_result_rec " + query.object);
1007 setup_update_query: function(query, records) {
1008 // We don't prepare an update query if the result has more than 1 entry
1009 if (records.length != 1)
1011 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1013 var record = records[0];
1015 var update_query_ext = query_ext.update_query_ext;
1017 console.log("Update case not handled yet!");
1018 if (!update_query_ext)
1021 var update_query = update_query_ext.query;
1022 var update_query_ext = query_ext.update_query_ext;
1023 var update_query_orig = query_ext.update_query_orig_ext.query;
1025 // Testing whether the result has subqueries (one level deep only)
1026 // iif the query has subqueries
1028 var obj = query.analyzed_query.subqueries;
1029 for (method in obj) {
1030 if (obj.hasOwnProperty(method)) {
1031 var key = manifold.metadata.get_key(method);
1035 var subrecords = record[method];
1038 $.each(subrecords, function (i, subrecord) {
1039 sq_keys.push(manifold.record_get_value(subrecord, key));
1041 update_query.params[method] = sq_keys;
1042 update_query_orig.params[method] = sq_keys.slice();
1048 update_query_ext.disabled = false;
1049 update_query_orig_ext.disabled = false;
1053 process_get_query_records: function(query, records) {
1054 this.setup_update_query(query, records);
1056 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1057 query_ext.query_state = QUERY_STATE_DONE;
1059 /* Publish full results */
1060 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1061 manifold.publish_result_rec(tmp_query, records);
1064 make_records: function(object, records)
1066 $.each(records, function(i, record) {
1067 manifold.make_record(object, record);
1071 make_record: function(object, record)
1073 // To make an object a record, we just add the hash function
1074 var key = manifold.metadata.get_key(object);
1075 record.hashCode = manifold.record_hashcode(key.sort());
1076 record.equals = manifold.record_equals(key);
1078 // Looking after subrecords
1079 for (var field in record) {
1080 var result_value = record[field];
1082 switch (this.get_type(result_value)) {
1084 var subobject = manifold.metadata.get_type(object, field);
1086 manifold.make_record(subobject, result_value);
1088 case TYPE_LIST_OF_RECORDS:
1089 var subobject = manifold.metadata.get_type(object, field);
1091 manifold.make_records(subobject, result_value);
1099 * What we need to do when receiving results from an update query:
1100 * - differences between what we had, what we requested, and what we obtained
1101 * . what we had : update_query_orig (simple fields and set fields managed differently)
1102 * . what we requested : update_query
1103 * . what we received : records
1104 * - raise appropriate events
1106 * The normal process is that results similar to Get will be pushed in the
1107 * pubsub mechanism, thus repopulating everything while we only need
1108 * diff's. This means we need to move the publish functionalities in the
1109 * previous 'process_get_query_records' function.
1111 process_update_query_records: function(query, records) {
1127 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1128 var query_uuid = query.query_uuid;
1129 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1130 var update_query = query_ext.main_query_ext.update_query_ext.query;
1131 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1133 // Since we update objects one at a time, we can get the first record
1134 var record = records[0];
1136 // Let's iterate over the object properties
1137 for (var field in record) {
1138 var result_value = record[field];
1139 switch (this.get_type(result_value)) {
1141 // Did we ask for a change ?
1142 var update_value = update_query[field];
1144 // Not requested, if it has changed: OUT OF SYNC
1145 // How we can know ?
1146 // We assume it won't have changed
1150 throw "Internal error";
1153 request: FIELD_REQUEST_CHANGE,
1155 value : update_value,
1156 status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
1158 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1162 throw "Not implemented";
1165 case TYPE_LIST_OF_VALUES:
1166 // Same as list of records, but we don't have to extract keys
1168 // The rest of exactly the same (XXX factorize)
1169 var update_keys = update_query_orig.params[field];
1170 var query_keys = update_query.params[field];
1171 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1172 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1175 $.each(added_keys, function(i, key) {
1176 if ($.inArray(key, result_value) == -1) {
1178 request: FIELD_REQUEST_ADD,
1181 status: FIELD_REQUEST_FAILURE,
1185 request: FIELD_REQUEST_ADD,
1188 status: FIELD_REQUEST_SUCCESS,
1191 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1193 $.each(removed_keys, function(i, key) {
1194 if ($.inArray(key, result_keys) == -1) {
1196 request: FIELD_REQUEST_REMOVE,
1199 status: FIELD_REQUEST_SUCCESS,
1203 request: FIELD_REQUEST_REMOVE,
1206 status: FIELD_REQUEST_FAILURE,
1209 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1214 case TYPE_LIST_OF_RECORDS:
1215 // example: slice.resource
1216 // - update_query_orig.params.resource = resources in slice before update
1217 // - update_query.params.resource = resource requested in slice
1218 // - keys from field = resources obtained
1219 var key = manifold.metadata.get_key(field);
1222 if (key.length > 1) {
1223 throw "Not implemented";
1228 /* XXX should be modified for multiple keys */
1229 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1231 var update_keys = update_query_orig.params[field];
1232 var query_keys = update_query.params[field];
1233 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1234 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1237 $.each(added_keys, function(i, key) {
1238 if ($.inArray(key, result_keys) == -1) {
1240 request: FIELD_REQUEST_ADD,
1243 status: FIELD_REQUEST_FAILURE,
1247 request: FIELD_REQUEST_ADD,
1250 status: FIELD_REQUEST_SUCCESS,
1253 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1255 $.each(removed_keys, function(i, key) {
1256 if ($.inArray(key, result_keys) == -1) {
1258 request: FIELD_REQUEST_REMOVE,
1261 status: FIELD_REQUEST_SUCCESS,
1265 request: FIELD_REQUEST_REMOVE,
1268 status: FIELD_REQUEST_FAILURE,
1271 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1279 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1280 this.setup_update_query(query, records);
1283 process_query_records: function(query, records) {
1284 if (query.action == 'get') {
1285 this.process_get_query_records(query, records);
1286 } else if (query.action == 'update') {
1287 this.process_update_query_records(query, records);
1291 // if set callback is provided it is called
1292 // most of the time publish_uuid will be query.query_uuid
1293 // however in some cases we wish to publish the result under a different uuid
1294 // e.g. an updater wants to publish its result as if from the original (get) query
1295 asynchroneous_success : function (data, query, publish_uuid, callback) {
1296 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1298 var start = new Date();
1299 if (manifold.asynchroneous_debug)
1300 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1302 if (data.code == 2) { // ERROR
1303 // We need to make sense of error codes here
1304 alert("Your session has expired, please log in again");
1305 localStorage.removeItem('user');
1306 window.location="/logout/";
1307 if (manifold.asynchroneous_debug) {
1308 duration=new Date()-start;
1309 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1313 if (data.code == 1) { // WARNING
1314 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1315 // publish error code and text message on a separate channel for whoever is interested
1317 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1321 // If a callback has been specified, we redirect results to it
1324 if (manifold.asynchroneous_debug) {
1325 duration=new Date()-start;
1326 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1331 if (manifold.asynchroneous_debug)
1332 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1334 // once everything is checked we can use the 'value' part of the manifoldresult
1335 var result=data.value;
1337 /* Eventually update the content of related queries (update, etc) */
1338 manifold.make_records(query.object, result);
1339 this.process_query_records(query, result);
1341 /* Publish results: disabled here, done in the previous call */
1342 //tmp_query = manifold.find_query(query.query_uuid);
1343 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1345 if (manifold.asynchroneous_debug) {
1346 duration=new Date()-start;
1347 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1352 /**************************************************************************
1353 * Plugin API helpers
1354 **************************************************************************/
1356 raise_event_handler: function(type, query_uuid, event_type, value) {
1357 if (manifold.pubsub_debug)
1358 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1359 if ((type != 'query') && (type != 'record'))
1360 throw 'Incorrect type for manifold.raise_event()';
1361 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1362 // this should be fixed upstream in manifold I expect
1363 if (query_uuid === undefined) {
1364 messages.warning("undefined query in raise_event_handler");
1368 // notify the change to objects that either listen to this channel specifically,
1369 // or to the wildcard channel
1370 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1372 $.each(channels, function(i, channel) {
1373 if (value === undefined) {
1374 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1375 $('.pubsub').trigger(channel, [event_type]);
1377 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1378 $('.pubsub').trigger(channel, [event_type, value]);
1383 raise_query_event: function(query_uuid, event_type, value) {
1384 manifold.raise_event_handler('query', query_uuid, event_type, value);
1387 raise_record_event: function(query_uuid, event_type, value) {
1388 manifold.raise_event_handler('record', query_uuid, event_type, value);
1392 raise_event: function(query_uuid, event_type, value) {
1393 // Query uuid has been updated with the key of a new element
1394 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1395 query = query_ext.query;
1397 switch(event_type) {
1399 case FIELD_STATE_CHANGED:
1400 // value is an object (request, key, value, status)
1401 // update is only possible is the query is not pending, etc
1402 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1403 // we should map SET_ADD on this...
1405 // 1. Update internal query store about the change in status
1407 // 2. Update the update query
1408 update_query = query_ext.main_query_ext.update_query_ext.query;
1409 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1411 switch(value.request) {
1412 case FIELD_REQUEST_CHANGE:
1413 if (update_query.params[value.key] === undefined)
1414 update_query.params[value.key] = Array();
1415 update_query.params[value.key] = value.value;
1417 case FIELD_REQUEST_ADD:
1418 if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
1419 value.request = FIELD_REQUEST_ADD_RESET;
1420 if (update_query.params[value.key] === undefined)
1421 update_query.params[value.key] = Array();
1422 update_query.params[value.key].push(value.value);
1424 case FIELD_REQUEST_REMOVE:
1425 if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
1426 value.request = FIELD_REQUEST_REMOVE_RESET;
1428 var arr = update_query.params[value.key];
1429 arr = $.grep(arr, function(x) { return x != value.value; });
1430 if (update_query.params[value.key] === undefined)
1431 update_query.params[value.key] = Array();
1432 update_query.params[value.key] = arr;
1435 case FIELD_REQUEST_ADD_RESET:
1436 case FIELD_REQUEST_REMOVE_RESET:
1437 // XXX We would need to keep track of the original query
1438 throw "Not implemented";
1442 // 3. Inform others about the change
1443 // a) the main query...
1444 manifold.raise_record_event(query_uuid, event_type, value);
1446 // b) subqueries eventually (dot in the key)
1448 var path_array = value.key.split('.');
1449 var value_key = value.key.split('.');
1451 var cur_query = query;
1452 if (cur_query.analyzed_query)
1453 cur_query = cur_query.analyzed_query;
1454 $.each(path_array, function(i, method) {
1455 cur_query = cur_query.subqueries[method];
1456 value_key.shift(); // XXX check that method is indeed shifted
1458 value.key = value_key;
1460 manifold.raise_record_event(cur_query.query_uuid, event_type, value);
1462 // XXX make this DOT a global variable... could be '/'
1468 /* An object has been added to / removed from a set : its
1469 * status become pending or reset to the original state. We
1470 * update the record status in the analyzed queries.
1472 * XXX Shall we update something in the main_query ?
1474 var prev_state, new_state;
1476 prev_state = manifold.query_store.get_record_state(query_uuid, value, STATE_SET);
1477 if (prev_state === null)
1478 prev_state = STATE_SET_OUT;
1480 if (event_type == SET_ADD) {
1481 switch (prev_state) {
1483 case STATE_SET_OUT_SUCCESS:
1484 case STATE_SET_IN_FAILURE:
1485 new_state = STATE_SET_IN_PENDING;
1488 case STATE_SET_OUT_PENDING:
1489 new_state = STATE_SET_IN;
1493 case STATE_SET_IN_PENDING:
1494 case STATE_SET_IN_SUCCESS:
1495 case STATE_SET_OUT_FAILURE:
1496 console.log("Inconsistent state: already in");
1499 } else { // SET_REMOVE
1500 switch (prev_state) {
1502 case STATE_SET_IN_SUCCESS:
1503 case STATE_SET_OUT_FAILURE:
1504 new_state = STATE_SET_OUT_PENDING;
1507 case STATE_SET_IN_PENDING:
1508 new_state = STATE_SET_OUT;
1512 case STATE_SET_OUT_PENDING:
1513 case STATE_SET_OUT_SUCCESS:
1514 case STATE_SET_IN_FAILURE:
1515 console.log("Inconsistent state: already out");
1521 var resource_key = value;
1523 if (event_type == SET_ADD)
1524 manifold.query_store.add_record(query_uuid, resource_key, new_state);
1526 manifold.query_store.remove_record(query_uuid, resource_key, new_state);
1528 var record = manifold.query_store.get_record(query_uuid, resource_key);
1532 // CONSTRAINT_RESERVABLE_LEASE
1534 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1535 var is_reservable = (record.exclusive == true);
1536 if (is_reservable) {
1537 var warnings = manifold.query_store.get_record_state(query_uuid, resource_key, STATE_WARNINGS);
1539 if (event_type == SET_ADD) {
1540 // We should have a lease_query associated
1541 var lease_query = query_ext.parent_query_ext.query.subqueries['lease'];
1542 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1543 // Do we have lease records with this resource
1544 var lease_records = $.grep(lease_query_ext.records, function(lease_key, lease) {
1545 return lease['resource'] == value;
1547 if (lease_records.length == 0) {
1549 // XXX Need for a better function to manage warnings
1550 var warn = "No lease defined for this reservable resource.";
1551 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1553 // Lease are defined, delete the warning in case it was set previously
1554 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1557 // Remove warnings attached to this resource
1558 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1561 manifold.query_store.set_record_state(query_uuid, resource_key, STATE_WARNINGS, warnings);
1564 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1568 value : resource_key,
1569 status: STATE_WARNINGS
1571 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1573 // -) When a lease is added, it might remove the warning associated to a reservable node
1575 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1576 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1578 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1579 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1581 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1583 /* END CONSTRAINTS */
1585 // update is only possible is the query is not pending, etc
1588 // XXX we can only update subqueries of the main query. Check !
1589 // assert query_ext.parent_query == query_ext.main_query
1590 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
1592 // This SET_ADD is called on a subquery, so we have to
1593 // recontruct the path of the key in the main_query
1594 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
1598 while (sq.parent_query_ext) {
1601 path = sq.query.object + path;
1602 sq = sq.parent_query_ext;
1605 main_query = query_ext.main_query_ext.query;
1607 request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
1610 status: STATE_SET, // XXX used to be FIELD_REQUEST_PENDING, and not new_state
1612 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
1614 // old //update_query.params[path].push(value);
1615 // old // console.log('Updated query params', update_query);
1616 // NOTE: update might modify the fields in Get
1617 // NOTE : we have to modify all child queries
1618 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
1620 // if everything is done right, update_query should not be null.
1621 // It is updated when we received results from the get query
1622 // object = the same as get
1623 // filter = key : update a single object for now
1624 // fields = the same as get
1625 manifold.raise_query_event(query_uuid, event_type, value);
1630 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1636 /* Update internal record state */
1637 manifold.query_store.add_filter(query_uuid, value);
1639 /* Propagate the message to plugins */
1640 manifold.raise_query_event(query_uuid, event_type, value);
1644 case FILTER_REMOVED:
1645 /* Update internal record state */
1646 manifold.query_store.remove_filter(query_uuid, value);
1648 /* Propagate the message to plugins */
1649 manifold.raise_query_event(query_uuid, event_type, value);
1654 main_query = query_ext.main_query_ext.query;
1655 main_update_query = query_ext.main_query_ext.update_query;
1656 query.select(value);
1658 // Here we need the full path through all subqueries
1660 // XXX We might need the query name in the QueryExt structure
1661 main_query.select(value);
1663 // XXX When is an update query associated ?
1664 // XXX main_update_query.select(value);
1666 manifold.raise_query_event(query_uuid, event_type, value);
1670 query = query_ext.query;
1671 main_query = query_ext.main_query_ext.query;
1672 main_update_query = query_ext.main_query_ext.update_query;
1673 query.unselect(value);
1674 main_query.unselect(value);
1676 // We need to inform about changes in these queries to the respective plugins
1677 // Note: query & main_query have the same UUID
1678 manifold.raise_query_event(query_uuid, event_type, value);
1681 // We need to inform about changes in these queries to the respective plugins
1682 // Note: query, main_query & update_query have the same UUID
1684 // http://trac.myslice.info/ticket/32
1685 // Avoid multiple calls to the same event
1686 //manifold.raise_query_event(query_uuid, event_type, value);
1688 // We are targeting the same object with get and update
1689 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1690 // NOTE: Editing a subquery == editing a local view on the destination
1692 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1693 // For the time being, we will collect all columns during the first query
1696 /* Publish/subscribe channels for internal use */
1697 get_channel: function(type, query_uuid) {
1698 if ((type !== 'query') && (type != 'record'))
1700 return '/' + type + '/' + query_uuid;
1703 }; // manifold object
1704 /* ------------------------------------------------------------ */
1708 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1709 // https://gist.github.com/661855
1711 $.subscribe = function( channel, selector, data, fn) {
1712 /* borrowed from jQuery */
1713 if ( data == null && fn == null ) {
1716 data = selector = undefined;
1717 } else if ( fn == null ) {
1718 if ( typeof selector === "string" ) {
1719 // ( channel, selector, fn )
1723 // ( channel, data, fn )
1726 selector = undefined;
1731 /* We use an indirection function that will clone the object passed in
1732 * parameter to the subscribe callback
1734 * FIXME currently we only clone query objects which are the only ones
1735 * supported and editable, we might have the same issue with results but
1736 * the page load time will be severely affected...
1738 o.on.apply(o, [channel, selector, data, function() {
1739 for(i = 1; i < arguments.length; i++) {
1740 if ( arguments[i].constructor.name == 'ManifoldQuery' )
1741 arguments[i] = arguments[i].clone();
1743 fn.apply(o, arguments);
1747 $.unsubscribe = function() {
1748 o.off.apply(o, arguments);
1751 $.publish = function() {
1752 o.trigger.apply(o, arguments);
1757 /* ------------------------------------------------------------ */
1759 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1760 //make sure to expose csrf in our outcoming ajax/post requests
1762 beforeSend: function(xhr, settings) {
1763 function getCookie(name) {
1764 var cookieValue = null;
1765 if (document.cookie && document.cookie != '') {
1766 var cookies = document.cookie.split(';');
1767 for (var i = 0; i < cookies.length; i++) {
1768 var cookie = jQuery.trim(cookies[i]);
1769 // Does this cookie string begin with the name we want?
1770 if (cookie.substring(0, name.length + 1) == (name + '=')) {
1771 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1778 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1779 // Only send the token to relative URLs i.e. locally.
1780 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));