Compilers Widget


Sphere Engine Compilers Widget allows you to run computer programs directly on the website. More precisely, it allows you to integrate the Compiler module of the Sphere Engine service via a component known as the widget, that's ready to be embedded on a website. Sphere Engine Compilers is a service that allows for remote execution of computer programs. It allows you to send a computer program written in one of many supported programming languages and execute it with the input data that you defined. Detailed information about the Sphere Engine Compilers module can be found in the introduction.

Embedding the widget is a quick and easy process allowing for the integration of any IT system with the Sphere Engine Compilers module and is recommended for both the expansion of existing projects and for projects built from scratch. An alternative method is integration using RESTful API.

The ability to embed a tool that allows you to run programs on a website can be used in many ways. For example:

  • extension of the system to conduct recruitment interviews with the ability to execute programs written by candidates,
  • supplementing e-learning programming courses with executable examples of programs,
  • enhancing the system for sharing code snippets with the ability to run the program.

Note: The above applications suggest the use of the widget to expand existing systems. Nothing prevents you from using this integration method to build systems from scratch.

See how it works

Widget embedded below allows you to familiarize yourself with its basic features.

Widget integration

Before the widget is integrated, it is necessary to create and configure it. In the widget's management panel (Menu > Compilers > Widgets), you can find the Create widget button which, when pressed, initiates the configuration process.

JavaScript

Using this method, you should attach to your code two snippets of HTML code responsible for the initialization and displaying the widget.

Widget initialization

The code responsible for widget initialization should remain embedded only once (regardless of the number of widgets displayed on the page), immediately after the <body> element.

A personalized and ready-to-use widget initialization code can be found in Menu > Compilers > Widgets > WIDGET NAME > Widget integration:

<script>SEC_HTTPS = false;
SEC_BASE = "<customized_link>"; 
(function(d, s, id){ SEC = window.SEC || (window.SEC = []);
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; 
  js.src = (SEC_HTTPS ? "https" : "http") + "://" + SEC_BASE + "/static/sdk/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);   
}(document, "script", "sphere-engine-compilers-jssdk"));
</script>
Displaying the widget

The following code should be embedded on the page in the spot envisioned for the widget:

<div class="sec-widget" data-widget="<hash>"></div>

The hash parameter which is the value of the data-widget attribute is the unique ID of the widget in the Sphere Engine system. It can be found in the Unique hash field in Menu > Compilers > Widgets > WIDGET NAME > Widget settings.

Displaying multiple widgets

Sphere Engine Compilers Widget allows you to embed multiple widgets on a single page. In the basic variant, no additional actions are required.

If you need to manipulate widget's behavior using JavaScript (see JavaScript SDK) it is necessary to identify them, which is done by means of a special identifier (marked as <id>) denoted by the data-id attribute of the div element used to embed the widget. For example:

<div id="idInHTML" data-id="<id>" class="sec-widget" data-widget="<hash>"></div>

Note: The widget is initialized automatically - directly after the page loads in the browser - even if the widget is not yet visible on the page. This makes it possible to perform operations on the widget (e.g. configuration) before displaying it.

