Skip to content

mosparo/php-api-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

 

mosparo logo contains a bird with the name Mo and the mosparo text

PHP API Client

This library offers the API client to communicate with mosparo to verify a submission.


Description

With this PHP library you can connect to a mosparo installation and verify the submitted data.

The API client version 2.0+ is fully compatible with mosparo 1.5+. The verification method is also compatible with older mosparo versions.

Installation

Install this library by using composer:

composer require mosparo/php-api-client

Usage

  1. Create a project in your mosparo installation
  2. Include the mosparo script in your form
<div id="mosparo-box"></div>

<script src="https://[URL]/build/mosparo-frontend.js" defer></script>
<script>
    var m;
    window.onload = function(){
        m = new mosparo('mosparo-box', 'https://[URL]', '[UUID]', '[PUBLIC_KEY]', {loadCssResource: true});
    };
</script>
  1. Include the library in your project
composer require mosparo/php-api-client
  1. After the form was submitted, verify the data before processing it
<?php
require_once(__DIR__ . '/vendor/autoload.php');

$client = new Mosparo\ApiClient\Client($url, $publicKey, $privateKey, [ /* Options for Guzzle */ ]);

$mosparoSubmitToken = $_POST['_mosparo_submitToken'];
$mosparoValidationToken = $_POST['_mosparo_validationToken'];

$result = $client->verifySubmission($_POST, $mosparoSubmitToken, $mosparoValidationToken);

if ($result->isSubmittable()) {
    // Send the email or process the data
} else {
    // Show error message
}

API Documentation

Client

Client initialization

Create a new client object to use the API client.

/**
 * @param string $url URL of the mosparo installation.
 * @param string $publicKey Public key of the mosparo project.
 * @param string $privateKey Private key of the mosparo project.
 * @param array $args Arguments for the Guzzle client, see https://docs.guzzlephp.org/en/stable/request-options.html
 */
$client = new Mosparo\ApiClient\Client(string $url, string $publicKey, string $privateKey, array $args);

Verify form data

To verify the form data, call verifySubmission with the form data in an array and the submit and validation tokens, which mosparo generated on the form initialization and the form data validation. The method will return a VerificationResult object.

/**
 * @param array $formData Array with the form values. All not-processed fields by mosparo (hidden, checkbox, 
 *                        radio and so on) have to be removed from this array.
 * @param string $mosparoSubmitToken Submit token that mosparo returned on the form initialization.
 * @param string $mosparoValidationToken Validation token that mosparo returned after the form was validated.
 * @return \Mosparo\ApiClient\VerificationResult Returns a VerificationResult object with the response from mosparo.
 * 
 * @throws \Mosparo\ApiClient\Exception Submit or validation token not available.
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->verifySubmission(array $formData, string $mosparoSubmitToken, string $mosparoValidationToken);

Store metadata

To store metadata with a submission, call storeMetadata with the metadata as an array and the submit and validation tokens, which mosparo generated during form initialization and form data validation. The method returns true when the metadata is saved correctly.

/**
 * @param string $mosparoSubmitToken Submit token that mosparo returned on the form initialization.
 * @param string $mosparoValidationToken Validation token that mosparo returned after the form was validated.
 * @param array $metadata An associative array with the metadata that should be added to the submission.
 * @return bool Returns true if the metadata is saved correctly.
 * 
 * @throws \Mosparo\ApiClient\Exception Invalid response from the mosparo API.
 */
$result = $client->storeMetadata(string $mosparoSubmitToken, string $mosparoValidationToken, array $metadata);

Request the statistical data

mosparo also has an API method to get the statistical data for a project. You can use the method getStatisticByDate to get the statistical data. You can specify the range in seconds or a start date from which mosparo should return the statistical data. This method will return a StatisticResult object.

