sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function getErrorMessage($name, $params = [])
{
if ($this->simpleErrorMessage) {
$name = 'message';
}
if (isset($this->$name)) {
return [$this->$name, $params];
}
$this->$name = Yii::t('kdn/yii2/validators/domain', $this->getDefaultErrorMessages()[$name]);
return [$this->$name, $params];
} | Get error message by name.
@param string $name error message name
@param array $params parameters to be inserted into the error message
@return array error message. | entailment |
protected function getDefaultErrorMessages()
{
$messages = [
'message' => '{attribute} is invalid.',
'messageDNS' => 'DNS record corresponding to {attribute} not found.',
'messageLabelNumberMin' =>
'{attribute} should consist of at least {labelNumberMin, number} labels separated by ' .
'{labelNumberMin, plural, =2{dot} other{dots}}.',
'messageLabelTooShort' => 'Each label of {attribute} should contain at least 1 character.',
'messageNotString' => '{attribute} must be a string.',
'messageTooShort' => '{attribute} should contain at least 1 character.',
];
if ($this->enableIDN) {
$messages['messageLabelStartEnd'] =
'Each label of {attribute} should start and end with letter or number.' .
' The rightmost label of {attribute} should start with letter.';
$messages['messageLabelTooLong'] = 'Label of {attribute} is too long.';
$messages['messageTooLong'] = '{attribute} is too long.';
if ($this->allowUnderscore) {
$messages['messageInvalidCharacter'] =
'Each label of {attribute} can consist of only letters, numbers, hyphens and underscores.';
} else {
$messages['messageInvalidCharacter'] =
'Each label of {attribute} can consist of only letters, numbers and hyphens.';
}
} else {
$messages['messageLabelStartEnd'] =
'Each label of {attribute} should start and end with latin letter or number.' .
' The rightmost label of {attribute} should start with latin letter.';
$messages['messageLabelTooLong'] = 'Each label of {attribute} should contain at most 63 characters.';
$messages['messageTooLong'] = '{attribute} should contain at most 253 characters.';
if ($this->allowUnderscore) {
$messages['messageInvalidCharacter'] =
'Each label of {attribute} can consist of only latin letters, numbers, hyphens and underscores.';
} else {
$messages['messageInvalidCharacter'] =
'Each label of {attribute} can consist of only latin letters, numbers and hyphens.';
}
}
return $messages;
} | Get default error messages.
@return array default error messages. | entailment |
public function dir()
{
$this->_name = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid($this->_prefix);
if (!mkdir($this->_name)) {
throw new \Exception('Cannot create temporary directory');
}
return $this;
} | Creates temporary directory
@throws \Exception
@return Temporary | entailment |
public function product($orderLineHandle, $product)
{
$products = new Product($this->client_raw);
$productHandle = $products->getHandle($product);
$this->client
->OrderLine_SetProduct(
array(
'orderLineHandle' => $orderLineHandle,
'valueHandle' => $productHandle
)
);
return true;
} | Set Order Line product
by product number
@param mixed $orderLineHandle
@param string $product
@return boolean | entailment |
public function unit($orderLineHandle, $unit)
{
$units = new Unit($this->client_raw);
$unitHandle = $units->getHandle($unit);
$this->client
->OrderLine_SetUnit(
array(
'orderLineHandle' => $orderLineHandle,
'valueHandle' => $unitHandle
)
);
return true;
} | Set Quotation Line unit
by unit number
@param mixed $orderLineHandle [description]
@param integer $unit
@return boolean | entailment |
public function add(array $data)
{
$defaults = array(
"description" => null,
"price" => null,
"discount" => null,
"qty" => 1,
"unit" => null
);
$merged = array_merge($defaults, $data);
$line = $this->create($this->quotationHandle);
if( isset($merged['product']) )
{
$this->product($line, $merged['product']);
unset( $merged['product'] );
}
foreach( $merged as $name => $value )
{
if( is_null($value) )
continue;
switch($name)
{
case 'description':
$this->description($line, $value);
break;
case 'price':
$this->price($line, $value);
break;
case 'discount':
$this->discount($line, $value);
break;
case 'qty':
$this->qty($line, $value);
break;
case 'unit':
$this->unit($line, $value);
break;
}
}
} | Create new Quotation line from data
@param array $data | entailment |
public function unit($QuotationLineHandle, $unit)
{
$units = new Unit($this->client_raw);
$unitHandle = $units->getHandle($unit);
$this->client
->QuotationLine_SetUnit(
array(
'quotationLineHandle' => $QuotationLineHandle,
'valueHandle' => $unitHandle
)
);
return true;
} | Set Quotation Line unit
by unit number
@param mixed $QuotationLineHandle [description]
@param integer $unit
@return boolean | entailment |
public function product($QuotationLineHandle, $product)
{
$products = new Product($this->client_raw);
$productHandle = $products->getHandle($product);
$this->client
->QuotationLine_SetProduct(
array(
'quotationLineHandle' => $QuotationLineHandle,
'valueHandle' => $productHandle
)
);
return true;
} | Set Quotation Line product
by product number
@param mixed $QuotationLineHandle
@param integer $product
@return boolean | entailment |
public function all()
{
$handles = $this->client
->DebtorContact_GetAll()
->DebtorContact_GetAllResult
->DebtorContactHandle;
return $this->getArrayFromHandles($handles);
} | Get all Contacts
@return array | entailment |
public function search($name)
{
$handles = $this->client
->DebtorContact_FindByName(array('name'=>$name))
->DebtorContact_FindByNameResult
->DebtorContactHandle;
return $this->getArrayFromHandles($handles);
} | Search contact by full name
@param string $name
@return array | entailment |
public function update(array $data, $id)
{
if( !is_integer($id) )
throw new Exception("ID must be a integer");
$handle = array('Id'=>$id);
foreach( $data as $field => $value )
{
switch( strtolower($field) )
{
case 'name':
$this->client
->debtorContact_SetName(array(
'debtorContactHandle' => $handle,
'value' => $value
));
break;
case 'email':
$this->client
->debtorContact_SetEmail(array(
'debtorContactHandle' => $handle,
'value' => $value
));
break;
case 'phone':
$this->client
->DebtorContact_SetTelephoneNumber(array(
'debtorContactHandle' => $handle,
'value' => $value
));
break;
case 'invoice':
$this->client
->debtorContact_SetIsToReceiveEmailCopyOfInvoice(array(
'debtorContactHandle' => $handle,
'value' => !!$value
));
break;
case 'order':
$this->client
->debtorContact_SetIsToReceiveEmailCopyOfOrder(array(
'debtorContactHandle' => $handle,
'value' => !!$value
));
break;
case 'comment':
$this->client
->debtorContact_SetComments(array(
'debtorContactHandle' => $handle,
'value' => $value
));
break;
}
}
return $this->getArrayFromHandles($handle);
} | Update an existion Contact by Contact ID
@param array $data
@param integer $id
@return array | entailment |
public function create(array $data, $debtor)
{
$debtors = new Debtor($this->client_raw);
$debtorHandle = $debtors->getHandle($debtor);
$id = $this->client
->DebtorContact_Create(array(
'debtorHandle' => $debtorHandle,
'name' => $data['name']
))->DebtorContact_CreateResult;
return $this->update($id->Id, $data);
} | Create a new Contact from data array
@param array $data
@param integer $debtor
@return array | entailment |
public function delete($id)
{
$data = $this->findById($id);
$this->client
->DebtorContact_Delete(array(
"debtorContactHandle" => $data->Handle
));
return true;
} | Delete a Contact by ID
@param integer $id
@return boolean | entailment |
public function execute(Arguments $args, ConsoleIo $io)
{
try {
$count = $this->ThumbManager->clearAll();
} catch (Exception $e) {
$io->err(__d('thumber', 'Error deleting thumbnails'));
$this->abort();
}
$io->verbose(__d('thumber', 'Thumbnails deleted: {0}', $count));
return null;
} | Clears all thumbnails
@param Arguments $args The command arguments
@param ConsoleIo $io The console io
@return null|int The exit code or null for success
@uses $ThumbManager | entailment |
protected function createAclFromConfig(array $config)
{
$aclConfig = [];
$denyByDefault = false;
if (array_key_exists('deny_by_default', $config)) {
$denyByDefault = $aclConfig['deny_by_default'] = (bool)$config['deny_by_default'];
unset($config['deny_by_default']);
}
foreach ($config as $controllerService => $privileges) {
$this->createAclConfigFromPrivileges($controllerService, $privileges, $aclConfig, $denyByDefault);
}
return AclFactory::factory($aclConfig);
} | Generate the ACL instance based on the zf-mvc-auth "authorization" configuration
Consumes the AclFactory in order to create the AclAuthorization instance.
@param array $config
@return AclAuthorization | entailment |
protected function createAclConfigFromPrivileges($controllerService, array $privileges, &$aclConfig, $denyByDefault)
{
// Normalize the controller service name.
// zend-mvc will always pass the name using namespace seprators, but
// the admin may write the name using dash seprators.
$controllerService = strtr($controllerService, '-', '\\');
if (isset($privileges['actions'])) {
foreach ($privileges['actions'] as $action => $methods) {
$action = lcfirst($action);
$aclConfig[] = [
'resource' => sprintf('%s::%s', $controllerService, $action),
'privileges' => $this->createPrivilegesFromMethods($methods, $denyByDefault),
];
}
}
if (isset($privileges['collection'])) {
$aclConfig[] = [
'resource' => sprintf('%s::collection', $controllerService),
'privileges' => $this->createPrivilegesFromMethods($privileges['collection'], $denyByDefault),
];
}
if (isset($privileges['entity'])) {
$aclConfig[] = [
'resource' => sprintf('%s::entity', $controllerService),
'privileges' => $this->createPrivilegesFromMethods($privileges['entity'], $denyByDefault),
];
}
} | Creates ACL configuration based on the privileges configured
- Extracts a privilege per action
- Extracts privileges for each of "collection" and "entity" configured
@param string $controllerService
@param array $privileges
@param array $aclConfig
@param bool $denyByDefault | entailment |
protected function createPrivilegesFromMethods(array $methods, $denyByDefault)
{
$privileges = [];
if (isset($methods['default']) && $methods['default']) {
$privileges = $this->httpMethods;
unset($methods['default']);
}
foreach ($methods as $method => $flag) {
// If the flag evaluates true and we're denying by default, OR
// if the flag evaluates false and we're allowing by default,
// THEN no rule needs to be added
if (( $denyByDefault && $flag)
|| (! $denyByDefault && ! $flag)
) {
if (isset($privileges[$method])) {
unset($privileges[$method]);
}
continue;
}
// Otherwise, we need to add a rule
$privileges[$method] = true;
}
if (empty($privileges)) {
return null;
}
return array_keys($privileges);
} | Create the list of HTTP methods defining privileges
@param array $methods
@param bool $denyByDefault
@return array|null | entailment |
private function getConfigFromContainer(ContainerInterface $container)
{
if (! $container->has('config')) {
return [];
}
$config = $container->get('config');
if (! isset($config['zf-mvc-auth']['authorization'])) {
return [];
}
return $config['zf-mvc-auth']['authorization'];
} | Retrieve configuration from the container.
Attempts to pull the 'config' service, and, further, the
zf-mvc-auth.authorization segment.
@param ContainerInterface $container
@return array | entailment |
protected function checkResponse(ResponseInterface $response, $data)
{
$acceptableStatuses = [200, 201];
if (!in_array($response->getStatusCode(), $acceptableStatuses)) {
throw new IdentityProviderException(
$data['message'] ?: $response->getReasonPhrase(),
$response->getStatusCode(),
$response
);
}
} | Check a provider response for errors.
@link https://developer.uber.com/v1/api-reference/
@throws IdentityProviderException
@param ResponseInterface $response
@param string $data Parsed response data
@return void | entailment |
public static function fromKeyFile($firebaseURI, $keyFile, $rootPath = '/')
{
return new self($firebaseURI, OAuth::fromKeyFile($keyFile), $rootPath);
} | @param $firebaseURI
@param $keyFile
@param string $rootPath
@return JCFirebase
@throws \Exception | entailment |
public function get($path = '', $options = array())
{
return $this->client->get(
$this->addDataToPathURI($path, $options),
$this->addDataToRequest($options),
$this->requestHeader
);
} | @param string $path
@param array $options
@return JCResponseInterface | entailment |
public function put($path = '', $options = array())
{
return $this->client->put($this->getPathURI($path),
$this->addDataToRequest($options, true),
$this->requestHeader
);
} | @param string $path
@param array $options
@return JCResponseInterface | entailment |
public function delete($path = '', $options = array())
{
return $this->client->delete(
$this->getPathURI($path),
$this->addDataToRequest($options),
$this->requestHeader
);
} | @param string $path
@param array $options
@return JCResponseInterface | entailment |
public function actionIndex()
{
$action = strtolower(Yii::$app->request->get('action', 'config'));
$actions = [
'uploadimage' => 'upload-image',
'uploadscrawl' => 'upload-scrawl',
'uploadvideo' => 'upload-video',
'uploadfile' => 'upload-file',
'listimage' => 'list-image',
'listfile' => 'list-file',
'catchimage' => 'catch-image',
'config' => 'config',
'listinfo' => 'list-info'
];
if (isset($actions[$action]))
return $this->run($actions[$action]);
else
return $this->show(['state' => 'Unknown action.']);
} | 蛋疼的统一后台入口 | entailment |
public function actionUploadImage()
{
$config = [
'pathFormat' => $this->config['imagePathFormat'],
'maxSize' => $this->config['imageMaxSize'],
'allowFiles' => $this->config['imageAllowFiles']
];
$fieldName = $this->config['imageFieldName'];
$result = $this->upload($fieldName, $config);
return $this->show($result);
} | 上传图片 | entailment |
public function actionUploadScrawl()
{
$config = [
'pathFormat' => $this->config['scrawlPathFormat'],
'maxSize' => $this->config['scrawlMaxSize'],
'allowFiles' => $this->config['scrawlAllowFiles'],
'oriName' => 'scrawl.png'
];
$fieldName = $this->config['scrawlFieldName'];
$result = $this->upload($fieldName, $config, 'base64');
return $this->show($result);
} | 上传涂鸦 | entailment |
public function actionUploadVideo()
{
$config = [
'pathFormat' => $this->config['videoPathFormat'],
'maxSize' => $this->config['videoMaxSize'],
'allowFiles' => $this->config['videoAllowFiles']
];
$fieldName = $this->config['videoFieldName'];
$result = $this->upload($fieldName, $config);
return $this->show($result);
} | 上传视频 | entailment |
public function actionUploadFile()
{
$config = [
'pathFormat' => $this->config['filePathFormat'],
'maxSize' => $this->config['fileMaxSize'],
'allowFiles' => $this->config['fileAllowFiles']
];
$fieldName = $this->config['fileFieldName'];
$result = $this->upload($fieldName, $config);
return $this->show($result);
} | 上传文件 | entailment |
public function actionListFile()
{
$allowFiles = $this->config['fileManagerAllowFiles'];
$listSize = $this->config['fileManagerListSize'];
$path = $this->config['fileManagerListPath'];
$result = $this->manage($allowFiles, $listSize, $path);
return $this->show($result);
} | 文件列表 | entailment |
public function actionCatchImage()
{
/* 上传配置 */
$config = [
'pathFormat' => $this->config['catcherPathFormat'],
'maxSize' => $this->config['catcherMaxSize'],
'allowFiles' => $this->config['catcherAllowFiles'],
'oriName' => 'remote.png'
];
$fieldName = $this->config['catcherFieldName'];
/* 抓取远程图片 */
$list = [];
if (isset($_POST[$fieldName])) {
$source = $_POST[$fieldName];
} else {
$source = $_GET[$fieldName];
}
foreach ($source as $imgUrl) {
$item = new Uploader($imgUrl, $config, 'remote');
if ($this->allowIntranet)
$item->setAllowIntranet(true);
$info = $item->getFileInfo();
$info['thumbnail'] = $this->imageHandle($info['url']);
$list[] = [
'state' => $info['state'],
'url' => $info['url'],
'source' => $imgUrl
];
}
/* 返回抓取数据 */
return [
'state' => count($list) ? 'SUCCESS' : 'ERROR',
'list' => $list
];
} | 获取远程图片 | entailment |
protected function upload($fieldName, $config, $base64 = 'upload')
{
$up = new Uploader($fieldName, $config, $base64);
if ($this->allowIntranet)
$up->setAllowIntranet(true);
$info = $up->getFileInfo();
if (($this->thumbnail or $this->zoom or $this->watermark) && $info['state'] == 'SUCCESS' && in_array($info['type'], ['.png', '.jpg', '.bmp', '.gif'])) {
$info['thumbnail'] = Yii::$app->request->baseUrl . $this->imageHandle($info['url']);
}
$info['url'] = Yii::$app->request->baseUrl . $info['url'];
$info['original'] = htmlspecialchars($info['original']);
$info['width'] = $info['height'] = 500;
return $info;
} | 各种上传
@param $fieldName
@param $config
@param $base64
@return array | entailment |
protected function getFiles($path, $allowFiles, &$files = [])
{
if (!is_dir($path)) return null;
if (in_array(basename($path), $this->ignoreDir)) return null;
if (substr($path, strlen($path) - 1) != '/') $path .= '/';
$handle = opendir($path);
//baseUrl用于兼容使用alias的二级目录部署方式
$baseUrl = Yii::$app->request->baseUrl;
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$path2 = $path . $file;
if (is_dir($path2)) {
$this->getFiles($path2, $allowFiles, $files);
} else {
if ($this->action->id == 'list-image') {
$pat = "/\.thumbnail\.(" . $allowFiles . ")$/i";
} else {
$pat = "/\.(" . $allowFiles . ")$/i";
}
if (preg_match($pat, $file)) {
$files[] = [
'url' => $baseUrl . substr($path2, strlen($this->webroot)),
'mtime' => filemtime($path2)
];
}
}
}
}
return $files;
} | 遍历获取目录下的指定类型的文件
@param $path
@param $allowFiles
@param array $files
@return array|null | entailment |
protected function show($result)
{
$callback = Yii::$app->request->get('callback', null);
if ($callback && is_string($callback)) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSONP;
return [
'callback' => $callback,
'data' => $result
];
}
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return $result;
} | 最终显示结果,自动输出 JSONP 或者 JSON
@param array $result
@return array | entailment |
public static function clearTextConcat($value)
{
if (is_string($value)) {
return trim(preg_replace('/\s+/s', ' ', $value));
}
if (is_array($value)) {
$result = [];
foreach ($value as $val) {
$result[] = self::clearTextConcat($val);
}
return implode(' ', array_filter($result, 'strlen'));
}
return null;
} | Recursive clears all text in array
@param string $value
@return string|NULL | entailment |
public static function clearText(&$value)
{
if (is_string($value)) {
$value = trim(preg_replace('/\s+/s', ' ', $value));
}
if (is_array($value)) {
foreach ($value as &$val) {
self::clearText($val);
}
}
} | Clears text
@param string $value | entailment |
public static function factory(array $config)
{
// Determine whether we are whitelisting or blacklisting
$denyByDefault = false;
if (array_key_exists('deny_by_default', $config)) {
$denyByDefault = (bool)$config['deny_by_default'];
unset($config['deny_by_default']);
}
// By default, create an open ACL
$acl = new AclAuthorization;
$acl->addRole('guest');
$acl->allow();
$grant = 'deny';
if ($denyByDefault) {
$acl->deny('guest', null, null);
$grant = 'allow';
}
if (! empty($config)) {
return self::injectGrants($acl, $grant, $config);
}
return $acl;
} | Create and return an AclAuthorization instance populated with provided privileges.
@param array $config
@return AclAuthorization | entailment |
private static function injectGrants(AclAuthorization $acl, $grantType, array $rules)
{
foreach ($rules as $set) {
if (! is_array($set) || ! isset($set['resource'])) {
continue;
}
self::injectGrant($acl, $grantType, $set);
}
return $acl;
} | Inject the ACL with the grants specified in the collection of rules.
@param AclAuthorization $acl
@param string $grantType Either "allow" or "deny".
@param array $rules
@return AclAuthorization | entailment |
private static function injectGrant(AclAuthorization $acl, $grantType, array $ruleSet)
{
// Add new resource to ACL
$resource = $ruleSet['resource'];
$acl->addResource($ruleSet['resource']);
// Deny guest specified privileges to resource
$privileges = isset($ruleSet['privileges']) ? $ruleSet['privileges'] : null;
// null privileges means no permissions were setup; nothing to do
if (null === $privileges) {
return;
}
$acl->$grantType('guest', $resource, $privileges);
} | Inject the ACL with the grant specified by a single rule set.
@param AclAuthorization $acl
@param string $grantType
@param array $ruleSet
@return void | entailment |
public function getOptions()
{
foreach ($this->defaultOpts() as $k => $v) {
if (!isset($this->_options[$k])) {
$this->_options[$k] = $v;
}
}
// !important see headerCallback() function
$this->_options[CURLOPT_HEADER] = false;
return $this->_options;
} | Getter for CURL Options
Use curl_setopt_array() for the CURL resourse
@see curl_setopt_array()
@return array | entailment |
public function setOptions(array $options)
{
foreach ($options as $k => $v) {
$this->_options[$k] = $v;
}
return $this;
} | Setter for CURL Options
Warning! setoptions clears all previously setted options and post data
@see curl_setopt_array
@param array $options
@return static | entailment |
public function setPostData($postData)
{
if (is_null($postData)) {
unset($this->_options[CURLOPT_POST]);
unset($this->_options[CURLOPT_POSTFIELDS]);
} else {
$this->_options[CURLOPT_POST] = true;
$this->_options[CURLOPT_POSTFIELDS] = $postData;
}
return $this;
} | Adds post data to options
@param mixed $postData
@return $this; | entailment |
protected function curl_execute()
{
$ch = curl_init();
curl_setopt_array($ch, $this->getOptions());
$this->_content = curl_exec($ch);
$this->_errorCode = curl_errno($ch);
$this->_info = curl_getinfo($ch);
if ($this->_errorCode) {
$this->_errorMessage = curl_error($ch);
}
curl_close($ch);
return $this->isHttpOK();
} | Executes the single curl
@return boolean | entailment |
protected static function curl_multi_exec($urls)
{
$nodes = [];
/* @var $url CurlTrait */
foreach ($urls as $url) {
$ch = curl_init();
$nodes[] = ['ch' => $ch, 'url' => $url];
curl_setopt_array($ch, $url->getOptions());
}
$mh = curl_multi_init();
foreach ($nodes as $node) {
curl_multi_add_handle($mh, $node['ch']);
}
//execute the handles
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
foreach ($nodes as $node) {
/* @var $url Curl */
$url = $node['url'];
$ch = $node['ch'];
$url->_content = curl_multi_getcontent($ch);
$url->_errorCode = curl_errno($ch);
if (!empty($url->_errorCode)) {
$url->_errorMessage = curl_error($ch);
}
$url->_info = curl_getinfo($ch);
}
//close the handles
foreach ($nodes as $node) {
curl_multi_remove_handle($mh, $node['ch']);
}
curl_multi_close($mh);
} | Executes parallels curls
@param CurlTrait[] $urls | entailment |
public static function getIpAddress()
{
// check for shared internet/ISP IP
if (isset($_SERVER['HTTP_CLIENT_IP']) && self::validateIp($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
// check for IPs passing through proxies
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// check if multiple ips exist in var
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
$iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($iplist as $ip) {
if (self::validateIp($ip)) {
return $ip;
}
}
} else {
if (self::validateIp($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
}
}
if (isset($_SERVER['HTTP_X_FORWARDED']) && self::validateIp($_SERVER['HTTP_X_FORWARDED'])) {
return $_SERVER['HTTP_X_FORWARDED'];
}
if (isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && self::validateIp($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
}
if (isset($_SERVER['HTTP_FORWARDED_FOR']) && self::validateIp($_SERVER['HTTP_FORWARDED_FOR'])) {
return $_SERVER['HTTP_FORWARDED_FOR'];
}
if (isset($_SERVER['HTTP_FORWARDED']) && self::validateIp($_SERVER['HTTP_FORWARDED'])) {
return $_SERVER['HTTP_FORWARDED'];
}
// return unreliable ip since all else failed
return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown';
} | Retrieves the best guess of the client's actual IP address.
Takes into account numerous HTTP proxy headers due to variations
in how different ISPs handle IP addresses in headers between hops. | entailment |
public static function validateIp($ip)
{
if (strtolower($ip) === 'unknown') {
return false;
}
// generate ipv4 network address
$ip = ip2long($ip);
// if the ip is set and not equivalent to 255.255.255.255
if (($ip !== false) && ($ip !== -1)) {
// make sure to get unsigned long representation of ip
// due to discrepancies between 32 and 64 bit OSes and
// signed numbers (ints default to signed in PHP)
$ip = sprintf('%u', $ip);
// do private network range checking
if ($ip >= 0 && $ip <= 50331647) {
return false;
}
if ($ip >= 167772160 && $ip <= 184549375) {
return false;
}
if ($ip >= 2130706432 && $ip <= 2147483647) {
return false;
}
if ($ip >= 2851995648 && $ip <= 2852061183) {
return false;
}
if ($ip >= 2886729728 && $ip <= 2887778303) {
return false;
}
if ($ip >= 3221225984 && $ip <= 3221226239) {
return false;
}
if ($ip >= 3232235520 && $ip <= 3232301055) {
return false;
}
if ($ip >= 4294967040) {
return false;
}
}
return true;
} | Ensures an ip address is both a valid IP and does not fall within
a private network range.
@param $ip
@return bool | entailment |
public function getDependencyConfig()
{
return [
'aliases' => [
MvcAuthAuthorizationInterface::class => Authorization\AclAuthorization::class,
],
'factories' => [
Authorization\AuthorizationListener::class =>
Authorization\AuthorizationListenerFactory::class,
Authorization\AclAuthorization::class => Factory\AclAuthorizationFactory::class,
],
];
} | Provide dependency configuration for this component.
@return array | entailment |
protected function _clear($filenames)
{
$count = 0;
foreach ($filenames as $filename) {
if (!(new File($this->getPath($filename)))->delete()) {
return false;
}
$count++;
}
return $count;
} | Internal method to clear thumbnails
@param array $filenames Filenames
@return int|bool Number of thumbnails deleted otherwise `false` in case of error | entailment |
protected function _find($regexpPattern = null, $sort = false)
{
$regexpPattern = $regexpPattern ?: sprintf('[\d\w]{32}_[\d\w]{32}\.(%s)', implode('|', self::$supportedFormats));
return (new Folder($this->getPath()))->find($regexpPattern, $sort);
} | Internal method to find thumbnails
@param string|null $regexpPattern `preg_match()` pattern
@param bool $sort Whether results should be sorted
@return array | entailment |
public function get($path, $sort = false)
{
$regexpPattern = sprintf('%s_[\d\w]{32}\.(%s)', md5($this->resolveFilePath($path)), implode('|', self::$supportedFormats));
return $this->_find($regexpPattern, $sort);
} | Gets all thumbnails that have been generated from an image path
@param string $path Path of the original image
@param bool $sort Whether results should be sorted
@return array
@uses _find() | entailment |
public static function findByKey($key, JCFirebase $firebase)
{
$response = $firebase->get(static::getNodeName() . '/' . $key);
$object = null;
if ($response->success() && $response->body() != 'null') {
$object = static::map($response->json(), new static());
$object->key = $key;
$object->firebase = $firebase;
}
return $object;
} | @param $key
@param JCFirebase $firebase
@return object | entailment |
public static function findAll(JCFirebase $firebase)
{
$response = $firebase->get(static::getNodeName());
$objects = array();
$jsonObject = json_decode($response->body(), true);
if ($response->success() && count($jsonObject)) {
do {
$object = static::map((object)current($jsonObject), new static());
$object->key = key($jsonObject);
$object->firebase = $firebase;
$objects[] = $object;
} while (next($jsonObject));
}
return $objects;
} | @param JCFirebase $firebase
@return array(FirebaseModel) | entailment |
public function execute($url = null, $postData = null)
{
if (!is_null($url)) {
$this->setUrl($url);
}
if (!is_null($postData)) {
$this->setPostData($postData);
}
$this->curl_execute();
if ($this->_errorCode) {
return false;
} else if (!$this->isHttpOK()) {
$this->_errorMessage = $this->getContent();
return false;
} else {
return true;
}
} | Executes the single curl
@param string $url
@param mixed $postData
@return boolean | entailment |
public function setIdentity(IIdentity $identity = NULL)
{
if ($identity !== NULL) {
$class = get_class($identity);
// we want to convert identity entities into fake identity
// so only the identifier fields are stored,
// but we are only interested in identities which are correctly
// mapped as doctrine entities
if ($this->entityManager->getMetadataFactory()->hasMetadataFor($class)) {
$cm = $this->entityManager->getClassMetadata($class);
$identifier = $cm->getIdentifierValues($identity);
$identity = new FakeIdentity($identifier, $class);
}
}
return parent::setIdentity($identity);
} | Sets the user identity.
@return UserStorage Provides a fluent interface | entailment |
public function getIdentity()
{
$identity = parent::getIdentity();
// if we have our fake identity, we now want to
// convert it back into the real entity
// returning reference provides potentially lazy behavior
if ($identity instanceof FakeIdentity) {
return $this->entityManager->getReference($identity->getClass(), $identity->getId());
}
return $identity;
} | Returns current user identity, if any.
@return IIdentity|NULL | entailment |
protected function getPath($file = null)
{
$path = Configure::readOrFail('Thumber.target');
return $file ? $path . DS . $file : $path;
} | Gets a path for a thumbnail.
Called with the `$file` argument, returns the file absolute path.
Otherwise, called with `null`, returns the path of the target directory.
@param string|null $file File
@return string | entailment |
protected function resolveFilePath($path)
{
//Returns, if it's a remote file
if (is_url($path)) {
return $path;
}
//If it a relative path, it can be a file from a plugin or a file
// relative to `APP/webroot/img/`
if (!Folder::isAbsolute($path)) {
$pluginSplit = pluginSplit($path);
//Note that using `pluginSplit()` is not sufficient, because
// `$path` may still contain a dot
$path = WWW_ROOT . 'img' . DS . $path;
if (!empty($pluginSplit[0]) && in_array($pluginSplit[0], CorePlugin::loaded())) {
$path = CorePlugin::path($pluginSplit[0]) . 'webroot' . DS . 'img' . DS . $pluginSplit[1];
}
}
is_readable_or_fail($path);
return $path;
} | Internal method to resolve a partial path, returning a full path
@param string $path Partial path
@return string | entailment |
public function obj() {
$result = new \stdClass();
$result->items = array();
foreach ($this->dom->getItems() as $item) {
array_push($result->items, $this->getObject($item, array()));
}
return $result;
} | Retrieve microdata as a PHP object.
@return object
An object with an 'items' property, which is an array of top level
microdata items as objects with the following properties:
- type: An array of itemtype(s) for the item, if specified.
- id: The itemid of the item, if specified.
- properties: An array of itemprops. Each itemprop is keyed by the
itemprop name and has its own array of values. Values can be strings
or can be other items, represented as objects.
@todo MicrodataJS allows callers to pass in a selector for limiting the
parsing to one section of the document. Consider adding such
functionality. | entailment |
protected function getObject($item, $memory) {
$result = new \stdClass();
$result->properties = array();
// Add itemtype.
if ($itemtype = $item->itemType()) {
$result->type = $itemtype;
}
// Add itemid.
if ($itemid = $item->itemid()) {
$result->id = $itemid;
}
// Add properties.
foreach ($item->properties() as $elem) {
if ($elem->itemScope()) {
// Cannot use in_array() for comparison when values are arrays, so
// iterate and check for equality with each item in memory.
foreach ($memory as $memory_item) {
if ($memory_item === $elem) {
$value = 'ERROR';
}
}
// If the item is not in memory, there are no cycles, and thus no error.
// Recurse into the item to build out its properties.
if (!isset($value)) {
$memory[] = $item;
$value = $this->getObject($elem, $memory);
array_pop($memory);
}
}
else {
$value = $elem->itemValue();
}
foreach ($elem->itemProp() as $prop) {
$result->properties[$prop][] = $value;
}
$value = NULL;
}
return $result;
} | Helper function.
In MicrodataJS, this is handled using a closure. PHP 5.3 allows closures,
but cannot use $this within the closure. PHP 5.4 reintroduces support for
$this. When PHP 5.3/5.4 are more widely supported on shared hosting,
this function could be handled with a closure. | entailment |
protected function registerCalculator()
{
$this->app->singleton(TextSizeCalculatorInterface::class, function () {
$path = __DIR__.'/../resources/fonts/DejaVuSans.ttf';
return new GDTextSizeCalculator(realpath($path) ?: $path);
});
$this->app->singleton('badger.calculator', TextSizeCalculatorInterface::class);
} | Register the calculator class.
@return void | entailment |
protected function registerBadger()
{
$this->app->singleton(Badger::class, function (Container $app) {
$calculator = $app->make('badger.calculator');
$path = realpath($raw = __DIR__.'/../resources/templates') ?: $raw;
$renderers = [
new PlasticRender($calculator, $path),
new PlasticFlatRender($calculator, $path),
new FlatSquareRender($calculator, $path),
new SocialRender($calculator, $path),
];
return new Badger($renderers);
});
$this->app->singleton('badger', Badger::class);
} | Register the badger class.
@return void | entailment |
public function findTemplate(\WP_Query $query = null, $filters = true)
{
$leaves = (new Hierarchy())->getHierarchy($query);
if (!is_array($leaves) || empty($leaves)) {
return '';
}
$types = array_keys($leaves);
$found = '';
while (!empty($types) && !$found) {
$type = array_shift($types);
$found = $this->finder->findFirst($leaves[$type], $type);
$filters and $found = $this->applyFilter("{$type}_template", $found, $query);
}
return $found;
} | Find a template for the given WP_Query.
If no WP_Query provided, global \WP_Query is used.
By default, found template passes through "{$type}_template" filter.
{@inheritdoc} | entailment |
public function loadTemplate(\WP_Query $query = null, $filters = true, &$found = false)
{
$template = $this->findTemplate($query, $filters);
$filters and $template = $this->applyFilter('template_include', $template, $query);
$found = is_file($template) && is_readable($template);
return $found ? $this->loader->load($template) : '';
} | Find a template for the given query and load it.
If no WP_Query provided, global \WP_Query is used.
By default, found template passes through "{$type}_template" and "template_include" filters.
{@inheritdoc} | entailment |
private function applyFilter($filter, $value, \WP_Query $query = null)
{
$backup = [];
global $wp_query, $wp_the_query;
is_null($query) and $query = $wp_query;
$custom = !$query->is_main_query();
if ($custom && $wp_query instanceof \WP_Query && $wp_the_query instanceof \WP_Query) {
$backup = [$wp_query, $wp_the_query];
unset($GLOBALS['wp_query'], $GLOBALS['wp_the_query']);
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'] = $query;
}
$result = apply_filters($filter, $value);
if ($custom && $backup) {
unset($GLOBALS['wp_query'], $GLOBALS['wp_the_query']);
list($wpQuery, $wpTheQuery) = $backup;
$GLOBALS['wp_query'] = $wpQuery;
$GLOBALS['wp_the_query'] = $wpTheQuery;
}
return $result;
} | To maximize compatibility, when applying a filters and the WP_Query object we are using is
NOT the main query, we temporarily set global $wp_query and $wp_the_query to our custom query.
@param string $filter
@param string $value
@param \WP_Query $query
@return string | entailment |
public function setSecretAnswer(UserInterface $user, $questionId, $answer)
{
$class = $this->entityOptions->getSecretAnswer();
/** @var \PServerCore\Entity\SecretAnswer $secretAnswer */
$secretAnswer = new $class;
$secretAnswer->setUser($user)
->setAnswer(trim($answer))
->setQuestion($this->getQuestion4Id($questionId));
$this->entityManager->persist($user);
$this->entityManager->persist($secretAnswer);
$this->entityManager->flush();
return $secretAnswer;
} | @param UserInterface $user
@param $questionId
@param $answer
@return \PServerCore\Entity\SecretAnswer | entailment |
public function isAnswerAllowed(UserInterface $user, $answer)
{
$answerEntity = $this->getEntityManagerAnswer()->getAnswer4UserId($user->getId());
if (!$answerEntity) {
return true;
}
// @TODO better workflow, with ZendFilter
$realAnswer = strtolower(trim($answerEntity->getAnswer()));
$plainAnswer = strtolower(trim($answer));
return $realAnswer === $plainAnswer;
} | @param UserInterface $user
@param $answer
@return bool | entailment |
public function addExecutor(ExecutorInterface $executor)
{
$action = $executor->getName();
if ($this->hasExecutor($action)) {
throw new \InvalidArgumentException(sprintf(
'There is already an executor registered for action "%s".',
$action
));
}
$this->executors[$action] = $executor;
} | Add an executor.
@param ExecutorInterface $executor
@throws \InvalidArgumentException | entailment |
public function getExecutor($action)
{
if (!$this->hasExecutor($action)) {
throw new \OutOfBoundsException(sprintf(
'There is no executor registered for action "%s".',
$action
));
}
return $this->executors[$action];
} | Returns a registered executor for given action.
@param string $action
@throws \OutOfBoundsException
@return ExecutorInterface | entailment |
public function getActionStats($action)
{
try {
return $this->pheanstalk->statsTube($action);
} catch (Exception $exception) {
if (false !== strpos($exception->getMessage(), 'NOT_FOUND')) {
return null;
}
throw $exception;
}
} | @param string $action
@throws Exception
@return array | entailment |
public function add($action, array $payload, $delay = null, $priority = null, $ttr = null)
{
if (false === $this->hasExecutor($action)) {
throw new \InvalidArgumentException(sprintf(
'Action "%s" is not defined in QueueManager',
$action
));
}
if (null === $delay) {
$delay = PheanstalkInterface::DEFAULT_DELAY;
}
if (null === $priority) {
$priority = PheanstalkInterface::DEFAULT_PRIORITY;
}
if (null === $ttr) {
$ttr = $this->defaultTtr;
}
if (!is_numeric($delay)) {
$delay = strtotime(sprintf('+ %s', $delay)) - time();
}
if ($delay < 0) {
throw new \InvalidArgumentException(
sprintf('You cannot schedule a job in the past (delay was %d)', $delay)
);
}
if ($priority < 0) {
throw new \InvalidArgumentException(
sprintf('The priority for a job cannot be negative (was %d)', $priority)
);
}
$payload = json_encode($payload);
$jobId = $this->pheanstalk->putInTube($action, $payload, $priority, $delay, $ttr);
$this->logJob(
$jobId,
sprintf(
'Added job in tube "%s" with: payload: %s, priority: %d, delay: %ds, ttr: %s',
$action,
$payload,
$priority,
$delay,
$ttr
)
);
return $jobId;
} | Add a job to the queue.
@param string $action The action
@param array $payload The job's payload
@param string|int $delay The delay after which the job can be reserved.
Can be a number of seconds, or a date-diff
string relative from now, like "10 seconds".
@param int $priority From 0 (most urgent) to 0xFFFFFFFF (least urgent)
@param int $ttr Time To Run: seconds a job can be reserved for
@throws \InvalidArgumentException When the action is not defined
@throws \InvalidArgumentException When `$delay` or `$priority` is negative
@return int The job id | entailment |
public function addForObject($action, $object, $delay = null, $priority = null, $ttr = null)
{
$executor = $this->getExecutor($action);
if (!$executor instanceof ObjectPayloadInterface) {
throw new \LogicException(
sprintf(
'The executor for action "%s" cannot be used for objects. Implement the ObjectPayloadInterface in class "%s" to enable this.',
$action,
get_class($executor)
)
);
}
if (!$executor->supportsObject($object)) {
throw new \InvalidArgumentException(
sprintf(
'The executor for action "%s" does not support %s objects',
$action,
get_class($object)
)
);
}
$payload = $executor->getObjectPayload($object);
return $this->add($action, $payload, $delay, $priority, $ttr);
} | Adds a job to the queue for an object.
@param string $action The action
@param object $object The object to add a job for
@param string|int $delay The delay after which the job can be reserved.
Can be a number of seconds, or a date-diff
string relative from now, like "10 seconds".
@param int $priority From 0 (most urgent) to 0xFFFFFFFF (least urgent)
@param int $ttr Time To Run: seconds a job can be reserved for
@throws \LogicException If the executor does not accepts objects as payloads
@throws \InvalidArgumentException If the executor does not accept the given object
@throws \InvalidArgumentException When the action is not defined
@return int The job id | entailment |
public function reschedule(Job $job, \DateTime $date, $priority = PheanstalkInterface::DEFAULT_PRIORITY)
{
if ($date < new \DateTime()) {
throw new \InvalidArgumentException(
sprintf('You cannot reschedule a job in the past (got %s, and the current date is %s)', $date->format(DATE_ISO8601), date(DATE_ISO8601))
);
}
$this->pheanstalk->release($job, $priority, $date->getTimestamp() - time());
$this->logJob($job->getId(), sprintf('Rescheduled job for %s', $date->format('Y-m-d H:i:s')));
} | Reschedules a job.
@param Job $job
@param \DateTime $date
@param integer $priority
@throws \InvalidArgumentException When `$date` is in the past | entailment |
public function peek($action, $state = 'ready')
{
if (false === $this->hasExecutor($action)) {
throw new \InvalidArgumentException(sprintf(
'Action "%s" is not defined in QueueManager',
$action
));
}
$states = ['ready', 'delayed', 'buried'];
if (!in_array($state, $states)) {
throw new \InvalidArgumentException(
sprintf('$state must be one of %s, got %s', json_encode($states), json_encode($state))
);
}
$peekMethod = sprintf('peek%s', ucfirst($state));
try {
return $this->pheanstalk->$peekMethod($action);
} catch (Exception $exception) {
if (false !== strpos($exception->getMessage(), 'NOT_FOUND')) {
return null;
}
throw $exception;
}
} | Inspects the next job from the queue. Note that this does not reserve
the job, so it will still be given to a worker if/once it's ready.
@param string $action The action to peek
@param string $state The state to peek for, can be 'ready', 'delayed' or 'buried'
@throws \InvalidArgumentException When $action is not a defined action
@throws \InvalidArgumentException When $state is not a valid state
@throws Exception When Pheanstalk decides to do this
@return Job The next job for the given state, or null if there is no next job | entailment |
public function delete(Job $job)
{
$this->pheanstalk->delete($job);
$this->logJob($job->getId(), 'Job deleted');
} | Permanently deletes a job.
@param Job $job | entailment |
public function bury(Job $job)
{
$this->pheanstalk->bury($job);
$this->logJob($job->getId(), 'Job buried');
} | Puts a job into a 'buried' state, revived only by 'kick' command.
@param Job $job | entailment |
public function kick($action, $max)
{
$this->pheanstalk->useTube($action);
$kicked = $this->pheanstalk->kick($max);
$this->logger->debug(
sprintf('Kicked %d "%s" jobs back onto the ready queue', $kicked, $action)
);
return $kicked;
} | Puts a job into a 'buried' state, revived only by 'kick' command.
@param string $action
@param int $max
@return int The number of kicked jobs | entailment |
public function executeJob(Job $job, $maxRetries = 1)
{
$this->dispatcher->dispatch(WorkerEvents::EXECUTE_JOB, new JobEvent($job));
$stats = $this->pheanstalk->statsJob($job);
$payload = (array) json_decode($job->getData(), true);
$releases = intval($stats['releases']);
$priority = intval($stats['pri']);
// context for logging
$context = [
'tube' => $stats['tube'],
'payload' => $payload,
'attempt' => $releases + 1,
];
try {
// execute command
$result = $this->execute($stats['tube'], $payload);
// delete job if it completed without exceptions
$this->delete($job);
return $result;
} catch (RescheduleException $re) {
// Override priority if the RescheduleException provides a new one.
if (!is_null($re->getReshedulePriority())) {
$priority = $re->getReshedulePriority();
}
// reschedule the job
$this->reschedule($job, $re->getRescheduleDate(), $priority);
} catch (AbortException $e) {
// abort thrown from executor, rethrow it and let the caller handle it
throw $e;
} catch (\Throwable $e) {
// some other exception occured
$message = sprintf('Exception occurred: %s in %s on line %d', $e->getMessage(), $e->getFile(), $e->getLine());
$this->logJob($job->getId(), $message, LogLevel::ERROR, $context);
$this->logJob($job->getId(), $e->getTraceAsString(), LogLevel::DEBUG, $context);
// see if we have any retries left
if ($releases > $maxRetries) {
// no more retries, bury job for manual inspection
$this->bury($job);
$this->dispatcher->dispatch(WorkerEvents::JOB_BURIED_EVENT, new JobBuriedEvent($job, $e, $releases));
} else {
// try again, regardless of the error
$this->reschedule($job, new \DateTime('+10 minutes'), $priority);
}
}
return false;
} | @param Job $job The job to process
@param int $maxRetries The number of retries for this job
@throws AbortException
@return bool|mixed The executor result if successful, false otherwise | entailment |
public function execute($action, array $payload)
{
$executor = $this->getExecutor($action);
// dispatch pre event, listeners may change the payload here
$event = new ExecutionEvent($executor, $action, $payload);
$this->dispatcher->dispatch(WorkerEvents::PRE_EXECUTE_ACTION, $event);
try {
$resolver = $this->getPayloadResolver($executor);
$payload = $resolver->resolve($event->getPayload());
} catch (ExceptionInterface $exception) {
$this->logger->error(
sprintf(
'Payload %s for "%s" is invalid: %s',
json_encode($payload, JSON_UNESCAPED_SLASHES),
$action,
$exception->getMessage()
)
);
return false;
}
$result = $executor->execute($payload);
// dispatch post event, listeners may change the result here
$event->setResult($result);
$this->dispatcher->dispatch(WorkerEvents::POST_EXECUTE_ACTION, $event);
return $event->getResult();
} | Executes an action with a specific payload.
@param string $action
@param array $payload
@return mixed | entailment |
public function clear($action, array $states = [])
{
if (empty($states)) {
$states = ['ready', 'delayed', 'buried'];
}
foreach ($states as $state) {
$this->clearTube($action, $state);
}
} | CAUTION: this removes all items from an action's queue.
This is an irreversible action!
@param string $action
@param array $states | entailment |
protected function clearTube($tube, $state = 'ready')
{
$this->logger->info(sprintf('Clearing all jobs with the "%s" state in tube "%s"', $state, $tube));
while ($job = $this->peek($tube, $state)) {
try {
$this->delete($job);
} catch (Exception $e) {
// job could have been deleted by another process
if (false === strpos($e->getMessage(), 'NOT_FOUND')) {
throw $e;
}
}
}
} | @param string $tube
@param string $state
@throws Exception | entailment |
protected function getPayloadResolver(ExecutorInterface $executor)
{
$key = $executor->getName();
if (!array_key_exists($key, $this->resolvers)) {
$resolver = new OptionsResolver();
$executor->configurePayload($resolver);
$this->resolvers[$key] = $resolver;
}
return $this->resolvers[$key];
} | Returns a cached version of the payload resolver for an executor.
@param ExecutorInterface $executor
@return OptionsResolver | entailment |
public function addLoader(TemplateLoaderInterface $loader, callable $predicate)
{
$this->loaders[] = [$loader, $predicate, false];
return $this;
} | {@inheritdoc} | entailment |
public function load($templatePath)
{
$loaders = $this->loaders;
foreach ($loaders as $i => $loaderData) {
list($loader, $predicate, $isFactory) = $loaderData;
if (!$predicate($templatePath)) {
continue;
}
if (!$isFactory) {
/* @var \Brain\Hierarchy\Loader\TemplateLoaderInterface $loader */
return $loader->load($templatePath);
}
$loader = $loader();
if (!$loader instanceof TemplateLoaderInterface) {
continue;
}
return $loader->load($templatePath);
}
return '';
} | {@inheritdoc} | entailment |
protected function instantiateLocator()
{
if (empty($this->config['locator class']))
{
$this->locator = new Locators;
return;
}
$class = $this->config['locator class'];
$this->locator = new $class;
} | Function to instantiate the Locator Class, In case of a custom Template,
path to the custom Template Locator could be passed in Acceptance.suite.yml file
for example: If the Class is present at _support/Page/Acceptance folder, simple add a new Parameter in acceptance.suite.yml file
locator class: 'Page\Acceptance\Bootstrap2TemplateLocators'
Locator could be set to null like this
locator class: null
When set to null, Joomla Browser will use the custom Locators present inside Locators.php
@return void
@since 3.0.0 | entailment |
public function getLocatorPath($path)
{
if (!isset($this->locator->$path))
{
return false;
}
return $this->locator->$path;
} | Locator getter
@param string $path Locator to get
@return mixed|false
@since 3.8.11 | entailment |
public function doAdministratorLogin($user = null, $password = null, $useSnapshot = true)
{
if (is_null($user))
{
$user = $this->config['username'];
}
if (is_null($password))
{
$password = $this->config['password'];
}
$this->debug('I open Joomla Administrator Login Page');
$this->amOnPage($this->locator->adminLoginPageUrl);
if ($useSnapshot && $this->loadSessionSnapshot($user))
{
return;
}
$this->waitForElement($this->locator->adminLoginUserName, TIMEOUT);
$this->debug('Fill Username Text Field');
$this->fillField($this->locator->adminLoginUserName, $user);
$this->debug('Fill Password Text Field');
$this->fillField($this->locator->adminLoginPassword, $password);
// @todo: update login button in joomla login screen to make this xPath more friendly
$this->debug('I click Login button');
$this->click($this->locator->adminLoginButton);
$this->debug('I wait to see Administrator Control Panel');
$this->waitForText($this->locator->adminControlPanelText, 4, $this->locator->controlPanelLocator);
if ($useSnapshot)
{
$this->saveSessionSnapshot($user);
}
} | Function to Do Admin Login In Joomla!
@param string|null $user Optional Username. If not passed the one in acceptance.suite.yml will be used
@param string|null $password Optional password. If not passed the one in acceptance.suite.yml will be used
@param bool $useSnapshot Whether or not you want to reuse the session from previous login. Enabled by default.
@return void
@since 3.0.0
@throws \Exception | entailment |
public function doFrontEndLogin($user = null, $password = null)
{
if (is_null($user))
{
$user = $this->config['username'];
}
if (is_null($password))
{
$password = $this->config['password'];
}
$this->debug('I open Joomla Frontend Login Page');
$this->amOnPage($this->locator->frontEndLoginUrl);
$this->debug('Fill Username Text Field');
$this->fillField($this->locator->loginUserName, $user);
$this->debug('Fill Password Text Field');
$this->fillField($this->locator->loginPassword, $password);
// @todo: update login button in joomla login screen to make this xPath more friendly
$this->debug('I click Login button');
$this->click($this->locator->loginButton);
$this->debug('I wait to see Frontend Member Profile Form with the Logout button in the module');
$this->waitForElement($this->locator->frontEndLoginSuccess, TIMEOUT);
} | Function to Do Frontend Login In Joomla!
@param string|null $user Optional username. If not passed the one in acceptance.suite.yml will be used
@param string|null $password Optional password. If not passed the one in acceptance.suite.yml will be used
@return void
@since 3.0.0
@throws \Exception | entailment |
public function doFrontendLogout()
{
$this->debug('I open Joomla Frontend Login Page');
$this->amOnPage($this->locator->frontEndLoginUrl);
$this->debug('I click Logout button');
$this->click($this->locator->frontEndLogoutButton);
$this->amOnPage('/index.php?option=com_users&view=login');
$this->debug('I wait to see Login form');
$this->waitForElement($this->locator->frontEndLoginForm, 30);
$this->seeElement($this->locator->frontEndLoginForm);
} | Function to Do frontend Logout in Joomla!
@return void
@since 3.0.0
@throws \Exception | entailment |
public function installJoomla($databaseName = null, $databasePrefix = null)
{
if (is_null($databaseName))
{
$databaseName = $this->config['database name'];
}
if (is_null($databasePrefix))
{
$databasePrefix = $this->config['database prefix'];
}
$this->debug('I open Joomla Installation Configuration Page');
$this->amOnPage('/installation/index.php');
$this->debug(
'I check that FTP tab is not present in installation. Otherwise it means that I have not enough '
. 'permissions to install joomla and execution will be stopped'
);
$this->dontSeeElement(array('id' => 'ftp'));
// I Wait for the text Main Configuration, meaning that the page is loaded
$this->debug('I wait for Main Configuration');
$this->waitForElement('#jform_language', 10);
$this->debug('Wait for chosen to render the Languages list field');
$this->wait(2);
$this->debug('I select es-ES as installation language');
// Select a random language to force reloading of the lang strings after selecting English
$this->selectOptionInChosenWithTextField('#jform_language', 'Español (España)');
$this->waitForText('Configuración principal', TIMEOUT, 'h3');
// Wait for chosen to render the field
$this->debug('I select en-GB as installation language');
$this->debug('Wait for chosen to render the Languages list field');
$this->wait(2);
$this->selectOptionInChosenWithTextField('#jform_language', 'English (United Kingdom)');
$this->waitForText('Main Configuration', TIMEOUT, 'h3');
$this->debug('I fill Site Name');
$this->fillField(array('id' => 'jform_site_name'), 'Joomla CMS test');
$this->debug('I fill Site Description');
$this->fillField(array('id' => 'jform_site_metadesc'), 'Site for testing Joomla CMS');
// I get the configuration from acceptance.suite.yml (see: tests/_support/acceptancehelper.php)
$this->debug('I fill Admin Email');
$this->fillField(array('id' => 'jform_admin_email'), $this->config['admin email']);
$this->debug('I fill Admin Username');
$this->fillField(array('id' => 'jform_admin_user'), $this->config['username']);
$this->debug('I fill Admin Password');
$this->fillField(array('id' => 'jform_admin_password'), $this->config['password']);
$this->debug('I fill Admin Password Confirmation');
$this->fillField(array('id' => 'jform_admin_password2'), $this->config['password']);
$this->debug('I click Site Offline: no');
// ['No Site Offline']
$this->click(array('xpath' => "//fieldset[@id='jform_site_offline']/label[@for='jform_site_offline1']"));
$this->debug('I click Next');
$this->click(array('link' => 'Next'));
$this->debug('I Fill the form for creating the Joomla site Database');
$this->waitForText('Database Configuration', TIMEOUT, array('css' => 'h3'));
$this->debug('I select MySQLi');
$this->selectOption(array('id' => 'jform_db_type'), $this->config['database type']);
$this->debug('I fill Database Host');
$this->fillField(array('id' => 'jform_db_host'), $this->config['database host']);
$this->debug('I fill Database User');
$this->fillField(array('id' => 'jform_db_user'), $this->config['database user']);
$this->debug('I fill Database Password');
$this->fillField(array('id' => 'jform_db_pass'), $this->config['database password']);
$this->debug('I fill Database Name');
$this->fillField(array('id' => 'jform_db_name'), $databaseName);
$this->debug('I fill Database Prefix');
$this->fillField(array('id' => 'jform_db_prefix'), $databasePrefix);
$this->debug('I click Remove Old Database ');
$this->selectOptionInRadioField('Old Database Process', 'Remove');
$this->debug('I click Next');
$this->click(array('link' => 'Next'));
$this->debug('I wait Joomla to remove the old database if exist');
$this->wait(1);
$this->waitForElementVisible(array('id' => 'jform_sample_file-lbl'), 30);
$this->debug('I install joomla with or without sample data');
$this->waitForText('Finalisation', TIMEOUT, array('xpath' => '//h3'));
// @todo: installation of sample data needs to be created
// No sample data
$this->selectOption(array('id' => 'jform_sample_file'), array('id' => 'jform_sample_file0'));
$this->click(array('link' => 'Install'));
// Wait while Joomla gets installed
$this->debug('I wait for Joomla being installed');
$this->waitForText('Congratulations! Joomla! is now installed.', TIMEOUT, array('xpath' => '//h3'));
} | Installs Joomla
@param string|null $databaseName Optional Database Name. If not passed the one in acceptance.suite.yml will be used
@param string|null $databasePrefix Optional Database Prefix. If not passed the one in acceptance.suite.yml will be used
@return void
@since 3.0.0
@throws \Exception | entailment |
public function installJoomlaRemovingInstallationFolder($databaseName = null, $databasePrefix = null)
{
$this->installJoomla($databaseName, $databasePrefix);
$this->debug('Removing Installation Folder');
$this->click(array('xpath' => "//input[@value='Remove \"installation\" folder']"));
$this->debug('I wait for Removing Installation Folder button to become disabled');
$this->waitForJS("return jQuery('form#adminForm input[name=instDefault]').attr('disabled') == 'disabled';", TIMEOUT);
$this->debug('Joomla is now installed');
$this->see('Congratulations! Joomla! is now installed.', '//h3');
} | Install Joomla removing the Installation folder at the end of the execution
@param string|null $databaseName Optional Database Name. If not passed the one in acceptance.suite.yml will be used
@param string|null $databasePrefix Optional Database Prefix. If not passed the one in acceptance.suite.yml will be used
@return void
@since 3.0.0
@throws \Exception | entailment |
public function installJoomlaMultilingualSite($languages = array(), $databaseName = null, $databasePrefix = null)
{
if (!$languages)
{
// If no language is passed French will be installed by default
$languages[] = 'French';
}
$this->installJoomla($databaseName, $databasePrefix);
$this->debug('I go to Install Languages page');
$this->click(array('id' => 'instLangs'));
$this->waitForText('Install Language packages', TIMEOUT, array('xpath' => '//h3'));
foreach ($languages as $language)
{
$this->debug('I mark the checkbox of the language: ' . $language);
$this->click(array('xpath' => "//label[contains(text()[normalize-space()], '$language')]"));
}
$this->click(array('link' => 'Next'));
$this->waitForText('Multilingual', TIMEOUT, array('xpath' => '//h3'));
$this->selectOptionInRadioField('Activate the multilingual feature', 'Yes');
$this->waitForElementVisible(array('id' => 'jform_activatePluginLanguageCode-lbl'));
$this->selectOptionInRadioField('Install localised content', 'Yes');
$this->selectOptionInRadioField('Enable the language code plugin', 'Yes');
$this->click(array('link' => 'Next'));
$this->waitForText('Congratulations! Joomla! is now installed.', TIMEOUT, array('xpath' => '//h3'));
$this->debug('Removing Installation Folder');
$this->click(array('xpath' => "//input[@value='Remove \"installation\" folder']"));
// @todo https://github.com/joomla-projects/joomla-browser/issues/45
$this->wait(2);
$this->debug('Joomla is now installed');
$this->see('Congratulations! Joomla! is now installed.', '//h3');
} | Installs Joomla with Multilingual Feature active
@param array $languages Array containing the language names to be installed
@param string|null $databaseName Optional Database Name. If not passed the one in acceptance.suite.yml will be used
@param string|null $databasePrefix Optional Database Prefix. If not passed the one in acceptance.suite.yml will be used
@example: $this->installJoomlaMultilingualSite(['Spanish', 'French']);
@return void
@since 3.0.0
@throws \Exception | entailment |
public function setErrorReportingToDevelopment()
{
$this->debug('I open Joomla Global Configuration Page');
$this->amOnPage('/administrator/index.php?option=com_config');
$this->debug('I wait for Global Configuration title');
$this->waitForText('Global Configuration', TIMEOUT, array('css' => '.page-title'));
$this->debug('I open the Server Tab');
$this->click(array('link' => 'Server'));
$this->debug('I wait for error reporting dropdown');
$this->selectOptionInChosen('Error Reporting', 'Development');
$this->debug('I click on save');
$this->click(array('xpath' => "//div[@id='toolbar-apply']//button"));
$this->debug('I wait for global configuration being saved');
$this->waitForText('Global Configuration', TIMEOUT, array('css' => '.page-title'));
$this->see('Configuration saved.', '#system-message-container');
} | Sets in Administrator->Global Configuration the Error reporting to Development
{@internal doAdminLogin() before}
@return void
@since 3.0.0
@throws \Exception | entailment |
public function installExtensionFromFolder($path, $type = 'Extension')
{
$this->amOnPage('/administrator/index.php?option=com_installer');
$this->waitForText('Extensions: Install', '30', array('css' => 'H1'));
$this->click(array('link' => 'Install from Folder'));
$this->debug('I enter the Path');
$this->fillField(array('id' => 'install_directory'), $path);
$this->click(array('id' => 'installbutton_directory'));
$this->waitForText('was successful', TIMEOUT, array('id' => 'system-message-container'));
$this->debug("$type successfully installed from $path");
} | Installs a Extension in Joomla that is located in a folder inside the server
@param String $path Path for the Extension
@param string $type Type of Extension
{@internal doAdminLogin() before}
@return void
@since 3.0.0
@throws \Exception | entailment |
public function installExtensionFromUrl($url, $type = 'Extension')
{
$this->amOnPage('/administrator/index.php?option=com_installer');
$this->waitForText('Extensions: Install', '30', array('css' => 'H1'));
$this->click(array('link' => 'Install from URL'));
$this->debug('I enter the url');
$this->fillField(array('id' => 'install_url'), $url);
$this->click(array('id' => 'installbutton_url'));
$this->waitForText('was successful', '30', array('id' => 'system-message-container'));
if ($type == 'Extension')
{
$this->debug('Extension successfully installed from ' . $url);
}
if ($type == 'Plugin')
{
$this->debug('Installing plugin was successful.' . $url);
}
if ($type == 'Package')
{
$this->debug('Installation of the package was successful.' . $url);
}
} | Installs a Extension in Joomla that is located in a url
@param String $url Url address to the .zip file
@param string $type Type of Extension
{@internal doAdminLogin() before}
@return void
@since 3.0.0
@throws \Exception | entailment |
public function installExtensionFromFileUpload($file, $type = 'Extension')
{
$this->amOnPage('/administrator/index.php?option=com_installer');
$this->waitForText('Extensions: Install', '30', array('css' => 'H1'));
$this->click(array('link' => 'Upload Package File'));
$this->debug('I make sure legacy uploader is visible');
$this->executeJS('document.getElementById("legacy-uploader").style.display="block";');
$this->debug('I enter the file input');
$this->attachFile(array('id' => 'install_package'), $file);
$this->waitForText('was successful', '30', array('id' => 'system-message-container'));
if ($type == 'Extension')
{
$this->debug('Extension successfully installed.');
}
if ($type == 'Plugin')
{
$this->debug('Installing plugin was successful.');
}
if ($type == 'Package')
{
$this->debug('Installation of the package was successful.');
}
} | Installs a Extension in Joomla using the file upload option
@param string $file Path to the file in the _data folder
@param string $type Type of Extension
{@internal doAdminLogin() before}
@return void
@throws \Exception | entailment |
public function checkForPhpNoticesOrWarnings($page = null)
{
if ($page)
{
$this->amOnPage($page);
}
$this->dontSeeInPageSource('Notice:');
$this->dontSeeInPageSource('<b>Notice</b>:');
$this->dontSeeInPageSource('Warning:');
$this->dontSeeInPageSource('<b>Warning</b>:');
$this->dontSeeInPageSource('Strict standards:');
$this->dontSeeInPageSource('<b>Strict standards</b>:');
$this->dontSeeInPageSource('The requested page can\'t be found');
} | Function to check for PHP Notices or Warnings
@param string $page Optional, if not given checks will be done in the current page
{@internal doAdminLogin() before}
@return void
@since 3.0.0 | entailment |
public function selectOptionInRadioField($label, $option)
{
$this->debug("Trying to select the $option from the $label");
$label = $this->findField(array('xpath' => "//label[contains(normalize-space(string(.)), '$label')]"));
$radioId = $label->getAttribute('for');
$this->click("//fieldset[@id='$radioId']/label[contains(normalize-space(string(.)), '$option')]");
} | Selects an option in a Joomla Radio Field based on its label
@param string $label The text in the <label> with for attribute that links to the radio element
@param string $option The text in the <option> to be selected in the chosen radio button
@return void
@since 3.0.0 | entailment |
public function selectOptionInChosen($label, $option)
{
$select = $this->findField($label);
$selectID = $select->getAttribute('id');
$chosenSelectID = $selectID . '_chzn';
$this->debug("I open the $label chosen selector");
$this->click(array('xpath' => "//div[@id='$chosenSelectID']/a/div/b"));
$this->debug("I select $option");
$this->click(array('xpath' => "//div[@id='$chosenSelectID']//li[text()='$option']"));
// Gives time to chosen to close
$this->wait(1);
} | Selects an option in a Chosen Selector based on its label
@param string $label The text in the <label> with for attribute that links to the <select> element
@param string $option The text in the <option> to be selected in the chosen selector
@return void
@since 3.0.0 | entailment |
public function selectOptionInChosenWithTextField($label, $option)
{
$select = $this->findField($label);
$selectID = $select->getAttribute('id');
$chosenSelectID = $selectID . '_chzn';
$this->debug("I open the $label chosen selector");
$this->click(array('css' => 'div#' . $chosenSelectID));
$this->debug("I select $option");
$this->fillField(array('xpath' => "//div[@id='$chosenSelectID']/div/div/input"), $option);
$this->click(array('xpath' => "//div[@id='$chosenSelectID']/div/ul/li[1]"));
// Gives time to chosen to close
$this->wait(1);
} | Selects an option in a Chosen Selector based on its label with filling the textfield
@param string $label The text in the <label> with for attribute that links to the <select> element
@param string $option The text in the <option> to be selected in the chosen selector
@return void
@since 3.0.0 | entailment |
public function selectOptionInChosenById($selectId, $option)
{
$chosenSelectID = $selectId . '_chzn';
$this->debug("I open the $chosenSelectID chosen selector");
$this->click(array('xpath' => "//div[@id='$chosenSelectID']/a/div/b"));
$this->debug("I select $option");
$this->click(array('xpath' => "//div[@id='$chosenSelectID']//li[text()='$option']"));
// Gives time to chosen to close
$this->wait(1);
} | Selects an option in a Chosen Selector based on its id
@param string $selectId The id of the <select> element
@param string $option The text in the <option> to be selected in the chosen selector
@return void | entailment |
public function selectOptionInChosenByIdUsingJs($selectId, $option)
{
$option = trim($option);
$this->executeJS("jQuery('#$selectId option').filter(function(){ return this.text.trim() === \"$option\" }).prop('selected', true);");
$this->executeJS("jQuery('#$selectId').trigger('liszt:updated').trigger('chosen:updated');");
$this->executeJS("jQuery('#$selectId').trigger('change');");
// Give time to Chosen to update
$this->wait(1);
} | Selects an option in a Chosen Selector based on its id
@param string $selectId The id of the <select> element
@param string $option The text in the <option> to be selected in the chosen selector
@return void
@since 3.0.0 | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.