Note: The process of loading (and, as a result, displaying) the widget begins only when the widget becomes visible on the screen (i.e. when the user scrolls the page to the widget's position). Thanks to this, the loading of other elements of the page is not blocked. This allows for the page to load faster, which is especially useful when embedding multiple widgets.

Standalone page

An alternative way to embed the widget directly on your site is to use the feature of presenting it as a "standalone page", i.e. on a separate website in the sphere-engine.com domain.

A link to a standalone page is generated when creating the widget. You will find a ready-to-use link in Menu > Compilers > Widgets > WIDGET NAME > Widget integration. It has the following structure:

https://compilers.widgets.sphere-engine.com/lp?hash=<hash>

Note: The Standalone page section of the Menu > Compilers > Widgets > WIDGET NAME > Widget integration page provides a configuration field that allows you to define (in the form of HTML code) the header of the page with the widget. You can, for example, embed your own logo in the header.

Security

Sphere Engine Compilers Widget provides mechanisms for secure integration. A fully secured widget can be embedded only on selected websites (i.e. on websites in the appropriate domain) and the communication between the client's system and the Sphere Engine system is fully reliable (i.e. unauthorized people are unable to falsify or fabricate communication).

Signature

In a production environment, we recommend using the signature security measure that fully protects the widget from unauthorized use. The signature verification feature must be enabled in advance by selecting the Secure the widget option in Menu > Compilers > Widgets > WIDGET NAME > Widget settings.

The use of a signature for communication between the client's system and the Sphere Engine system increases the security level, i.e .:

  • eliminates the possibility of unauthorized access to the widget (preventing even complex and difficult attempts at acquiring access by preparing fake HTTP requests)
  • guarantees the reliability of transmitted data.
Signature parameters

Signature generation is based on selected widget parameters and additional signature parameters:

  • hash - unique widget ID in the Sphere Engine system. It can be found in the Unique hash field in Menu > Compilers > Widgets > WIDGET NAME > Widget settings.
  • se_secret - secret key which is the basis for the security of the signature. It can be found in the Shared secret field in Menu > Compilers > Widgets > WIDGET NAME > Widget settings.
  • (optional) se_nonce - unique (for a given widget) session ID.

Important: The se_secret parameter is the basis for the security of the signature and should remain a secret. Do not send it in messages between systems.

Important: The procedure of signature generation in the client's system should not be performed on the front-end side of the application (e.g. using a JavaScript function) due to the se_secret parameter being disclosed.

Note: The use of an optional se_nonce parameter ensures that each session of the end-user (i.e., every situation in which the widget has been initialized) is a one-off. It is impossible to re-initialize the widget using the se_nonce parameter with the same value. Using this parameter provides full protection against unauthorized use of the widget.

Signature generation algorithm

The signature generation procedure can be divided into the following steps:

  • Normalization by sorting parameter names in alphabetical order. For example:
    [hash, se_secret, se_nonce] ➡ [hash, se_nonce, se_secret].
  • Conjunction by saving the parameters and their values ​​in the form of a string with the following format:
    param1=value1&param2=value2&...&paramN=valueN
    for example:
    hash=XYZ&se_nonce=12345&se_secret=CIPHER
  • Encoding to the application/x-www-form-urlencoded format using UTF-8 encoding.
  • Hashing using the SHA-256 algorithm which is available for the majority of popular programming languages ​​(in the standard library or as part of an additional library).

Pseudocode of the algorithm that generates the signature

generate_signature(params) {
    // Normalization
    params = sort(params);

    // Conjunction with Encoding
    seq = [];
    foreach p in params {
        seq += key(p) + "=" + urlencode(value(p), "utf-8"); 
    }

    // Hashing
    return sha256(join("&", seq));
}

Implementation of the algorithm that generates the signature in PHP

function generate_signature($params) {
    ksort($params);

    $seq = [];
    foreach ($params as $k => $v) {
        $seq[] = $k . "=" . urlencode($v);
    }

    return hash("sha256", implode("&", $seq));
}

Implementation of the algorithm that generates the signature in Python

def generate_signature(params):
    keys = sorted(params.keys())

    seq = []
    for k in keys :
        seq.append(k + "=" + urllib.parse.quote_plus(params[k]))

    return hashlib.sha256("&".join(seq).encode('utf-8')).hexdigest()
Attaching a signature

The signature and the values ​​of all parameters used to generate it (except the se_secret parameter which should remain secret) should be attached to the embedded widget in the form of the appropriate HTML attributes with the data- prefix:

  • data-widget for the hash parameter,
  • data-nonce for the se_nonce parameter,
  • date-signature for the signature.

An example of HTML code used to embed a widget prepared to support the signature

<div class="sec-widget" 
    data-id="widget-secured-by-signature" 
    data-widget="XYZ"  
    data-signature="e85b12137f76526ca6804625fc4e2093a0750fc6c6c158fc2be210ac5" 
    data-nonce="e9838cc0819d713b3670df7adb0079a3">
</div>

For those interested: The general scheme for securing communication with the signature assumes that both communicating parties share a secret key (so-called shared secret).
The sender uses the selected parameters of the message (or even the entire message) along with the key to create the so-called signature. The generated signature is attached to the message and sent to recipient.
The recipient, who also has access to the key, repeats the procedure of creating the signature. The received message is authorized, if the signature sent by the sender is identical to the signature generated by the recipient.

JavaScript SDK

The Sphere Engine JavaScript SDK library is loaded asynchronously. For this reason, before using the functions provided by the library, we must be sure that it has been initialized.

First, place the following snippet just after the code that initializes the Sphere Engine Compilers Widget:

<script>SEC.ready=function(e){"loading"!=document.readyState&&"interactive"!=document.readyState?e():window.addEventListener("load",e)};</script>

As a result, the initialization code should look as follows:

<script>SEC_HTTPS = false;
SEC_BASE = "<customized_link>"; 
(function(d, s, id){ SEC = window.SEC || (window.SEC = []);
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; 
  js.src = (SEC_HTTPS ? "https" : "http") + "://" + SEC_BASE + "/static/sdk/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);   
}(document, "script", "sphere-engine-compilers-jssdk"));
SEC.ready=function(e){"loading"!=document.readyState&&"interactive"!=document.readyState?e():window.addEventListener("load",e)};
</script>

The above code defines the SEC.ready() function which has been designed in a way that ensures that features that use JavaScript SDK will be used only after all the required components have been loaded.

All operations that use JavaScript SDK should be performed through the SEC.ready() function, i.e. according to the following scheme:

SEC.ready(function() {
    // SDK functions usage
});

Using the SEC.ready() function ensures that the library has been loaded, the SEC object has been initialized and no errors will occur while scripts are being executed.

Access to the widget

We gain access to the widget by using the SEC.widget() function, which based on the given widget ID (previously defined by the data-id attribute) returns the object of SECWidget class used to manage the widget. For example:

SEC.ready(function() {
    var widget = SEC.widget("widget");
    // variable "widget" is ready to use
});

The SECWidget class provides the following options for managing the widget:

  • creating a widget,
  • dedicated events allowing for handling actions performed by the widget.

Methods

The global SEC object provides public methods for managing widgets.

SEC.widget()

An object of class SECWidget, which represents the widget, is created.

Parameters

Name Type Description
id string widget's identifier placed in the HTML document ("data-id" attribute)

Returned value

An object of class SECWidget is returned.

Example

Press the button to load widget
Load widget
<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        $('#btn-load-widget').on('click', function(e) {
            e.preventDefault();
            var SECWidget = SEC.widget("example-widget");
        });
    });