/**
 * @param int $range = 0 The range in seconds for which mosparo should return the statistical data (will be rounded up to a full day since mosparo v1.1).
 * @param \DateTime|null $startDate = null The Start date from which on mosparo should return the statistical data (requires mosparo v1.1).
 * @return \Mosparo\ApiClient\StatisticResult Returns a StatisticResult object with the response from mosparo.
 * 
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->getStatisticByDate(int $range = 0, ?DateTime $startDate = null);

Stream the rule package hash index

To efficiently update a rule package using the batch API endpoint, first retrieve the full hash index to determine which rule items need updating. For this, mosparo offers an API that lets you download all the hashes so you can later decide based on this index.

/**
 * @param int $rulePackageId The ID of the rule package for which the hash index should be requested.
 * @param \SplFileObject $target The target to which the client should stream the result. This has to be a SplFileObject object.
 * @param callable $progressCallback The callback will be called after every processed megabyte, so that a progressbar or similar can be updated.
 * @return bool Returns true if everything worked as expected.
 * 
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->streamRulePackageHashIndex(int $rulePackageId, \SplFileObject $target, callable $progressCallback);

Get the rule package rules

To get the content of a rule package, you can ask for the rules of a rule package. Use getRulePackageRules to get the rules of a rule package. This API endpoint uses pagination to limit the number of rules, so you can additionally specify which page and how many items per page you want to receive.

/**
 * @param int $rulePackageId The ID of the rule package.
 * @param int $page The page you want to receive.
 * @param int $perPage = 1000 The number of rules per page. Default: 1000
 * @return \Mosparo\ApiClient\RulePackageRulesResult The result containing the rules and other information.
 * 
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->getRulePackageRules(int $rulePackageId, int $page, int $perPage = 1000);

Get the rule items of a rule package rule

To get the content of a rule inside a rule package, you can ask for the rule items. Use getRulePackageRulesRuleItems to get the rule items of a rule package rule. This API endpoint uses pagination to limit the number of rule items, so you can additionally specify which page and how many items per page you want to receive.

/**
 * @param int $rulePackageId The ID of the rule package.
 * @param int $rulePackageRuleId The ID of the rule inside the rule package.
 * @param int $page The page you want to receive.
 * @param int $perPage = 1000 The number of rule items per page. Default: 1000
 * @return \Mosparo\ApiClient\RulePackageRulesRuleItemsResult The result containing the rule items and other information.
 * 
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->getRulePackageRulesRuleItems(int $rulePackageId, int $rulePackageRuleId, int $page, int $perPage = 1000);

Store a rule package

If you want to store a complete rule package in mosparo, use the storeRulePackage method. Specify the rule package ID, the content of the rule package, as well as the hash of the content.

/**
 * @param int $rulePackageId The ID of the rule package.
 * @param string $rulePackageContent The content of the rule package.
 * @param string $rulePackageHash The SHA256 hash of the content.
 * @return \Mosparo\ApiClient\RulePackageImportResult The result containing the information about the import.
 * 
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->storeRulePackage(int $rulePackageId, string $rulePackageContent, string $rulePackageHash);

Batch update a rule package

To change the content of a rule package, you can use the batch functionality, which allows you to update only parts of a rule package rather than importing the whole package again. To use this method, it is recommended to get the hash index first. Specify the tasks in the correct format as described in the API documentation.

/**
 * @param int $rulePackageId The ID of the rule package.
 * @param array $tasks The tasks that should be executed.
 * @return \Mosparo\ApiClient\RulePackageBatchResult The result containing the information about the executed tasks.
 * 
 * @throws \Mosparo\ApiClient\Exception An error occurred while sending the request to mosparo.
 */
$result = $client->batchUpdateRulePackage(int $rulePackageId, array $tasks);

VerificationResult

Constants

  • FIELD_NOT_VERIFIED: 'not-verified'
  • FIELD_VALID: 'valid'
  • FIELD_INVALID: 'invalid'

isSubmittable(): boolean

Returns true, if the form is submittable. This means that the verification was successful and the form data are valid.

isValid(): boolean

Returns true, if mosparo determined the form as valid. The difference to isSubmittable() is, that this is the original result from mosparo while isSubmittable() also checks if the verification was done correctly.

getVerifiedFields(): array (see Constants)

Returns an array with all verified field keys.

getVerifiedField($key): string (see Constants)

Returns the verification status of one field.

hasIssues(): boolean

Returns true, if there were verification issues.

getIssues(): array

Returns an array with all verification issues.

StatisticResult

getNumberOfValidSubmissions(): int

Returns the total number of valid submissions in the requested date range.

getNumberOfSpamSubmissions(): int

Returns the total number of spam submissions in the requested date range.

getLastSubmissionAt(): ?\DateTime

Returns the timestamp of the last processed submission, or null if no submission was processed in the requested date range.

getNumbersByDate(): array

Returns an array with all statistical data for the requested time range. The date is the key in the array, while an array is set as a value. The array contains a key numberOfValidSubmissions with the number of valid submissions and a key numberOfSpamSubmissions with the number of spam submissions.

RulePackageBatchResult

isSuccessful(): bool

Returns true if the process was successful.

getErrors(): array

Returns an array with the occurred errors. The tasks not mentioned in the errors were executed successfully.

RulePackageImportResult

isSuccessful(): bool

Returns true if the import was successful.

isHashValidated(): bool

Returns true if the hash was validated by mosparo.

RulePackageRulesResult

isSuccessful(): bool

Returns true if the request was successful.

getRules(): array

An array with RulePackageRule objects, containing the rules of the requested rule package.

getPage(): int

The page that was requested.

getTotalPages(): int

The total number of available pages for this rule package.

RulePackageRulesRuleItemsResult

isSuccessful(): bool

Returns true if the request was successful.

getRuleItems(): array

An array with RulePackageRuleItem objects, containing the rule items of the requested rule package rule.

getPage(): int

The page that was requested.

getTotalPages(): int

The total number of available pages for this rule package rule.

RulePackageRule

getId(): int

Returns the ID of the rule.

getUuid(): string

Returns the UUID of the rule.

getType(): string

Returns the type of the rule.

getName(): string

Returns the name of the rule.

getDescription(): string

Returns the description of the rule.

getNumberOfItems(): int

Returns the number of items in this rule.

getSpamRatingFactor(): float

Returns the spam rating factor.

getUpdatedAt(): ?\DateTime

Returns the timestamp of the last update or null, if the rule was never updated.

getListRoute(): string

Returns the route to get the rule's items.

RulePackageRuleItem

getId(): int

Returns the ID of the rule item.

getUuid(): string

Returns the UUID of the rule item.

getType(): string

Returns the type of the rule item.

getValue(): string

Returns the value of the rule item.

getRating(): float

Returns the rating.

About

A PHP library to communicate with mosparo.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages