PageSourceSearch

https://www.sculptures.org.nz/_web_services/likes-api.js

js sculptures.org.nz collected 2026-09-25 09:21:26 UTC 12,241 bytes, 474 lines download raw bytes

1/**
2* +--------------------------------------------------------------------+
3* | This MySource Matrix CMS file is Copyright (c) Squiz Pty Ltd       |
4* | ABN 77 084 670 600                                                 |
5* +--------------------------------------------------------------------+
6* | IMPORTANT: Your use of this Software is subject to the terms of    |
7* | the Licence provided in the file licence.txt. If you cannot find   |
8* | this file please contact Squiz (www.squiz.com.au) so we may provide|
9* | you a copy.                                                        |
10* +--------------------------------------------------------------------+
11*
12*/
13
14(function(gscope){
15
16
17	/**
18	* Convert a JSON string to object
19	*/
20	function jsonToObj(json)
21	{
22		// Make the conversion
23		if (typeof(JSON) !== 'undefined') {
24			return JSON.parse(json);
25		}// end if
26
27		// Don't worry, even the creator of JSON says eval is ok here
28		return eval('(' + json + ')');
29
30	}// end jsonToObj
31
32
33	/**
34	* Get all the properties of an object as an array
35	*
36	* @param object    obj     The object to get the parameters for
37	*/
38	function getProperties(obj)
39	{
40		var properties = [];
41		for (var propName in obj){
42			if (obj.hasOwnProperty(propName)){
43				properties.push(propName);
44			}// end if
45		}// end for
46
47		return properties;
48
49	}// end getProperties
50
51
52	/**
53	* Convert a variable to a boolean
54	*/
55	function convertToBoolean(variable)
56	{
57		var ret = false;
58		if (variable !== null && typeof(variable) !== "undefined") {
59			switch (typeof(variable)) {
60				case 'number':
61					ret = (variable === 1) ? true : false;
62					break;
63
64				case 'boolean':
65					ret = variable;
66					break;
67
68				case 'string':
69					var testVar = variable.toLowerCase();
70					if (testVar === 'true' || testVar === '1') {
71						ret = true;
72					} else if (testVar === 'false' || testVar === '0') {
73						ret = false;
74					}// end if
75					break;
76			}// end switch
77
78		}// end if
79
80		return ret;
81
82	}// end convertToBoolean
83
84
85	/**
86	* The API constructor
87	*/
88	gscope.Squiz_Matrix_API = function(options)
89	{
90		var self = this;
91
92		if (!options.hasOwnProperty('key') || options.key === '') {
93			throw 'An API key is required';
94		}// end if
95
96		self.key = options.key;
97
98		self.nonceToken = '';
99
100	};// end construct
101
102
103	/**
104	* API methods
105	*/
106	gscope.Squiz_Matrix_API.prototype = {
107		syncing_enabled : 0,
108
109		_http: function(options)
110		{
111			var self = this;
112
113			// Create the HTTPRequest object
114			function createRequest()
115			{
116				var request;
117				try {
118					request = new XMLHttpRequest();
119				} catch (trymicrosoft) {
120					try {
121						request = new ActiveXObject("Msxml2.XMLHTTP");
122					} catch (othermicrosoft) {
123						try {
124							request = new ActiveXObject("Microsoft.XMLHTTP");
125						} catch(nosupport) {
126							request = false;
127						}// end try
128					}// end try
129				}// end try
130
131				if (!request) {
132					throw 'Your browser does not support Ajax';
133				}// end if
134
135				return request;
136
137			}// end createRequest
138
139
140			// Process parameters into a data array
141			function data(params)
142			{
143				// Automatically append 'key' to every request
144				var dataArr = {};
145
146				for (var i = 0, l = params.length; i < l; i+=1) {
147					dataArr[params[i][0]] = params[i][1];
148				}// end for
149				return JSON.stringify(dataArr);
150
151			}// end data
152
153			// Set some defaults for the HTTP Request
154			options = self._options(['params'],{
155						url:                'http://www.sculptures.org.nz/_web_services/likes-api.js',
156						method:             'POST',
157						contentType:        'application/json',
158						params:             [],
159						async:              true,
160						onSuccess:          function(){},
161						onError:            function(){
162													throw 'HTTPRequest call failed';
163											}
164			},options);
165
166			var http = createRequest();
167			http.open(options.method,encodeURI(options.url),options.async);
168			http.onreadystatechange = function() {
169				if (http.readyState === 4) {
170					if (http.status === 200) {
171						if (typeof(http.responseText) !== 'undefined' || http.responseText !== '' || http.responseText !== null) {
172							var response = jsonToObj(http.responseText);
173							options.onSuccess.call(this,response);
174						} else {
175							options.onError.call(this,http);
176						}// end if
177					} else {
178						options.onError.call(this,http);
179					}// end if
180				}// end if
181			};// end onreadstatechange
182
183			http.setRequestHeader("Content-type", options.contentType);
184			http.setRequestHeader("X-SquizMatrix-JSAPI-Key", self.key);
185
186			// Send the request
187			http.send(data(options.params));
188
189		},// end _ajax
190
191
192		/**
193		* Validates options and returns merged data
194		*/
195		_options: function(required,defaults,options,discard)
196		{
197		    if (arguments.length < 4) {
198		        discard = true;
199		    }
200
201			// Required data
202			for (var i = 0, l = required.length; i<l; i+=1) {
203				if (!options.hasOwnProperty(required[i])) {
204					throw 'Required argument "' + required[i] + '" missing';
205				}// end if
206			}// end for
207
208			// Merge options and defaults
209			for (var def in options) {
210			    if (defaults.hasOwnProperty(def)){
211					defaults[def] = (options.hasOwnProperty(def)) ? options[def] : defaults[def];
212				} else if ((discard === false) && (options.hasOwnProperty(def))) {
213				    defaults[def] = options[def];
214				}//end if
215			}// end for
216
217			if (defaults.hasOwnProperty('dataCallback') && typeof(defaults.dataCallback) !== "function") {
218				throw 'Data callback must be a function';
219			}// end if
220
221			return defaults;
222
223		},// end _options
224
225			
226		/**
227		* batches multiple JS API calls and executs them in one HTTP Request
228		*
229		*
230		* @param object		options       JSON string of options
231		* {
232		*      functions:		json		json of all the function and its respective arguments to be passed in
233		*      dataCallback:	function	Custom callback function
234		* }
235		*/
236		batchRequest: function(options)
237		{
238			var fnName = 'batchRequest';
239			if (arguments.length === 0) {
240				return {
241					// Set the default values
242					defaults: {
243						functions:          null,
244						dataCallback:       function(){}
245					},
246
247					// Set the required arguments
248					required: ['functions']
249				};
250			}// end if
251
252			// Extract some configuration and use it to build
253			// parameters for the post call
254			var fnConfig = this[fnName].call(this);
255			options = this._options(fnConfig.required,fnConfig.defaults,options);
256
257			// Package up the required function calls into string to POST
258			//var postData = JSON.stringify(options.functions);
259
260			this._doPost(fnName,[
261				['functions', options.functions]
262			],options);
263
264		},// end batchRequest
265
266			
267		/**
268		* This will get metadata values
269		*
270		* @param object		options       JSON string of options
271		* {
272		*      asset_id:		string/int	Id of the asset we are getting info for
273		*      dataCallback:	function	Custom callback function
274		* }
275		*/
276		getMetadata: function(options)
277		{
278			var fnName = 'getMetadata';
279			if (arguments.length === 0) {
280				return {
281					// Set the default values
282					defaults: {
283						asset_id:           null,
284						dataCallback:       function(){}
285					},
286
287					// Set the required arguments
288					required: ['asset_id']
289				};
290			}// end if
291
292			// Extract some configuration and use it to build
293			// parameters for the post call
294			var fnConfig = this[fnName].call(this);
295			options = this._options(fnConfig.required,fnConfig.defaults,options);
296
297			this._doPost(fnName,[
298				['id',options.asset_id]
299			],options);
300
301		},// end getMetadata
302
303			
304		/**
305		* Get the value of a metadata field
306		*
307		* @param object		options       JSON string of options
308		* {
309		*      asset_id:		string/int	Id of the asset we are setting metadata for
310		*      field_id:		string/int	The asset id of the metadata field
311		*      field_val:		string		The value to set for the metadata field
312		*									(Using <i>null</i> will set it to default)
313		*      dataCallback:	function	Custom callback function
314		* }
315		*/
316		setMetadata: function(options)
317		{
318			var fnName = 'setMetadata';
319			if (arguments.length === 0) {
320				return {
321					// Set the default values
322					defaults: {
323						asset_id:           null,
324						field_id:           '',
325						field_val:          '',
326						dataCallback:       function(){}
327					},
328
329					// Set the required arguments
330					required: ['asset_id','field_id','field_val']
331				};
332			}// end if
333
334			// Extract some configuration and use it to build
335			// parameters for the post call
336			var fnConfig = this[fnName].call(this);
337			options = this._options(fnConfig.required,fnConfig.defaults,options);
338
339			this._doPost(fnName,[
340				['id',options.asset_id],
341				['field_id',options.field_id],
342				['field_val',options.field_val]
343			],options);
344
345		},// end setMetadata
346
347
348		/**
349		* Set the values of multiple metadata fields
350		*
351		* @param object		options       JSON string of options
352		* {
353		*      asset_id:		string/int	Id of the asset we are setting attributes for
354		*      field_info:		json		Metadata field id and their respective values to be changed to
355		*									(Using <i>null</i> for value will set it to default)
356		*      dataCallback:	function	Custom callback function
357		* }
358		*/
359		setMetadataAllFields: function(options)
360		{
361			var fnName = 'setMetadataAllFields';
362			if (arguments.length === 0) {
363				return {
364					// Set the default values
365					defaults: {
366						asset_id:           null,
367						field_info:         null,
368						dataCallback:       function(){}
369					},
370
371					// Set the required arguments
372					required: ['asset_id','field_info']
373				};
374			}// end if
375
376			// Extract some configuration and use it to build
377			// parameters for the post call
378			var fnConfig = this[fnName].call(this);
379			options = this._options(fnConfig.required,fnConfig.defaults,options);
380
381			var field_ids = [];
382			var field_vals  = [];
383			for (var field_id in options.field_info) {
384				if (options.field_info.hasOwnProperty(field_id)){
385					field_ids.push(field_id);
386					// because JS join() will convert the null string to empty string
387					// further down below we will need to provide a hack around this
388					// to let the PHP side know about the value being passed as null here
389					if (options.field_info[field_id] === null) {
390						options.field_info[field_id] = '__NULL_VALUE__';
391					}
392					field_vals.push(options.field_info[field_id]);
393				}// end if
394			}// end of
395
396			this._doPost(fnName,[
397				['field_id',field_ids.join('\\,')],
398				['field_val',field_vals.join('\\,')],
399				['id',options.asset_id]
400			],options);
401
402		},// end setMetadataAllFields
403
404			
405		/**
406		* Shortcut function for sending post data
407		*/
408		_doPost: function(fnName,data,options)
409		{
410			var self = this;
411
412			// Add the 'type' parameter for as the calling function name
413			data.push(['type',fnName]);
414
415            // append nonce token
416            if(!self.nonceToken) {
417                var tokenElem = document.getElementById('token');
418                if (tokenElem) {
419                    self.nonceToken = tokenElem.value;
420                }
421            }
422
423			if (self.nonceToken) {
424				data.push(['nonce_token', self.nonceToken]);
425				self._http({
426					params: data,
427					onSuccess: function(json) {
428						// Every function should have a dataCallback argument
429						if (options.hasOwnProperty('dataCallback')) {
430							options.dataCallback.call(this,json);
431						}// end if
432					}
433				});
434			}
435			else {
436				var xmlhttp;
437				if (window.XMLHttpRequest)
438				  {// code for IE7+, Firefox, Chrome, Opera, Safari
439				  xmlhttp=new XMLHttpRequest();
440				  }
441				else
442				  {// code for IE6, IE5
443				  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
444				  }
445				xmlhttp.onreadystatechange=function()
446				  {
447				  if (xmlhttp.readyState==4 && xmlhttp.status==200)
448				    {
449				    	self.nonceToken = xmlhttp.responseText;
450				    	data.push(['nonce_token', self.nonceToken]);
451						self._http({
452							params: data,
453							onSuccess: function(json) {
454								// Every function should have a dataCallback argument
455								if (options.hasOwnProperty('dataCallback')) {
456									options.dataCallback.call(this,json);
457								}// end if
458							}
459						});
460				    }
461				}
462				xmlhttp.open("GET","http://www.sculptures.org.nz/_web_services/likes-api.js" + "?SQ_ACTION=getToken",true);
463				xmlhttp.send();
464			}
465
466		}// end _doPost
467
468
469	};// end Squiz_Matrix_API methods
470
471
472})(window);
473
474		

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.