</script><a href="#" id="btn-load-widget" class="btn btn-default">Load widget</a>

SECWidget.config()

Setting the widget's configuration data.

Parameters

Name Type Description
configOptions object widget's configuration options

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var SECWidget = SEC.widget("example-widget");
        SECWidget.config({
            code: {
                compiler: 28,
                source: "#!/bin/bash\n\necho test",
                input: "",
            },
            toolbar: {
                groups: [
                    {
                        id: "left",
                        buttons: [
                            {
                                id: "button",
                                icon: "code",
                                type: "primary",
                                tooltip: "My tooltip",
                                callback: function(codeEditor) {
                                    alert('You clicked the button');
                                }
                            }
                        ]    
                    }
                ]
            },
            compilers: {
                list: [11, 21, 28, 33]
            }
        });
    });
</script>

SECWidget.loadCode()

Loading data (source code, programming language, input data) to the running editor.

Parameters

Name Type Description
compiler integer programming language identifier (see list of languages)
sourceCode string program's source code
input string input data

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var sourceCode = "<?php \n\n$hi = fopen('php://stdin', \"r\");\nfscanf($hi, \"%d\", $n);\n\
fclose($hi);\n\necho 'number: ' . $n;";
        var SECWidget = SEC.widget("example-widget");
        SECWidget.loadCode(29, sourceCode, "5");
    });
</script>

SECWidget.chooseCompilers()

Selection of programming languages ​​available in the widget.

Parameters

