sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function handleMaintenanceMode()
{
// Authorize logged in admins on the fly
if ($this->doesCurrentUserHaveAccess())
{
return true;
}
if (Craft::$app->request->isSiteRequest && $this->settings->maintenanceModeEnabled)
{
$requestingIp =... | Restricts accessed based on authorizedIps
@return bool
@throws HttpException
@throws \yii\base\InvalidConfigException | entailment |
protected function doesCurrentUserHaveAccess()
{
// Admins have access by default
if (Craft::$app->user->getIsAdmin())
{
return true;
}
// User has the right permission
if (Craft::$app->user->checkPermission(Patrol::MAINTENANCE_MODE_BYPASS_PERMISSION))
... | Returns whether or not the current user has access during maintenance mode | entailment |
public function getRequestingIp()
{
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
return $_SERVER['HTTP_CF_CONNECTING_IP'];
}
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
return isset($_SERVER['HTTP_X_FORWARDED_FOR']);
}
elseif (isset(... | Ensures that we get the right IP address even if behind CloudFlare or most proxies
@return string | entailment |
protected function forceRedirect($redirectTo = '')
{
if (empty($redirectTo))
{
$this->runDefaultBehavior();
}
Craft::$app->response->redirect($redirectTo, $this->settings->redirectStatusCode);
} | @param string $redirectTo
@throws HttpException | entailment |
public function parseAuthorizedIps($ips)
{
$ips = trim($ips);
if (is_string($ips) && !empty($ips))
{
$ips = explode(PHP_EOL, $ips);
}
return $this->filterOutArrayValues(
$ips, function($val) {
return preg_match('/^[0-9\.\*]{5,15}$/i', $va... | Parses authorizedIps to ensure they are valid even when created from a string
@param array|string $ips
@return array | entailment |
protected function filterOutArrayValues($values = null, \Closure $filter = null, $preserveKeys = false)
{
$data = [];
if (is_array($values) && count($values))
{
foreach ($values as $key => $value)
{
$value = trim($value);
if (!empty($... | Filters out array values by using a custom filter
@param array|string|null $values
@param callable|\Closure $filter
@param bool $preserveKeys
@return array | entailment |
public function parseRestrictedAreas($areas)
{
if (is_string($areas) && !empty($areas))
{
$areas = trim($areas);
$areas = explode(PHP_EOL, $areas);
}
return $this->filterOutArrayValues(
$areas,
function($val) {
$valid =... | Parse restricted areas to ensure they are valid even when created from a string
@param array|string $areas
@return array | entailment |
public function addFunction($functionName, $callback, $timeout = null)
{
if (isset($this->functions[$functionName])) {
throw new \InvalidArgumentException("Function $functionName is already registered");
}
$this->functions[$functionName] = array('callback' => $callback);
... | @param string $functionName
@param callback $callback
@param int $timeout
@throws \InvalidArgumentException
@return self | entailment |
public function unregister($functionName)
{
if (!isset($this->functions[$functionName])) {
throw new \InvalidArgumentException("Function $functionName is not registered");
}
unset($this->functions[$functionName]);
return $this;
} | @param string
@throws \InvalidArgumentException
@return self | entailment |
protected function doWork($socket)
{
Connection::send($socket, 'grab_job');
$resp = array('function' => 'noop');
while (count($resp) && $resp['function'] == 'noop') {
$resp = Connection::blockingRead($socket);
}
if (in_array($resp['function'], array('noop', 'no_... | Listen on the socket for work.
Sends the 'grab_job' command and then listens for either the 'noop' or
the 'no_job' command to come back. If the 'job_assign' comes down the
pipe then we run that job.
@param resource $socket The socket to work on
@throws \MHlavac\Gearman\Exception
@return bool Returns true if work wa... | entailment |
public function jobStatus($numerator, $denominator)
{
Connection::send($this->conn, 'work_status', array(
'handle' => $this->handle,
'numerator' => $numerator,
'denominator' => $denominator,
));
} | Update Gearman with your job's status.
@param int $numerator The numerator (e.g. 1)
@param int $denominator The denominator (e.g. 100)
@see MHlavac\Gearman\Connection::send() | entailment |
public function attachCallback($callback, $type = self::JOB_COMPLETE)
{
if (!is_callable($callback)) {
throw new Exception('Invalid callback specified');
}
if (!isset($this->callback[$type])) {
throw new Exception('Invalid callback type specified.');
}
... | @param callback $callback
@param int $type
@throws \MHlavac\Gearman\Exception When an invalid callback or type is specified. | entailment |
public function init()
{
parent::init();
self::$plugin = $this;
$this->_setPluginComponents();
$this->_setLogging();
$this->_registerCpRoutes();
$this->_registerEventHandlers();
} | ========================================================================= | entailment |
public function doNormal($functionName, $workload, $unique = null)
{
return $this->runSingleTaskSet($this->createSet($functionName, $workload, $unique));
} | Runs a single task and returns a string representation of the result.
@param string $functionName
@param string $workload
@param string $unique
@return string | entailment |
public function doHigh($functionName, $workload, $unique = null)
{
return $this->runSingleTaskSet($this->createSet($functionName, $workload, $unique, Task::JOB_HIGH));
} | Runs a single high priority task and returns a string representation of the result.
@param string $functionName
@param string $workload
@param string $unique
@return string | entailment |
public function doLow($functionName, $workload, $unique = null)
{
return $this->runSingleTaskSet($this->createSet($functionName, $workload, $unique, Task::JOB_LOW));
} | Runs a single low priority task and returns a string representation of the result.
@param string $functionName
@param string $workload
@param string $unique
@return string | entailment |
protected function runSingleTaskSet(Set $set)
{
$this->runSet($set);
$task = current($set->tasks);
return $task->result;
} | @param Set $set
@return string | entailment |
public function doBackground($functionName, $workload, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_BACKGROUND);
$this->runSet($set);
return current($set->tasks);
} | Runs a task in the background, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param string $unique
@return Task | entailment |
public function doHighBackground($functionName, $workload, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_HIGH_BACKGROUND);
$this->runSet($set);
return current($set->tasks);
} | Runs a task in the background, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param string $unique
@return Task | entailment |
public function doLowBackground($functionName, $workload, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_LOW_BACKGROUND);
$this->runSet($set);
return current($set->tasks);
} | Runs a task in the background, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param string $unique
@return Task | entailment |
public function doEpoch($functionName, $workload, $epoch, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_EPOCH, $epoch);
$this->runSet($set);
return current($set->tasks);
} | Schedule a background task, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param int $epoch
@param string $unique
@return Task | entailment |
private function createSet($functionName, $workload, $unique = null, $type = Task::JOB_NORMAL, $epoch = 0)
{
if (null === $unique) {
$unique = $this->generateUniqueId();
}
$task = new Task($functionName, $workload, $unique, $type, $epoch);
$task->type = $type;
$s... | @param string $functionName
@param string $workload
@param string $unique
@param int $type Type of job to run task as
@param int $epoch Time of job to run at (unix timestamp)
@return Set | entailment |
protected function submitTask(Task $task)
{
switch ($task->type) {
case Task::JOB_LOW:
$type = 'submit_job_low';
break;
case Task::JOB_LOW_BACKGROUND:
$type = 'submit_job_low_bg';
break;
case Task::JOB_HIGH_BACKGROUND:
$type... | Submit a task to Gearman.
@param Task $task Task to submit to Gearman
@see \MHlavac\Gearman\Task, \MHlavac\Gearman\Client::runSet() | entailment |
public function runSet(Set $set, $timeout = null)
{
foreach ($this->getServers() as $server) {
$conn = Connection::connect($server, $timeout);
if (!Connection::isConnected($conn)) {
unset($this->servers[$server]);
continue;
}
$... | Run a set of tasks.
@param Set $set A set of tasks to run
@param int $timeout Time in seconds for the socket timeout. Max is 10 seconds
@see MHlavac\Gearman\Set, MHlavac\Gearman\Task | entailment |
protected function handleResponse($resp, $s, Set $tasks)
{
if (isset($resp['data']['handle']) &&
$resp['function'] != 'job_created') {
$task = $tasks->getTask($resp['data']['handle']);
}
switch ($resp['function']) {
case 'work_complete':
$tasks->t... | Handle the response read in.
@param array $resp The raw array response
@param resource $s The socket
@param Set $tasks The tasks being ran
@throws \MHlavac\Gearman\Exception | entailment |
public function disconnect()
{
if (!is_array($this->conn) || !count($this->conn)) {
return;
}
foreach ($this->conn as $conn) {
Connection::close($conn);
}
} | Disconnect from Gearman. | entailment |
function it_provides_access_to_error_details(){
$this->getCode()->shouldBe( 400 );
$this->getErrorMessage()->shouldBeString();
$this->getErrorMessage()->shouldBe( 'BadRequestError: "Missing personalisation: name"' );
$this->getErrors()->shouldBeArray();
$this->getErrors()[0]->shouldBeArray... | Test constructor variations | entailment |
public function sendSms( $phoneNumber, $templateId, array $personalisation = array(), $reference = '', $smsSenderId = NULL ){
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_SMS,
$this->buildSmsPayload( 'sms', $phoneNumber, $templateId, $personalisation, $reference, $smsSenderId)
... | Send an SMS message.
@param string $phoneNumber
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
public function sendEmail( $emailAddress, $templateId, array $personalisation = array(), $reference = '', $emailReplyToId = NULL ){
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_EMAIL,
$this->buildEmailPayload( 'email', $emailAddress, $templateId, $personalisation, $reference, $e... | Send an Email message.
@param string $emailAddress
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
public function sendLetter( $templateId, array $personalisation = array(), $reference = '' ){
$payload = $this->buildPayload( 'letter', '', $templateId, $personalisation, $reference );
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_LETTER,
$payload
);
} | Send a Letter
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
public function sendPrecompiledLetter( $reference, $pdf_data, $postage = NULL ){
$payload = [
'reference' => $reference,
'content' => base64_encode($pdf_data)
];
if ($postage != NULL) {
$payload['postage'] = $postage;
}
return $this->httpPost(
... | Send a precompiled letter.
Example usage: sendPrecompiledLetter($templateId, $ref, file_get_contents(<PATH TO FILE>)))
@param string $templateId
@param string $reference
@param string $pdf_data
@return array | entailment |
public function getNotification( $notificationId ){
$path = sprintf( self::PATH_NOTIFICATION_LOOKUP, $notificationId );
return $this->httpGet( $path );
} | Returns details about the passed notification ID.
NULL is returned if no notification is found for the ID.
@param string $notificationId
@return array|null | entailment |
public function listNotifications( array $filters = array() ){
// Only allow the following filter keys.
$filters = array_intersect_key( $filters, array_flip([
'older_than',
'reference',
'status',
'template_type',
]));
return $this->httpGe... | Returns a list of all notifications for the current Service ID.
Filter supports:
- older_than
- reference
- status
- template_type
@param array $filters
@return mixed|null | entailment |
public function listReceivedTexts( array $filters = array() ){
// Only allow the following filter keys.
$filters = array_intersect_key( $filters, array_flip([
'older_than'
]));
return $this->httpGet( self::PATH_RECEIVED_TEXT_LIST, $filters );
} | Returns a list of all received texts for the current Service ID.
Filter supports:
- older_than
@param array $filters
@return mixed|null | entailment |
public function getTemplate( $templateId ){
$path = sprintf( self::PATH_TEMPLATE_LOOKUP, $templateId );
return $this->httpGet( $path );
} | Get a template by ID.
@param string $templateId
@return array | entailment |
public function getTemplateVersion( $templateId, $version ){
$path = sprintf( self::PATH_TEMPLATE_VERSION_LOOKUP, $templateId, $version );
return $this->httpGet( $path );
} | Get a template by ID and version.
@param string $templateId
@param int $version
@return array | entailment |
public function listTemplates( $templateType = null ){
$queryParams = is_null( $templateType ) ? [] : [ 'type' => $templateType ];
return $this->httpGet( self::PATH_TEMPLATE_LIST, $queryParams );
} | Get all templates
Can pass in template_type to filter templates.
@param string $template_type
@return array | entailment |
public function previewTemplate( $templateId, $personalisation){
$path = sprintf( self::PATH_TEMPLATE_PREVIEW, $templateId );
$payload = [
'personalisation'=>$personalisation
];
return $this->httpPost( $path, $payload );
} | Get a preview of a template
@return array | entailment |
private function buildPayload( $type, $to, $templateId, array $personalisation, $reference ){
$payload = [
'template_id'=> $templateId
];
if ( $type == 'sms' ) {
$payload['phone_number'] = $to;
} else if ( $type == 'email' ) {
$payload['email_address... | Generates the payload expected by the API.
@param string $type
@param string $to
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
private function buildEmailPayload( $type, $to, $templateId, array $personalisation, $reference, $emailReplyToId = NULL ) {
$payload = $this->buildPayload( $type, $to, $templateId, $personalisation, $reference );
if ( isset($emailReplyToId) && $emailReplyToId != '' ) {
$payload['email_repl... | Generates the payload expected by the API for email adding the optional items.
@param string $type
@param string $to
@param string $templateId
@param array $personalisation
@param string $reference
@param string $emailReplyToId
@return array | entailment |
private function buildSmsPayload( $type, $to, $templateId, array $personalisation, $reference, $smsSenderId = NULL ){
$payload = $this->buildPayload( $type, $to, $templateId, $personalisation, $reference );
if ( isset($smsSenderId) && $smsSenderId != '' ) {
$payload['sms_sender_id'] = $sms... | Generates the payload expected by the API for sms adding the optional items.
@param string $type
@param string $to
@param string $templateId
@param array $personalisation
@param string $reference
@param string $smsSenderId
@return array | entailment |
private function httpGet( $path, array $query = array() ){
$url = new Uri( $this->baseUrl . $path );
foreach( $query as $name => $value ){
$url = URI::withQueryValue($url, $name, $value );
}
//---
$request = new Request(
'GET',
$url,
... | Performs a GET against the Notify API.
@param string $path
@param array $query
@return array|null
@throw Exception\NotifyException | Exception\ApiException | Exception\UnexpectedValueException | entailment |
private function httpPost( $path, Array $payload ){
$url = new Uri( $this->baseUrl . $path );
$request = new Request(
'POST',
$url,
$this->buildHeaders(),
json_encode( $payload )
);
try {
$response = $this->getHttpClient()->... | Performs a POST against the Notify API.
@param string $path
@param array $payload
@return array
@throw Exception\NotifyException | Exception\ApiException | Exception\UnexpectedValueException | entailment |
protected function handleResponse( ResponseInterface $response ){
$body = json_decode($response->getBody(), true);
// The expected response should always be JSON, thus now an array.
if( !is_array($body) ){
throw new Exception\ApiException( 'Malformed JSON response from server', $re... | Called with a response from the API when the response code was successful. i.e. 20X.
@param ResponseInterface $response
@return array
@throw Exception\ApiException | entailment |
protected function handleErrorResponse( ResponseInterface $response ){
$body = json_decode($response->getBody(), true);
$message = "HTTP:{$response->getStatusCode()}";
throw new Exception\ApiException( $message, $response->getStatusCode(), $body, $response );
} | Called with a response from the API when the response code was unsuccessful. i.e. not 20X.
@param ResponseInterface $response
@return null
@throw Exception\ApiException | entailment |
public function get10()
{
// Is it valid?
if ($this->isValid()) {
// Is it already an ISBN-10? If so, return as-is.
if (strlen($this->raw) == 10) {
return $this->raw;
} elseif (strlen($this->raw) == 13
&& substr($this->raw, 0, 3) =... | Get the ISBN in ISBN-10 format:
@return mixed ISBN, or false if invalid/incompatible. | entailment |
public function get13()
{
// Is it invalid?
if (!$this->isValid()) {
return false;
}
// Is it an ISBN-10? If so, convert to Bookland EAN:
if (strlen($this->raw) == 10) {
$start = '978' . substr($this->raw, 0, 9);
return $start . self::getI... | Get the ISBN in ISBN-13 format:
@return mixed ISBN, or false if invalid/incompatible. | entailment |
public function isValid()
{
// If we haven't already checked validity, do so now and store the result:
if (null === $this->valid) {
$this->valid = self::isValidISBN10($this->raw)
|| self::isValidISBN13($this->raw);
}
return $this->valid;
} | Is the current ISBN valid in some format? (May be 10 or 13 digit).
@return boolean | entailment |
public static function getISBN10CheckDigit($isbn)
{
$sum = 0;
for ($x = 0; $x < strlen($isbn); $x++) {
$sum += intval(substr($isbn, $x, 1)) * (1 + $x);
}
$checkdigit = $sum % 11;
return $checkdigit == 10 ? 'X' : $checkdigit;
} | Given the first 9 digits of an ISBN-10, generate the check digit.
@param string $isbn The first 9 digits of an ISBN-10.
@return string The check digit. | entailment |
public static function isValidISBN10($isbn)
{
$isbn = self::normalizeISBN($isbn);
if (strlen($isbn) != 10) {
return false;
}
return substr($isbn, 9) == self::getISBN10CheckDigit(substr($isbn, 0, 9));
} | Is the provided ISBN-10 valid?
@param string $isbn The ISBN-10 to test.
@return boolean | entailment |
public static function getISBN13CheckDigit($isbn)
{
$sum = 0;
$weight = 1;
for ($x = 0; $x < strlen($isbn); $x++) {
$sum += intval(substr($isbn, $x, 1)) * $weight;
$weight = $weight == 1 ? 3 : 1;
}
$retval = 10 - ($sum % 10);
return $retval == ... | Given the first 12 digits of an ISBN-13, generate the check digit.
@param string $isbn The first 12 digits of an ISBN-13.
@return string The check digit. | entailment |
public static function isValidISBN13($isbn)
{
$isbn = self::normalizeISBN($isbn);
if (strlen($isbn) != 13) {
return false;
}
return
substr($isbn, 12) == self::getISBN13CheckDigit(substr($isbn, 0, 12));
} | Is the provided ISBN-13 valid?
@param string $isbn The ISBN-13 to test.
@return boolean | entailment |
public function getLocation($ip, $asArray = true)
{
if ($this->useLocalDB) {
$ipDataArray = $this->fromDB($ip) + ['ip' => $ip];
} else {
$ipDataArray = $this->fromSite($ip) + ['ip' => $ip];
}
if ($asArray) {
return $ipDataArray;
}
... | Определение географического положения по IP-адресу.
@param string $ip
@param boolean $asArray
@return array|IpData ('ip', 'country', 'city', 'region', 'lat', 'lng') или false если ничего не найдено.
@throws Exception | entailment |
public function updateDB()
{
if (($fileName = $this->getArchive()) === false) {
throw new Exception('Ошибка загрузки архива.');
}
$zip = new \ZipArchive;
if ($zip->open($fileName) !== true) {
@unlink($fileName);
throw new Exception('Ошибка распаков... | Метод создаёт или обновляет локальную базу IP-адресов.
@throws Exception | entailment |
protected function generateCityTables($zip)
{
$citiesArray = explode("\n", $zip->getFromName(self::ARCHIVE_CITIES_FILE));
array_pop($citiesArray); // пустая строка
$cities = [];
$uniqueRegions = [];
$regionId = 1;
foreach ($citiesArray as $city) {
$row = ... | Метод производит заполнение таблиц городов и регионов используя
данные из файла self::ARCHIVE_CITIES.
@param $zip \ZipArchive
@throws \yii\db\Exception | entailment |
protected function generateIpTable($zip)
{
$ipsArray = explode("\n", $zip->getFromName(self::ARCHIVE_IPS_FILE));
array_pop($ipsArray); // пустая строка
$i = 0;
$values = [];
Yii::$app->{$this->db}->createCommand()->truncateTable(self::DB_IP_TABLE_NAME)->execute();
fo... | Метод производит заполнение таблиц IP-адресов используя
данные из файла self::ARCHIVE_IPS.
@param $zip \ZipArchive
@throws \yii\db\Exception | entailment |
protected function getArchive()
{
if (($fileData = $this->getRemoteContent(self::ARCHIVE_URL)) === false) {
return false;
}
$fileName = Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . substr(strrchr(self::ARCHIVE_URL, '/'), 1);
if (@file_put_contents($fileName, $fileDa... | Метод загружает архив с данными с адреса self::ARCHIVE_URL.
@return boolean|string путь к загруженному файлу или false если файл загрузить не удалось.
@throws Exception | entailment |
protected function getRemoteContent($url)
{
$response = (new Client())
->createRequest()
->setMethod('GET')
->setUrl($url)
->send();
if (!$response->isOk) {
throw new Exception("URL {$url} doesn't exist");
}
return $respons... | Метод возвращает содержимое документа полученного по указанному url.
@param string $url
@return string
@throws Exception | entailment |
public function settingsHtml()
{
Craft::$app->view->registerAssetBundle(PatrolPluginAssetBundle::class);
/**
* @var SettingsModel $settings
*/
$settings = $this->getSettings();
$variables = [
'plugin' => $this,
'settings' => $sett... | Returns rendered settings UI as a twig markup object
@return \Twig_Markup
@throws \Twig_Error_Loader
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | entailment |
private function getFieldsDataFromMetadata(ClassMetadataInfo $metadata)
{
$fieldsData = (array) $metadata->fieldMappings;
// Convert type to filter widget
foreach ($fieldsData as $fieldName => $data) {
$fieldsData[$fieldName]['fieldName'] = $fieldName;
$fieldsData[$f... | Returns an array of fields data (name and filter widget to use).
Fields can be both column fields and association fields.
@param ClassMetadataInfo $metadata
@return array $fields | entailment |
public function destroyAUX()
{
parent::destroyAUX();
$metaModel = $this->getMetaModel()->getTableName();
// Try to delete the column. If it does not exist as we can assume it has been deleted already then.
$tableColumns = $this->connection->getSchemaManager()->listTableColumns($meta... | {@inheritdoc} | entailment |
public function initializeAUX()
{
parent::initializeAUX();
if ($colName = $this->getColName()) {
$tableName = $this->quoteReservedWord($this->getMetaModel()->getTableName());
$this->tableManipulator->createColumn($tableName, $this->quoteReservedWord($colName), 'blob NULL');
... | {@inheritdoc} | entailment |
public function searchFor($strPattern)
{
$subSelect = $this->connection->createQueryBuilder();
$subSelect
->select($this->quoteReservedWord('uuid'))
->from($this->quoteReservedWord('tl_files'))
->where($subSelect->expr()->like($this->quoteReservedWord('path'), ':v... | {@inheritdoc} | entailment |
public function unsetDataFor($arrIds)
{
$builder = $this->connection->createQueryBuilder();
$builder
->update($this->quoteReservedWord($this->getMetaModel()->getTableName()))
->set($this->quoteReservedWord($this->getColName()), ':null')
->where($builder->expr()->i... | {@inheritdoc} | entailment |
public function getDataFor($arrIds)
{
$builder = $this->connection->createQueryBuilder();
$idField = $this->quoteReservedWord('id');
$aliasFile = $this->quoteReservedWord('file');
$builder
->select($idField, ' ' . $this->quoteReservedWord($this->getColName()) . ' ' . $... | {@inheritdoc} | entailment |
public function setDataFor($arrValues)
{
$tableName = $this->getMetaModel()->getTableName();
$colName = $this->getColName();
foreach ($arrValues as $id => $value) {
if (null === $value) {
// The sort key be can remove in later version.
$value = [... | This method is called to store the data for certain items to the database.
@param mixed $arrValues The values to be stored into database. Mapping is item id=>value.
@return void | entailment |
public function serializeData($mixValues)
{
$data = ToolboxFile::convertValuesToDatabase($mixValues ?: ['bin' => [], 'value' => [], 'path' => []]);
// Check single file or multiple file.
if ($this->get('file_multiple')) {
return \serialize($data);
}
return $data... | Take the data from the system and serialize it for the database.
@param mixed $mixValues The data to serialize.
@return string An serialized array with binary data or a binary data. | entailment |
private function handleCustomFileTree(&$arrFieldDef)
{
if ($this->get('file_uploadFolder')) {
// Set root path of file chooser depending on contao version.
$file = null;
if ($this->validator->isUuid($this->get('file_uploadFolder'))) {
$file = $this->fileR... | Manipulate the field definition for custom file trees.
@param array $arrFieldDef The field definition to manipulate.
@return void | entailment |
public function getFieldDefinition($arrOverrides = [])
{
$fieldDefinition = parent::getFieldDefinition($arrOverrides);
$fieldDefinition['inputType'] = 'fileTree';
$fieldDefinition['eval']['files'] = true;
$fieldDefinition['eval']['extensions'] = $this->config->get('all... | {@inheritdoc} | entailment |
protected function prepareTemplate(Template $template, $rowData, $settings)
{
parent::prepareTemplate($template, $rowData, $settings);
// No data, nothing to do.
if (!$rowData[$this->getColName()]) {
return;
}
$toolbox = clone $this->toolboxFile;
$toolb... | {@inheritDoc} | entailment |
public function create($id, $args){
// Construct the payload, optionally with attachments
$payload = array(
"source_guid" => $args[0],
"text" => $args[1]
);
if ( !empty($args[2]) ) {
$payload = array_merge($payload, array("attachments" => array($args... | create: Create messages in a group.
@param string $id
@param array $args
source_guid required string — This is used for client-side deduplication.
text required string — This can be omitted if at least one attachment is present.
attachments optional array - include array of attachments to attach images, etc.
@return s... | entailment |
public function attachCallback($callback, $type = self::TASK_COMPLETE)
{
if (!is_callable($callback)) {
throw new Exception('Invalid callback specified');
}
if (!in_array(
$type,
array(self::TASK_COMPLETE, self::TASK_FAIL, self::TASK_STATUS)
)) {
... | Attach a callback to this task.
@param callback $callback A valid PHP callback
@param int $type Type of callback
@throws \MHlavac\Gearman\Exception When the callback is invalid.
@throws \MHlavac\Gearman\Exception When the callback's type is invalid.
@return $this | entailment |
public function complete($result)
{
$this->finished = true;
$this->result = $result;
if (!count($this->callback[self::TASK_COMPLETE])) {
return;
}
foreach ($this->callback[self::TASK_COMPLETE] as $callback) {
call_user_func($callback, $this->func, $t... | Run the complete callbacks.
Complete callbacks are passed the name of the job, the handle of the
job and the result of the job (in that order).
@param object $result JSON decoded result passed back
@see \MHlavac\Gearman\Task::attachCallback() | entailment |
public function fail()
{
$this->finished = true;
if (!count($this->callback[self::TASK_FAIL])) {
return;
}
foreach ($this->callback[self::TASK_FAIL] as $callback) {
call_user_func($callback, $this);
}
} | Run the failure callbacks.
Failure callbacks are passed the task object job that failed
@see \MHlavac\Gearman\Task::attachCallback() | entailment |
public function status($numerator, $denominator)
{
if (!count($this->callback[self::TASK_STATUS])) {
return;
}
foreach ($this->callback[self::TASK_STATUS] as $callback) {
call_user_func($callback,
$this->func,
$th... | Run the status callbacks.
Status callbacks are passed the name of the job, handle of the job and
the numerator/denominator as the arguments (in that order).
@param int $numerator The numerator from the status
@param int $denominator The denominator from the status
@see \MHlavac\Gearman\Task::attachCallback() | entailment |
public function getText()
{
if (!$this->text) {
$this->text = '';
for ($i = 0; $i < $this->macLength; $i++) {
$this->text .= strtolower($this->macChars{rand(0, strlen($this->macChars) - 1)});
}
}
return $this->text;
} | Returns text
@return string | entailment |
public function getHash($text = null)
{
// inserting captcha record
$time = time() + $this->timeout;
$textHash = $this->getTextHash($text);
// if session is started - storing captcha info here
$session = $this->getSession();
if ($session->isSessionStarted()) {
... | Returns text hash
@param string $text User supplie text
@return string | entailment |
public function getTextHash($text)
{
if (!$text) {
$text = $this->getText();
}
$text = strtolower($text);
return md5('ox' . $text);
} | Returns given string captcha hash
@param string $text string to hash
@return string | entailment |
public function getImageUrl()
{
$config = \OxidEsales\Eshop\Core\Registry::getConfig();
$url = $config->getCurrentShopUrl() . 'modules/oe/captcha/core/utils/verificationimg.php?e_mac=';
$key = $config->getConfigParam('oecaptchakey');
$key = $key ? $key : $config->getConfigParam('sCo... | Returns url to CAPTCHA image generator.
@return string | entailment |
public function passCaptcha($displayError = true)
{
$return = true;
// spam spider prevention
$mac = $this->getConfig()->getRequestParameter('c_mac');
$macHash = $this->getConfig()->getRequestParameter('c_mach');
if (!$this->pass($mac, $macHash)) {
$return = fal... | Check if captcha is passed.
@return bool | entailment |
protected function pass($mac, $macHash)
{
$time = time();
$hash = $this->getTextHash($mac);
$pass = $this->passFromSession($macHash, $hash, $time);
// if captcha info was NOT stored in session
if ($pass === null) {
$pass = $this->passFromDb((int) $macHash, $hash,... | Verifies captcha input vs supplied hash. Returns true on success.
@param string $mac User supplied text
@param string $macHash Generated hash
@return bool | entailment |
protected function passFromSession($macHash, $hash, $time)
{
$pass = null;
$session = $this->getSession();
if (($hashArray = $session->getVariable('captchaHashes'))) {
$pass = (isset($hashArray[$macHash][$hash]) && $hashArray[$macHash][$hash] >= $time) ? true : false;
... | Checks for session captcha hash validity
@param string $macHash hash key
@param string $hash captcha hash
@param int $time check time
@return bool | entailment |
protected function passFromDb($macHash, $hash, $time)
{
$database = DatabaseProvider::getDb();
$where = "where oxid = " . $database->quote($macHash) . " and oxhash = " . $database->quote($hash);
$query = "select 1 from oecaptcha " . $where;
$pass = (bool) $database->getOne($query, fa... | Checks for DB captcha hash validity
@param int $macHash hash key
@param string $hash captcha hash
@param int $time check time
@return bool | entailment |
private function databaseConnect()
{
$dsn = 'mysql:host='.$this->db['host'].';port='.$this->db['port'].';dbname='.$this->db['name'];
$options = array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_ERRMODE ... | Database connection link | entailment |
private function query($q, $fetchAll = true)
{
$stmt = $this->dbh->query($q);
if ($fetchAll === true)
{
return $stmt->fetchAll();
}
else
{
return $stmt->fetch();
}
} | Query fetcher
@param string $q Query
@param boolean $fetchAll fetchAll or fetch
@return object PDO | entailment |
public function setCompress($p)
{
if (in_array($p, $this->compressAvailable))
$this->compressFormat = $p;
return $this;
} | Set compress file format (default : null - no compress)
@param string $p Compress format available in $this->compressAvailable
@return object MySQLBackup | entailment |
public function addTable($table)
{
if (!in_array($table, $this->tables))
{
$this->tables[] = $table;
}
return $this;
} | Add table name to dump
@param string $table Table name to dump
@return object MySQLBackup | entailment |
public function addTables(array $tables)
{
if (is_array($tables) && count($tables) > 0)
{
foreach ($tables as $t)
{
$this->addTable($t);
}
}
return $this;
} | Dump selected tables
@param array $tables Tables to backup
@return object MySQLBackup | entailment |
public function addAllTables()
{
$result = $this->query('SHOW TABLES');
foreach ($result as $row)
{
$this->addTable($row[0]);
}
return $this;
} | Dump all tables
@return object MySQLBackup | entailment |
public function excludeTables(array $tables)
{
if (is_array($tables) && count($tables) > 0)
{
$this->excludedTables = $tables;
}
return $this;
} | Exclude tables
@return object MySQLBackup | entailment |
public function dump()
{
$return = '';
if (count($this->tables) == 0)
{
$this->addAllTables();
}
$return .= "--\n";
$return .= "-- Backup ".$this->db['name']." - ".date('Y-m-d H:i:s')."\n";
$return .= "--\n\n\n";
... | Dump SQL database with selected tables | entailment |
private function download()
{
header('Content-disposition: attachment; filename="'.$this->filename.'.'.$this->extension.'"');
header('Content-type: application/octet-stream');
readfile($this->filename.'.'.$this->extension);
} | Download the dump file | entailment |
private function compress()
{
switch ($this->compressFormat)
{
case 'zip':
if (class_exists('\ZipArchive'))
{
$zip = new \ZipArchive;
if ($zip->open($this->filename.'.zip', \ZipA... | Compress the file | entailment |
private function delete()
{
if (file_exists($this->filename.'.'.$this->extension))
{
unlink($this->filename.'.'.$this->extension);
}
} | Delete the file | entailment |
public function getDefaultTemplate()
{
list($default, $negated) = $this->getTemplateStrings();
$template = new ArrayTemplate([
'default' => $default,
'negated' => $negated,
]);
return $template->setTemplateVars([
'key' => $this->getKey(),
... | {@inheritdoc}
@return TemplateInterface | entailment |
protected function doMatch($actual)
{
$this->validateActual($actual);
if ($this->isDeep()) {
return $this->matchDeep($actual);
}
$actual = $this->actualToArray($actual);
return $this->matchArrayIndex($actual);
} | Matches if the actual value has a property, optionally matching
the expected value of that property. If the deep flag is set,
the matcher will use the ObjectPath utility to parse deep expressions.
@code
$this->doMatch('child->name->first', 'brian');
@endcode
@param mixed $actual
@return mixed | entailment |
protected function matchArrayIndex($actual)
{
if (isset($actual[$this->getKey()])) {
$this->assertion->setActual($actual[$this->getKey()]);
return $this->isExpected($actual[$this->getKey()]);
}
return false;
} | Match that an array index exists, and matches
the expected value if set.
@param $actual
@return bool | entailment |
protected function matchDeep($actual)
{
$path = new ObjectPath($actual);
$value = $path->get($this->getKey());
if ($value === null) {
return false;
}
$this->assertion->setActual($value->getPropertyValue());
return $this->isExpected($value->getPropertyVa... | Uses ObjectPath to parse an expression if the deep flag
is set.
@param $actual
@return bool | entailment |
protected function isExpected($value)
{
if ($expected = $this->getValue()) {
$this->setActualValue($value);
return $this->getActualValue() === $expected;
}
return true;
} | Check if the given value is expected.
@param $value
@return bool | entailment |
protected function getTemplateStrings()
{
$default = 'Expected {{actual}} to have a{{deep}}property {{key}}';
$negated = 'Expected {{actual}} to not have a{{deep}}property {{key}}';
if ($this->getValue() && $this->isActualValueSet()) {
$default = 'Expected {{actual}} to have a{{... | Returns the strings used in creating the template for the matcher.
@return array | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.