/*©agpl************************************************************************* * * * This file is part of FRIEND UNIFYING PLATFORM. * * Copyright (c) Friend Software Labs AS. All rights reserved. * * * * Licensed under the Source EULA. Please refer to the copy of the GNU Affero * * General Public License, found in the file license_agpl.txt. * * * *****************************************************************************©*/ if( window.friendUP ) throw new Error( 'namespace.js - friendUP namespace is already defined, make sure this is the first script executed' ); window.friendUP = { app : {}, component : {}, gui : {}, io : {}, media : {}, system : {}, tool : {}, util : {} }; window.Friend = window.Friend || {}; /*©agpl************************************************************************* * * * This file is part of FRIEND UNIFYING PLATFORM. * * Copyright (c) Friend Software Labs AS. All rights reserved. * * * * Licensed under the Source EULA. Please refer to the copy of the GNU Affero * * General Public License, found in the file license_agpl.txt. * * * *****************************************************************************©*/ /** @file * * Friend New API definition - Low level * * This source must be the second after namespace.js! * * @author FL (Francois Lionet) * @date first pushed on 19/08/2018 */ // Root of the API Friend = window.Friend || {}; // Current versions of the API Friend.APIVersion = '1.2'; Friend.APIVersionMinimal = '1.2'; // We might want to change that one day when the number of versions gets too high // but we should not really... // API Variables Friend.APIDefinition = {}; Friend.NORETURN = 'noReturn'; Friend.ERROR = 'error'; // Friend API engine - only possible in Javascript! (Y) :) ////////////////////////////////////////////////////////////////////////////// // To be called at first pass of Javascript Friend.addToAPI = function( functionPath, argumentNames, properties, parentClass ) { var definition = {}; definition.functionName = functionPath.substring( functionPath.lastIndexOf( '.' ) + 1 ); definition.functionPath = functionPath; definition.argumentNames = argumentNames; // Can be ommited definition.properties = properties; if ( !parentClass ) parentClass = Friend; // Find the position of the callback definition.callbackPosition = -1; for ( var n = 0; n < argumentNames.length; n++ ) { if ( argumentNames[ n ] == 'callback' ) { definition.callbackPosition = n; break; } } definition.numberOfArguments = argumentNames.length; definition.isDirect = ( properties.tags.indexOf( '#direct' ) >= 0 ); definition.isCallback = ( properties.tags.indexOf( '#callback' ) >= 0 ); // Find the function var functionClass; if ( properties.redirection ) { functionClass = GetClass( properties.redirection.functionPath, parentClass ); } else { functionClass = GetClass( functionPath, parentClass ); } // Add to API! if ( functionClass ) { definition.klass = functionClass; parentClass.APIDefinition[ functionPath ] = definition; return true; } console.log( 'ERROR - API function not found: ' + functionPath ); return 'ERROR - API function not found: ' + functionPath; }; Friend.removeFromAPI = function( functionPath ) { if ( Friend.APIDefinition[ functionPath ] ) { Friend.APIDefinition = Friend.Utilities.cleanArray( Friend.APIDefinition, Friend.APIDefinition[ functionPath ] ); return true; } console.log( 'ERROR - API function not found: ' + functionPath ); return false; } // Create a sourcecode with the API definition, to add to your view/iFrame Friend.getAPI = function( applicationId, options, callback, extra ) { var source = ""; source += "/*******************************************************************************\n"; source += "* *\n"; source += "* Friend Unifying Platform *\n"; source += "* ------------------------ *\n"; source += "* *\n"; source += "* Copyright 2014-2017 Friend Software Labs AS, all rights reserved. *\n"; source += "* Hillevaagsveien 14, 4016 Stavanger, Norway *\n"; source += "* Tel.: (+47) 40 72 96 56 *\n"; source += "* Mail: info@friendos.com *\n"; source += "* *\n"; source += "********************************************************************************/\n"; source += "/** @file\n"; source += "*\n"; source += "* Friend API - Application level\n"; source += "*/\n"; // Get the good version... var version = Friend.APIVersion; if ( options.version ) version = options.version; var pos = version.indexOf( '.' ); if ( Friend.APIVersion == version ) { // Simple, use the current API doExport( Friend.APIDefinition, Friend ); } else { // Convert dots into underscore while ( pos >= 0 ) { version = version.substring( 0, pos ) + '_' + version.substring( pos + 1 ); pos = version.indexOf( '.', pos + 1 ); }; // Load file from server Friend.DOS.loadFile( 'System:js/api/apiv' + version + '.js', {}, function( response, data, extra ) { if ( !response ) { callback( false, 'ERROR - API not found.', extra ); } // Creates the APIDefinition from the code var fakeFriend = { Friend: {} }; var scanner = new Friend.Utilities.TextScanner( data, {} ); var definition = {}; var line = scanner.getLine( { next: true } ); while( line ) { if ( line.indexOf( 'Friend.' ) == 0 ) { // Direct source? if ( line.indexOf( 'Friend.APIDirectSources' ) == 0 ) { var pos = line.indexOf( 'System:' ); if ( pos ) { var end = line.indexOf( "'", pos ); fakeFriend.APIDirectSource.push( line.substring( start, end ) ); } } else if ( line.indexOf( 'Friend.addToAPI' ) == 0 ) { // Function definitions var parser = new Friend.Utilities.CodeParser( line, {} ); parser.setSection( '(', ')' ); var functionPath = parser.getNextToken().value; var parameters = parser.getNextToken().value; var options = parser.GetNextToken(); var error = Friend.addToAPI( functionPath, parameters, options, fakeFriend ); if ( error ) { callback( false, error, extra ); return; } } } }; doExport( definition, fakeFriend ); } ); } function doExport( definition, parent ) { // HOGNE: We need to filter the entry based on the authorisations of the application! if ( true ) { // Only specific APIs? if ( options.APIs && options.APIs.length ) { for ( var a = 0; a < options.APIs.length; a++ ) { var api = options.APIs[ a ]; for ( var d = 0; d < parent.APIDefinition.length; d++ ) { var definition = parent.APIDefinition[ d ]; if ( definition.indexOf( api ) == 0 ) { doExportDefinition( definition, parent ); } } } } else { // All the APIs for ( var d in Friend.APIDefinition ) { doExportDefinition( Friend.APIDefinition[ d ], parent ); } } // Add the functions defined in plain in the sourcecode -> duplication up and down... if ( !options.noDirectCode ) { for ( var s = 0; s < parent.APIDirectSources.length; s++ ) { var path = parent.APIDirectSources[ s ]; Friend.DOS.loadFile( path, {}, function( response, code, extra ) { if ( response ) { var markerStart = 'APIDIRECTCODESTART'; var markerEnd = 'APIDIRECTCODEEND'; var start = code.indexOf( markerStart ); if ( start >= 0 ) { var end = code.indexOf( markerEnd ); if ( end >= 0 ) { code = code.substring( start + markerStart.length, end ); source += code; } } callback( true, source, extra ); } else { callback( false, 'ERROR - Cannot load source from server.', extra ); console.log( 'ERROR - Cannot load source from server: ' + path ); } } ); } } else { callback( true, source, extra ); } } } function doExportDefinition( definition ) { // Check that the class is already defined var dot = definition.functionPath.indexOf( '.' ); while ( dot >= 0 ) { var name = definition.functionPath.substring( 0, dot ); if ( source.indexOf( name + '.' ) < 0 ) { source += name + ' = window.' + name + ' || {};\n'; } dot = definition.functionPath.indexOf( '.', dot + 1 ); } // Call the API! source += definition.functionPath + ' = function( '; for ( var p = 0; p < definition.argumentNames.length; p++ ) { if ( p > 0 ) source += ', '; source += definition.argumentNames[ p ]; } source += ' )\n'; source += '{\n'; source += ' CallLowLevelAPI( arguments, '; source += "'" + definition.functionPath + "', [ "; for ( p = 0; p < definition.argumentNames.length; p++ ) { if ( p > 0 ) source += ', '; source += "'" + definition.argumentNames[ p ] + "'"; } source += " ],{ tags: '" + definition.properties.tags + "' } );\n"; source += '};\n'; } } // Called by APIWrapper.js Friend.callAPIFunction = function( msg ) { // Get information from message var messageInfo = {}; if( msg.applicationId ) { messageInfo.view = GetContentWindowByAppMessage( findApplication( msg.applicationId ), msg ); messageInfo.applicationId = msg.applicationId; if( msg.applicationName ) messageInfo.applicationName = msg.applicationName; messageInfo.viewId = msg.viewId; messageInfo.callback = msg.callback; } // Call the function var definition = Friend.APIDefinition[ msg.method ]; if( definition ) { // Replace callback by local callback if( definition.callbackPosition >= 0 ) msg.arguments[ definition.callbackPosition ] = thisCallback; // Up to 10 arguments (Javascript -> pass more in objects) switch( definition.numberOfArguments ) { case 0: ret = definition.klass(); break; case 1: ret = definition.klass( msg.arguments[ 0 ] ); break; case 2: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ] ); break; case 3: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ] ); break; case 4: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ] ); break; case 5: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ], msg.arguments[ 4 ] ); break; case 6: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ], msg.arguments[ 4 ], msg.arguments[ 5 ] ); break; case 7: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ], msg.arguments[ 4 ], msg.arguments[ 5 ], msg.arguments[ 6 ] ); break; case 8: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ], msg.arguments[ 4 ], msg.arguments[ 5 ], msg.arguments[ 6 ], msg.arguments[ 7 ] ); break; case 9: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ], msg.arguments[ 4 ], msg.arguments[ 5 ], msg.arguments[ 6 ], msg.arguments[ 7 ], msg.arguments[ 8 ] ); break; case 10: ret = definition.klass( msg.arguments[ 0 ], msg.arguments[ 1 ], msg.arguments[ 2 ], msg.arguments[ 3 ], msg.arguments[ 4 ], msg.arguments[ 5 ], msg.arguments[ 6 ], msg.arguments[ 7 ], msg.arguments[ 8 ], msg.arguments[ 9 ] ); break; } // If value is by return, send the message back... if( definition.isDirect ) { // Except for double access functions, when it is returned by callback. if( ret != Friend.NORETURN ) { var nmsg = { command: definition.functionName + 'Response', response: ret == Friend.ERROR ? false : true, data: ret, extra: msg.extra, isFriendAPI: true }; sendItBack( nmsg ); } } function thisCallback( response, data, extra ) { var nmsg = { command: definition.functionName + 'Response', response: response, data: data, extra: extra, isFriendAPI: true }; sendItBack( nmsg ); } } else { // API Function not found var functionName = msg.method.substring( msg.method.lastIndexOf( '.' ) + 1 ); var nmsg = { command: functionName + 'Response', response: false, data: { error: 'ERROR - API function not found.' }, extra: false, isFriendAPI: true }; sendItBack( nmsg ); } function sendItBack( message ) { if ( typeof messageInfo.callback == 'function' ) { messageInfo.callback( message ); return; } if ( messageInfo.view ) { if ( typeof messageInfo.callback == 'string' ) { message.type = 'callback'; message.callback = messageInfo.callback; } message.applicationId = messageInfo.applicationId; message.viewId = messageInfo.viewId; messageInfo.view.postMessage( JSON.stringify( message ), '*' ); } } }; GetClass = function( source, root ) { var start = 0; var end = source.indexOf( '.' ); if ( end < 0 ) end = source.length; var klass = window[ source.substring( start, end ) ]; if ( typeof klass == 'undefined' ) return null; while( end < source.length ) { start = end + 1; end = source.indexOf( '.', start ), source.length; if ( end < 0 ) end = source.length; klass = klass[ source.substring( start, end ) ]; if ( typeof klass == 'undefined' ) return null; }; return klass; }; // Returns the documentation about this function... Friend.getFunctionDocumentation = function( functionPath, options, callback, extra ) { }; Friend.addToAPI( 'Friend.getAPI', [ 'applicationId', 'options', 'callback', 'extra' ], { tags: '#callback ' } ); Friend.addToAPI( 'Friend.getFunctionDocumenation', [ 'functionPath', 'options', 'callback', 'extra' ], { tags: '#direct #callback ' } ); /* json2.js 2013-05-26 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /*©agpl************************************************************************* * * * This file is part of FRIEND UNIFYING PLATFORM. * * Copyright (c) Friend Software Labs AS. All rights reserved. * * * * Licensed under the Source EULA. Please refer to the copy of the GNU Affero * * General Public License, found in the file license_agpl.txt. * * * *****************************************************************************©*/ // We need friend! Friend = window.Friend || {}; // Get elements or an element by id ge = function( el ) { switch( typeof ( el ) ) { case 'string': if( el.substr ( 0, 1 ) == '#' ) return document.getElementById( el.substr ( 1, el.length - 1 ) ); else if( el.substr ( 0, 1 ) == '.' ) { var elements = document.getElementsByTagName( '*' ); var out = []; var cl = el.split( '.' ).join( '' ); for( var a = 0; a < elements.length; a++ ) { if( !elements[a].className.split ) continue; var classes = elements[a].className.split( ' ' ); for( var b = 0; b < classes.length; b++ ) { if( classes[b] == cl ) { out.push( elements[a] ); break; } } } return out; } return document.getElementById( el ); case 'array': var r = []; for( var a in el ) { var t = document.getElementById( el[a] ); if( t ) r.push( t ); } return r; case 'object': if( el.nodeName ) return el; return false; default: return false; } } // Deep clone an element function deepClone( ele ) { var obj = ele.cloneNode(); // Get objects and functions for( var a in ele ) { switch( a ) { case 'onclick': case 'command': case 'name': case 'items': case 'innerHMTL': case 'touchend': case 'onmouseup': case 'onmousedown': case 'ontouchstart': case 'ontouchend': case 'disabled': obj[a] = ele[a]; break; } } // Get attributes var supported = [ 'name', 'disabled', 'divider' ]; for( var a = 0; a < supported.length; a++ ) { if( ele.getAttribute ) { var v = ele.getAttribute( supported[ a ] ); if( v ) obj.setAttribute( supported[ a ], v ); } } // Get childnodes recursively if( ele.childNodes ) { for( var a = 0; a < ele.childNodes.length; a++ ) { var d = deepClone( ele.childNodes[ a ] ); obj.appendChild( d ); } } // Return clone return obj; } // var i18n_translations = new Array (); var SEPARATOR = ''; // Get an element by id function Ge ( ele ) { var e = document.getElementById ( ele ); if ( e ) return e; return false; } // Get elements by name function GeByName ( nm, el ) { var out = new Array (); if ( !el ) el = document; var eles = el.getElementsByTagName ( '*' ); for ( var a = 0; a < eles.length; a++ ) if ( eles[a].name == nm ) out.push ( eles[a] ); return out.length == 1 ? out[0] : out; } function GetElementTop ( ele ) { var top = 0; do { var t = parseInt ( ele.offsetTop ); if ( !isNaN ( t ) && t >= 0 ) top += t; ele = ele.offsetParent; } while ( ele && ele != document.body ) return top; } function GetElementLeft ( ele ) { var left = 0; do { var t = parseInt ( ele.offsetLeft ); if ( !isNaN ( t ) && t >= 0 ) left += t; ele = ele.offsetParent; } while ( ele && ele != document.body ) return left; } // See if an element has a class function HasClass( ele, className ) { var cls = ele.className ? ele.className.split( ' ' ) : false; if ( !cls ) return false; for ( var a = 0; a < cls.length; a++ ) if ( cls[a] == className ) return true; return false; } // Get elements by class name function GeByClass ( nm, el ) { var out = new Array (); var eles = document.getElementsByTagName ( '*' ); for ( var a = 0; a < eles.length; a++ ) { if ( eles[a].className == nm ) { var belongstoel = false; if ( el ) { var e = eles[a]; while ( e != document.body ) { if ( e == el ) { belongstoel = true; break; } e = e.parentNode; } } else belongstoel = true; if ( belongstoel ) out.push ( eles[a] ); } } return out.length == 1 ? out[0] : out; } var _is_touch_device; function isTouchDevice() { if( _is_touch_device === false || _is_touch_device === true ) return _is_touch_device; try { document.createEvent( 'TouchEvent' ); window.isTablet = true; _is_touch_device = true; return true; } catch ( e ) { _is_touch_device = false; return false; } } isTouchDevice(); // Generate a unique id function UniqueId () { var el; do { el = 'element_' + Math.floor ( (Math.random() * 1000) + (Math.random() * 1000) ); } while ( Ge ( el ) ); return el; } function UniqueHash( str ) { if( !str ) str = Math.random() + '' + Math.random() + '' + Math.random(); else str = str + ''; if( window.SHA256 ) { return SHA256( str ); } return str; } // set a cookie function SetCookie( key, value, expiry ) { try { var t = new Date (); if ( !expiry ) expiry = 1; expiry = new Date( t.getTime() + ( expiry*1000*60*60*24 ) ); document.cookie = key + '=' + escape ( value ) + ';expires='+expiry.toGMTString(); return; } catch( e ) { } return false; } function DelCookie ( key ) { document.cookie = key + '=;'; } // get a cookie function GetCookie( key ) { if ( !key ) return false; try { var c = document.cookie.split ( ';' ); for ( var a = 0; a < c.length; a++ ) { c[a] = c[a].split ( /^\s+|\s+$/g ).join ( '' ); // rm whitespace var v = c[a].split ( '=' ); if ( v[0] == key ) { return unescape ( v[1] ); } } return false; } catch( e ) { } return false; } // Set opacity on an element function SetOpacity( element, opacity ) { if ( !element ) return; if ( navigator.userAgent.indexOf ( 'MSIE' ) >= 0 && navigator.userAgent.indexOf ( 'MSIE 9' ) < 0 && navigator.userAgent.indexOf ( 'MSIE 10' ) < 0 ) { if ( opacity == 1 ) element.style.filter = null; else element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity='+Math.round(opacity*100)+')'; } else element.style.opacity = opacity; } // Get data through an ajax query function GetByAjax( url, execfunc ) { var client = new XMLHttpRequest (); client.loadfunc = execfunc ? execfunc : false; client.onreadystatechange = function () { if ( this.readyState == 4 ) { if ( this.loadfunc != false ) this.loadfunc (); } } client.open ( 'POST', url ); client.send (); } function hideKeyboard() { if( !isMobile && !isTablet ) return; setTimeout( function() { var field = document.createElement( 'input' ); field.setAttribute( 'type', 'text' ); field.setAttribute( 'style', 'position: absolute; top: 0px; opacity: 0; -webkit-user-modify: read-write-plaintext-only; left: 0px;' ); document.body.appendChild( field ); field.onfocus = function() { setTimeout( function() { field.setAttribute('style', 'display:none;'); setTimeout( function() { document.body.removeChild( field ); document.body.focus(); }, 14 ); }, 200); }; field.focus(); setTimeout( function() { if( field.parentNode == document.body ) document.body.removeChild( field ); }, 500 ); }, 50 ); } // Make sure the objs are in array form function MakeArray ( objs ) { if ( objs.length >= 1 ) return objs; return [ objs ]; } /** * HTML Entity map */ Friend.HTMLEntities = { "'": "'", "<": "<", ">": ">", " ": " ", "¡": "¡", "¢": "¢", "£": "£", "¤": "¤", "¥": "¥", "¦": "¦", "§": "§", "¨": "¨", "©": "©", "ª": "ª", "«": "«", "¬": "¬", "®": "®", "¯": "¯", "°": "°", "±": "±", "²": "²", "³": "³", "´": "´", "µ": "µ", "¶": "¶", "·": "·", "¸": "¸", "¹": "¹", "º": "º", "»": "»", "¼": "¼", "½": "½", "¾": "¾", "¿": "¿", "À": "À", "Á": "Á", "Â": "Â", "Ã": "Ã", "Ä": "Ä", "Å": "Å", "Æ": "Æ", "Ç": "Ç", "È": "È", "É": "É", "Ê": "Ê", "Ë": "Ë", "Ì": "Ì", "Í": "Í", "Î": "Î", "Ï": "Ï", "Ð": "Ð", "Ñ": "Ñ", "Ò": "Ò", "Ó": "Ó", "Ô": "Ô", "Õ": "Õ", "Ö": "Ö", "×": "×", "Ø": "Ø", "Ù": "Ù", "Ú": "Ú", "Û": "Û", "Ü": "Ü", "Ý": "Ý", "Þ": "Þ", "ß": "ß", "à": "à", "á": "á", "â": "â", "ã": "ã", "ä": "ä", "å": "å", "æ": "æ", "ç": "ç", "è": "è", "é": "é", "ê": "ê", "ë": "ë", "ì": "ì", "í": "í", "î": "î", "ï": "ï", "ð": "ð", "ñ": "ñ", "ò": "ò", "ó": "ó", "ô": "ô", "õ": "õ", "ö": "ö", "÷": "÷", "ø": "ø", "ù": "ù", "ú": "ú", "û": "û", "ü": "ü", "ý": "ý", "þ": "þ", "ÿ": "ÿ", "Œ": "Œ", "œ": "œ", "Š": "Š", "š": "š", "Ÿ": "Ÿ", "ƒ": "ƒ", "ˆ": "ˆ", "˜": "˜", "Α": "Α", "Β": "Β", "Γ": "Γ", "Δ": "Δ", "Ε": "Ε", "Ζ": "Ζ", "Η": "Η", "Θ": "Θ", "Ι": "Ι", "Κ": "Κ", "Λ": "Λ", "Μ": "Μ", "Ν": "Ν", "Ξ": "Ξ", "Ο": "Ο", "Π": "Π", "Ρ": "Ρ", "Σ": "Σ", "Τ": "Τ", "Υ": "Υ", "Φ": "Φ", "Χ": "Χ", "Ψ": "Ψ", "Ω": "Ω", "α": "α", "β": "β", "γ": "γ", "δ": "δ", "ε": "ε", "ζ": "ζ", "η": "η", "θ": "θ", "ι": "ι", "κ": "κ", "λ": "λ", "μ": "μ", "ν": "ν", "ξ": "ξ", "ο": "ο", "π": "π", "ρ": "ρ", "ς": "ς", "σ": "σ", "τ": "τ", "υ": "υ", "φ": "φ", "χ": "χ", "ψ": "ψ", "ω": "ω", "ϑ": "ϑ", "ϒ": "&Upsih;", "ϖ": "ϖ", "–": "–", "—": "—", "‘": "‘", "’": "’", "‚": "‚", "“": "“", "”": "”", "„": "„", "†": "†", "‡": "‡", "•": "•", "…": "…", "‰": "‰", "′": "′", "″": "″", "‹": "‹", "›": "›", "‾": "‾", "⁄": "⁄", "€": "€", "ℑ": "ℑ", "℘": "℘", "ℜ": "ℜ", "™": "™", "ℵ": "ℵ", "←": "←", "↑": "↑", "→": "→", "↓": "↓", "↔": "↔", "↵": "↵", "⇐": "⇐", "⇑": "&UArr;", "⇒": "⇒", "⇓": "⇓", "⇔": "⇔", "∀": "∀", "∂": "∂", "∃": "∃", "∅": "∅", "∇": "∇", "∈": "∈", "∉": "∉", "∋": "∋", "∏": "∏", "∑": "∑", "−": "−", "∗": "∗", "√": "√", "∝": "∝", "∞": "∞", "∠": "∠", "∧": "∧", "∨": "∨", "∩": "∩", "∪": "∪", "∫": "∫", "∴": "∴", "∼": "∼", "≅": "≅", "≈": "≈", "≠": "≠", "≡": "≡", "≤": "≤", "≥": "≥", "⊂": "⊂", "⊃": "⊃", "⊄": "⊄", "⊆": "⊆", "⊇": "⊇", "⊕": "⊕", "⊗": "⊗", "⊥": "⊥", "⋅": "⋅", "⌈": "⌈", "⌉": "⌉", "⌊": "⌊", "⌋": "⌋", "⟨": "〈", "⟩": "〉", "◊": "◊", "♠": "♠", "♣": "♣", "♥": "♥", "♦": "♦", "&": "&" }; /** * Encodes string with HTML entities * @param string string to be encoded */ function EntityEncode( string ) { let output = []; for( let a = string.length - 1; a >= 0; a-- ) { let k = string[a]; for( let b in Friend.HTMLEntities ) { if( b == string[a] ) { k = Friend.HTMLEntities[b]; break; } } output.push( k ); } return output.join( '' ); } /** * Decodes string with HTML entities * @param string string to be decoded */ function EntityDecode( string ) { for( let b in Friend.HTMLEntities ) { string = string.split( Friend.HTMLEntities[b] ).join( b ); } return string; } // Get a translated string function i18n( string ) { if( i18n_translations[string] ) return i18n_translations[string]; if( typeof( translations ) != 'undefined' ) if ( translations[string] ) return translations[string]; return string; } // Add translations by path function i18nAddPath( path, callback ) { var j = new cAjax(); j.open( 'get', path, true ); j.onload = function() { var s = this.responseText().split( "\n" ); for( var a = 0; a < s.length; a++ ) { var p = s[a].split( ":" ); if( Trim( p[0] ).length && Trim( p[1] ).length ) { i18n_translations[Trim( p[0] )] = Trim( p[1] ); } } if( typeof callback == 'function' ) callback(); } j.send(); } // Add translations from string function i18nAddTranslations( string ) { var s = string.split( "\n" ); for( var a = 0; a < s.length; a++ ) { var p = s[a].split( ":" ); if( Trim( p[0] ).length && Trim( p[1] ).length ) { i18n_translations[Trim( p[0] )] = Trim( p[1] ); } } } // Search and execute replacements in string (Note from FL: I'll certainly remove this later, redundant) function i18nReplaceInString( str ) { var pos = 0; while ( ( pos = str.indexOf( "{i18n_", pos ) ) >= 0 ) { var pos2 = str.indexOf( "}", pos ); if ( pos2 >=0 ) { var key = str.substring( pos + 1, pos2 - pos - 1 ); var r = i18n( key ); if ( r != key ) { str = str.substring(0, pos) + r + str.substring(pos2 + 1); } pos = pos2 + 1; } else { break; } } return str; } // Execute replacements (Note from FL: I'll certainly remove this later) function i18nReplace( data, replacements ) { var str = data ? data : this.data; if( !str ) return ''; // Array if( replacements.length && typeof( replacements[ 0 ] ) != 'undefined' ) { for( var a = 0; a < replacements.length; a++ ) { str = str.split( '{' + replacements[ a ] + '}' ).join( i18n( replacements[ a ] ) ); } } // Object? else { for( var a in replacements ) { str = str.split( '{' + a + '}' ).join( replacements[a] ); } } return str; } function i18nClearLocale() { i18n_translations = []; } // Alter Div Contents function AlterDivContents ( element, string, spd ) { if ( !spd ) spd = 10; else if ( spd > 100 ) spd = 100; // Make sure element has id if ( !element.id ) { var base = 'ele'; var sugg_id = ''; do { sugg_id = base + '_' + Math.floor ( Math.random() * 999 ); } while ( Ge ( base ) ); element.id = sigg_id; } // Reset vars element._phase = element.innerHTML.length > 0 ? 0 : 100; element._data = string; element._int = 0; element._speed = spd; element._dataShown = false; // The actual fade code element._brain = function () { if ( this._phase < 200 ) { if ( this._phase <= 100 ) SetOpacity ( this, ( 100 - this._phase ) / 100 ); else { if ( !this._dataShown ) { this._dataShown = true; this.innerHTML = this._data; } SetOpacity ( this, ( this._phase - 100 ) / 100 ); } this._phase += this._speed; } else { SetOpacity ( this, 1 ); clearInterval ( this._int ); } } // Initialize fade element._int = setInterval ( 'Ge(\''+element.id+'\')._brain()', 25 ); } function StrPad ( num, len, ch ) { var number = num + ""; var out = ''; for ( var a = 0; a < len; a++ ) { if ( len - a > number.length ) out += ch; else out += number.substr ( a - len, 1 ); } return out; } function ShowDialog ( width, url, func, endfunc ) { var d, bg; if ( !( d = Ge ( 'Dialog' ) ) ) { bg = document.createElement ( 'div' ); bg.id = 'DialogBackground'; bg.onmousedown = function () { return false; } Ge ( 'Empty' ).appendChild ( bg ); d = document.createElement ( 'div' ); d.id = 'Dialog'; Ge ( 'Empty' ).appendChild ( d ); d.bg = bg; } else bg = d.bg; bg.style.zIndex = 100; bg.style.opacity = 0; bg.style.display = ''; bg.style.background = '#000000'; bg.style.position = 'fixed'; bg.style.top = '0px'; bg.style.left = '0px'; bg.style.width = '100%'; bg.style.height = '100%'; d.style.zIndex = 101; bg.style.filter = 'alpha(opacity=60)'; d.style.opacity = 0; d.style.display = ''; d.style.boxShadow = '0px 3px 15px rgba(0,0,0,0.4)'; d.style.webkitBoxShadow = '0px 3px 15px rgba(0,0,0,0.4)'; d.style.mozBoxShadow = '0px 3px 15px rgba(0,0,0,0.4)'; d.style.width = Math.floor ( width ) + 'px'; d.style.left = Math.floor ( GetWindowWidth() >> 1 - ( width >> 1 ) ) + 'px'; d.style.top = Math.floor ( GetWindowHeight() >> 1 - ( d.offsetHeight >> 1 ) ) + 'px'; d.style.visibility = 'hidden'; d.op = 0; d.func = null; d._time = 0; d.endfunc = endfunc; document.body.style.overflow = 'hidden'; d.fadeIn = function ( init ) { if ( init ) { if ( this.interval ) clearInterval ( this.interval ); this.interval = setInterval ( 'ge(\'' + this.id + '\').fadeIn()', 25 ); this._time = 0; this.style.visibility = 'visible'; } if ( this._time == 0 ) this._time = ( new Date () ).getTime (); this.op = (( new Date () ).getTime () - this._time) / 250.0; if ( this.op >= 1 ) { this.op = 1; clearInterval ( this.interval ); if ( this.endfunc ) this.endfunc (); } SetOpacity ( this, this.op ); if ( window.addEventListener ) SetOpacity ( this.bg, this.op >> 1 ); } d.fadeOut = function ( init ) { if ( init ) { if ( this.interval ) clearInterval ( this.interval ); this.interval = setInterval ( 'ge(\'' + this.id + '\').fadeOut()', 25 ); this._time = 0; } if ( this._time == 0 ) this._time = ( new Date () ).getTime (); this.op = (( new Date () ).getTime () - this._time) / 250.0; if ( this.op >= 1 ) { this.op = 1; clearInterval ( this.interval ); if ( this.func ) this.func(); } SetOpacity ( this, 1-this.op ); SetOpacity ( this.bg, (1-this.op) >> 1 ); } GetByAjax ( url, function () { d.innerHTML = '
' + GuiCreate ( [ content[a] ] ) + ' | '; } str += '
' + headers[a] + ' | '; } str += '
' + entries[a][b] + ' | '; } sw = sw == 1 ? 2 : 1; str += '