Name Type Description
compilersList array[int] list of language identifiers (see. list of languages)

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var SECWidget = SEC.widget("example-widget");
        SECWidget.chooseCompilers([1,2]);
    });
</script>

SECWidget.events.subscribe()

Assigns a function to the event. (see list of events).

Parameters

Name Type Description
event string the name of the event to assign a function to
callback function function to be called on an event

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
SEC.ready(function() {

    var callback = function(data) {
        // Your code goes here
    };

    var SECWidget = SEC.widget("example-widget");
    SECWidget.events.subscribe('{name_of_the_event}', callback);

});
</script>

SECWidget.events.unsubscribe()

Removes a function from the list of functions assigned to the event (see list of events).

Parameters

Name Type Description
event string the name of the event to remove the function from
callback function function to be removed from the list of functions assigned to the event

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
SEC.ready(function() {

    var callback = function(data) {
        // Your code goes here
    };

    var SECWidget = SEC.widget("example-widget");
    SECWidget.events.unsubscribe('{name_of_the_event}', callback);

});
</script>

SECWidget.toolbar.createButton()

Creates a button in the widget's toolbar.

Parameters

Name Type Description
groupId string identifier of a group of buttons
buttonId string button identifier
buttonIcon string name of the icon to be placed on the button (picked from Font Awesome)
buttonType string button type (default, primary, warning, success, danger)
buttonTooltip string message displayed when hovering over the button
buttonCallback function function to be called after clicking the button (parameters: trigger, codeEditor)

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var SECWidget = SEC.widget("example-widget");
        SECWidget.toolbar.createButton(
            "middle",
            "alert-button",
            "refresh",
            "primary",
            "tooltip :)",
            function(){
                alert('button clicked');
            }
        );
    });
</script>

SECWidget.toolbar.deleteButton()

Removes the button from the widget's toolbar.

Parameters

Name Type Description
buttonId string button identifier

Example

Remove toolbar button
<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var SECWidget = SEC.widget("example-widget");
        SECWidget.toolbar.createButton(
            "middle",
            "alert-button",
            "refresh",
            "primary",
            "tooltip :)",
            function(){
                alert('button clicked');
            }
        );
        $('#btn-delete-toolbar-button').on('click', function(e) {
            e.preventDefault();
            SECWidget.toolbar.deleteButton('alert-button');
        });
    });
</script><a href="#" id="btn-delete-toolbar-button" class="pt-2">Remove toolbar button</a>

SECWidget.toolbar.createButtonGroup()

Creates a group of buttons in the widget's toolbar.

Parameters

Name Type Description
groupId string group identifier
groupButtons array array of button identifiers

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var buttons = [
            {
                "id": "button_id_1",
                "icon": "refresh",
                "type": "default",
                "tooltip": "tooltip :)",
                "callback": function(){
                    alert('button1 clicked');
                }
            },
            {
                "id": "button_id_2",
                "icon": "refresh",
                "type": "primary",
                "tooltip": "tooltip :)",
                "callback": function(){
                    alert('button2 clicked');
                }
            }
        ];
        var SECWidget = SEC.widget("example-widget");
        SECWidget.toolbar.createButtonGroup(
            "middle",
            buttons
        );
    });
</script>

SECWidget.toolbar.deleteButtonGroup()

Removes a group of buttons from the widget's toolbar.

Parameters

Name Type Description
groupId string group identifier

Example

remove toolbar button group
<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var buttons = [
            {
                "id": "button_id_1",
                "icon": "refresh",
                "type": "default",
                "tooltip": "tooltip :)",
                "callback": function(){
                    alert('button1 clicked');
                }
            },
            {
                "id": "button_id_2",
                "icon": "refresh",
                "type": "primary",
                "tooltip": "tooltip :)",
                "callback": function(){
                    alert('button2 clicked');
                }
            }
        ];
        var SECWidget = SEC.widget("example-widget");
        SECWidget.toolbar.createButtonGroup(
            "middle",
            buttons
        );
        $('#btn-remove-toolbar-button-group').on('click', function(e) {
            e.preventDefault();
            SECWidget.toolbar.deleteButtonGroup("middle");
            $(this).addClass('disabled');
        });
    });
</script><a href="#" id="btn-remove-toolbar-button-group">remove toolbar button group</a>

Events

An object of the SECWidget class has a collection of dedicated events called at specific moments of the widget's operation.

beforeSendSubmission

The event is invoked before sending a submission to the Sphere Engine system (i.e. after pressing the Submit button but before actually sending the submission).

Data sent to the callback function

An object with the following fields is sent to the callback function:

Name Type Description
submissionSource string the source code of the program sent in the submission
submissionLanguage string the programming language used to write the program
submissionInput string input data sent in the submission

The value returned by the callback function

The value returned by the callback function determines whether the submission will be sent to the Sphere Engine system:

  • true - the submission is to be sent,
  • false - the submission will be stopped from being sent.

Example

Data:
Submit submission to see the result
<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var beforeSendSubmission = function(data) {
            $('#result').html('')
                .append("> submissionLanguage: " + data.submissionLanguage + "<br><br>")
                .append("> submissionInput: <br>" + data.submissionInput + "<br><br>")
                .append("> submissionSource: <br>" + data.submissionSource + "<br><br>");
            return true;
        };
        var SECWidget = SEC.widget("example-widget");
        SECWidget.events.subscribe('beforeSendSubmission', beforeSendSubmission);
    });
</script>
Data:
<pre id="result" style="height: 300px;">Submit submission to see the result</pre>

afterSendSubmission

The event is invoked immediately after the submission has been sent to the Sphere Engine system.

Data sent to the callback function

An object with the following fields is sent to the callback function:

Name Type Description
submissionId integer submission identifier in the Sphere Engine system
submissionSource string the source code of the program sent in the submission
submissionLanguage string the programming language used to write the program
submissionInput string input data sent in the submission

Example

Data:
Submit submission to see the result
<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var afterSendSubmission = function(data) {
            $('#result').html('')
                .append("> submissionId: " + data.submissionId + "<br><br>");
        };
        var SECWidget = SEC.widget("example-widget");
        SECWidget.events.subscribe('afterSendSubmission', afterSendSubmission);
    });
</script>
Data:
<pre id="result" style="height: 100px;">Submit submission to see the result</pre>

checkStatus

The event is invoked regularly while checking the status of the submission during execution.

Data sent to the callback function

An object with the following fields is sent to the callback function:

Name Type Description
submissionId integer submission identifier in the Sphere Engine system
submissionTime integer execution time in seconds (available after execution)
submissionMemory integer memory consumption in kilobytes (available after execution)
statusNumber integer numeric value of the submission's status (see: list of statuses)
statusDescription string description of the submission's status

Example

Data:
Submit submission to see the result
<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var checkStatus = function(data) {
            $('#result')
                .append("<br><br>")
                .append("> submissionId: " + data.submissionId + "<br>")
                .append("> statusNumber: " + data.statusNumber + "<br>")
                .append("> statusDescription: " + data.statusDescription + "<br>")
                .append("> submissionMemory: " + data.submissionMemory + "<br>")
                .append("> submissionTime: " + data.submissionTime + "<br>");
            $('#result').scrollTop($('#result').prop("scrollHeight"));
        };
        var SECWidget = SEC.widget("example-widget");
        SECWidget.events.subscribe('checkStatus', checkStatus);
    });
</script>        
Data:
<pre id="result" style="height: 300px;">Submit submission to see the result</pre>

enterFullScreen

The event is invoked when the widget is switched to full screen mode.

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var enterFullScreen = function() {
            alert('enter fullscreen');
        };
        var SECWidget = SEC.widget("example-widget");
        SECWidget.events.subscribe('enterFullScreen', enterFullScreen);
    });
</script>

exitFullScreen

The event is invoked when leaving the full screen mode.

Example

<div data-id="example-widget" data-widget="{widget_hash}"></div>
<script>
    SEC.ready(function() {
        var exitFullScreen = function() {
            alert('exit fullscreen');
        };
        var SECWidget = SEC.widget("example-widget");
        SECWidget.events.subscribe('exitFullScreen', exitFullScreen);
    });
</script>