sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function checkoutComplete($order_id)
{
$this->setOrderCheckoutComplete($order_id);
$this->controlAccessCheckoutComplete();
$this->setTitleCheckoutComplete();
$this->setBreadcrumbCheckoutComplete();
$this->setData('message', $this->getMessageCheckoutComplete());
$this->setDataTemplatesCheckoutComplete();
$this->hook->attach('order.complete.page', $this->data_order, $this->order, $this);
$this->outputCheckoutComplete();
} | Page callback
Displays the checkout complete page
@param int $order_id | entailment |
protected function setDataTemplatesCheckoutComplete()
{
$templates = array(
'payment' => $this->getPaymentMethodTemplate('complete', $this->data_order, $this->payment),
'shipping' => $this->getShippingMethodTemplate('complete', $this->data_order, $this->shipping)
);
$this->setData('rendered', $templates);
} | Sets payment/shipping method templates on the checkout complete page | entailment |
protected function setOrderCheckoutComplete($order_id)
{
$this->data_order = $this->order->get($order_id);
if (empty($this->data_order)) {
$this->outputHttpStatus(404);
}
$this->prepareOrderCheckoutComplete($this->data_order);
} | Load and set an order from the database
@param integer $order_id | entailment |
protected function prepareOrderCheckoutComplete(array &$order)
{
$this->setItemTotalFormatted($order, $this->price);
$this->setItemTotalFormattedNumber($order, $this->price);
} | Prepare the order data
@param array $order | entailment |
protected function controlAccessCheckoutComplete()
{
if (empty($this->data_order['user_id']) || $this->data_order['user_id'] !== $this->cart_uid) {
$this->outputHttpStatus(403);
}
if (!$this->order->isPending($this->data_order)) {
$this->outputHttpStatus(403);
}
} | Controls access to the checkout complete page | entailment |
public function listAddress()
{
$this->actionListAddress();
$this->setTitleListAddress();
$this->setBreadcrumbListAddress();
$this->setFilterListAddress();
$this->setPagerlListAddress();
$this->setData('addresses', $this->getListAddress());
$this->outputListAddress();
} | Page callback
Displays the address overview page | entailment |
protected function actionListAddress()
{
list($selected, $action) = $this->getPostedAction();
$deleted = 0;
foreach ($selected as $id) {
if ($action === 'delete' && $this->access('address_delete')) {
$deleted += (int) $this->address->delete($id);
}
}
if ($deleted > 0) {
$message = $this->text('Deleted %num item(s)', array('%num' => $deleted));
$this->setMessage($message, 'success');
}
} | Applies an action to the selected aliases | entailment |
protected function setPagerlListAddress()
{
$conditions = $this->query_filter;
$conditions['count'] = true;
$pager = array(
'query' => $this->query_filter,
'total' => (int) $this->address->getList($conditions)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function getListAddress()
{
$conditions = $this->query_filter;
$conditions['limit'] = $this->data_limit;
$addresses = (array) $this->address->getList($conditions);
$this->prepareListAddress($addresses);
return $addresses;
} | Returns an array of addresses using pager limits and the URL query conditions
@return array | entailment |
protected function prepareListAddress(array &$addresses)
{
foreach ($addresses as &$address) {
$address['translated'] = $this->address->getTranslated($address, true);
}
} | Prepares an array of addresses
@param array $addresses | entailment |
public function listAlias()
{
$this->actionListAlias();
$this->setTitleListAlias();
$this->setBreadcrumbListAlias();
$this->setFilterListAlias();
$this->setPagerListAlias();
$this->setData('aliases', $this->getListAlias());
$this->setData('handlers', $this->alias->getHandlers());
$this->outputListAlias();
} | Page callback
Displays the alias overview page | entailment |
protected function actionListAlias()
{
list($selected, $action) = $this->getPostedAction();
$deleted = 0;
foreach ($selected as $id) {
if ($action === 'delete' && $this->access('alias_delete')) {
$deleted += (int) $this->alias->delete($id);
}
}
if ($deleted > 0) {
$message = $this->text('Deleted %num item(s)', array('%num' => $deleted));
$this->setMessage($message, 'success');
}
} | Applies an action to the selected aliases | entailment |
protected function setPagerListAlias()
{
$conditions = $this->query_filter;
$conditions['count'] = true;
$pager = array(
'query' => $this->query_filter,
'total' => (int) $this->alias->getList($conditions)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function getListAlias()
{
$conditions = $this->query_filter;
$conditions['limit'] = $this->data_limit;
return (array) $this->alias->getList($conditions);
} | Returns an array of aliases using the pager limits and conditions from the URL query
@return array | entailment |
public function load($file, $type = null)
{
$path = $this->locator->locate($file);
$config = array();
$result = parse_ini_file($path, true);
if (false === $result || array() === $result) {
throw new InvalidArgumentException(sprintf('The "%s" file is not valid.', $file));
}
if (isset($result['parameters']) && is_array($result['parameters'])) {
$config['parameters'] = array();
foreach ($result['parameters'] as $key => $value) {
$config['parameters'][$key] = $value;
}
}
} | Loads a resource.
@param mixed $file The resource
@param string $type The resource type
@throws InvalidArgumentException When ini file is not valid | entailment |
public function handle($request, Closure $next, $acceptedPostTypes)
{
$acceptedPostTypes = explode('|', $acceptedPostTypes);
$message = $request->route('post_type') . ' post type is not supported. ';
$authorized = false;
// Lets verify that we are authorized to use this post type
if(in_array($request->route('post_type'), $acceptedPostTypes)){
$authorized = true;
$message = '';
// We need to validate access of the sub post type for the taxonomy API. Lets check if we are using this method
if(array_key_exists('sub_post_type', $request->route()->parameters)){
// There is sub post type in the request, we need to authorize
$authorized = false;
$message .= $request->route('sub_post_type') . ' post type is not supported.';
// Lets authorize the variable
if(in_array($request->route('sub_post_type'), $acceptedPostTypes)){
$authorized = true;
}
// We can continue authorized because there is no sub post type in the request
} else {
$authorized = true;
}
}
if(!$authorized){
$hint = 'Verify if you are authorized to use this post type.';
return response()->json([
'code' => 'unsupported_post_type',
'errors' => [
'unsupported_post_type' => [
0 => $message . $hint,
],
],
'hint' => $hint,
], 400);
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
public function store(array &$submitted, array $options)
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateStore();
$this->validateBool('status');
$this->validateDomainStore();
$this->validateBasepathStore();
$this->validateName();
$this->validateDataStore();
$this->validateImagesStore();
$this->validateDefaultStore();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs store data validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validateStore()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null; // Adding a new store
}
$data = $this->store->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('Store'));
return false;
}
$this->setUpdating($data);
$this->setSubmitted('default', $this->store->isDefault($data['store_id']));
return true;
} | Validates a store to be updated
@return boolean|null | entailment |
protected function validateDomainStore()
{
$field = 'domain';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
if ($this->getSubmitted('default')) {
$this->unsetSubmitted('domain'); // Cannot update domain of default store
return null;
}
$label = $this->translation->text('Domain');
if (empty($value)) {
$this->setErrorRequired($field, $label);
}
$updating = $this->getUpdating();
if (isset($updating['domain']) && $updating['domain'] === $value) {
return true;
}
$existing = $this->store->get($value);
if (!empty($existing)) {
$this->setErrorExists($field, $label);
return false;
}
return true;
} | Validates a domain
@return boolean|null | entailment |
protected function validateBasepathStore()
{
$field = 'basepath';
if ($this->isExcluded($field) || $this->isError('domain')) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
if ($this->getSubmitted('default')) {
$this->unsetSubmitted($field);
return null; // Cannot update basepath of default store
}
$updating = $this->getUpdating();
if (isset($updating['basepath'])
&& $updating['basepath'] === $value
&& $updating['domain'] === $this->getSubmitted('domain')) {
return true;
}
if (preg_match('/^[a-z0-9-]{0,50}$/', $value) !== 1) {
$this->setErrorInvalid($field, $this->translation->text('Path'));
return false;
}
return true;
} | Validates a store base path
@return boolean|null | entailment |
protected function validateDataStore()
{
$field = 'data';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating()) {
if (!isset($value)) {
$this->unsetSubmitted($field);
return null;
}
} else if (empty($value)) {
$value = $this->store->getConfig(null, $this->store->getDefault());
// Will be set later
unset($value['title'], $value['meta_title']);
}
if (!is_array($value)) {
$this->setErrorInvalid($field, $this->translation->text('Settings'));
return false;
}
$this->setSubmitted('data', $value);
$this->validateDataTitleStore();
$this->validateDataEmailStore();
$this->validateDataMapStore();
$this->validateDataMetaTitleStore();
$this->validateDataMetaDescriptionStore();
$this->validateDataTranslationStore();
$this->validateDataThemeStore();
return !$this->isError();
} | Validate "data" field
@return null|bool | entailment |
protected function validateDataTitleStore()
{
$field = 'data.title';
$value = $this->getSubmitted($field);
if (empty($value) && !$this->isError('name')) {
$this->setSubmitted($field, $this->getSubmitted('name'));
}
$options = $this->options;
$this->options += array('parents' => 'data');
$result = $this->validateTitle();
$this->options = $options;
return $result;
} | Validates a store title
@return boolean|null | entailment |
protected function validateDataEmailStore()
{
$field = 'data.email';
$value = $this->getSubmitted($field);
$label = $this->translation->text('E-mail');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
if (!is_array($value)) {
$this->setErrorInvalid($field, $label);
return false;
}
$filtered = array_filter($value, function ($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
if (count($value) != count($filtered)) {
$this->setErrorInvalid($field, $label);
return false;
}
return true;
} | Validates E-mails
@return boolean|null | entailment |
protected function validateDataMapStore()
{
$field = 'data.map';
$value = $this->getSubmitted($field);
if (empty($value)) {
return null;
}
$label = $this->translation->text('Map');
if (!is_array($value) || count($value) != 2) {
$this->setErrorInvalid($field, $label);
return false;
}
if (count($value) != count(array_filter($value, 'is_numeric'))) {
$this->setErrorInvalid($field, $label);
return false;
}
return true;
} | Validates map coordinates
@return boolean|null | entailment |
protected function validateDataMetaTitleStore()
{
$field = 'data.meta_title';
$value = $this->getSubmitted($field);
if (empty($value) && !$this->isError('name')) {
$this->setSubmitted($field, $this->getSubmitted('name'));
}
$options = $this->options;
$this->options += array('parents' => 'data');
$result = $this->validateMetaTitle();
$this->options = $options;
return $result;
} | Validates "meta_title" field
@return boolean|null | entailment |
protected function validateDataMetaDescriptionStore()
{
$options = $this->options;
$this->options += array('parents' => 'data');
$result = $this->validateMetaDescription();
$this->options = $options;
return $result;
} | Validates "meta_description" field
@return boolean|null | entailment |
protected function validateDataTranslationStore()
{
$options = $this->options;
$this->options += array('parents' => 'data');
$result = $this->validateTranslation();
$this->options = $options;
return $result;
} | Validates translatable fields
@return boolean|null | entailment |
protected function validateDataThemeStore()
{
$field = 'data.theme';
$value = $this->getSubmitted($field);
$module = $this->module->get($value);
if (isset($module['type']) && $module['type'] === 'theme' && !empty($module['status'])) {
return true;
}
$this->setErrorUnavailable($field, $this->translation->text('Theme'));
return false;
} | Validates theme module IDs
@return boolean | entailment |
protected function validateImagesStore()
{
if ($this->isError()) {
return null;
}
$error = false;
foreach (array('logo', 'favicon') as $field) {
if ($this->getSubmitted("delete_$field")) {
$this->setSubmitted("data.$field", '');
}
$file = $this->request->file($field);
if (empty($file)) {
continue;
}
$result = $this->file_transfer->upload($file, null, 'image/upload/store');
if ($result !== true) {
$error = true;
$this->setError($field, (string) $result);
continue;
}
$this->setSubmitted("data.$field", $this->file_transfer->getTransferred(true));
}
return empty($error);
} | Validates uploaded favicon
@return boolean | entailment |
protected function validateDefaultStore()
{
$id = $this->getUpdatingId();
if (!empty($id) && $this->store->isDefault($id)) {
$this->unsetSubmitted('domain');
$this->unsetSubmitted('basepath');
}
} | Validates default store | entailment |
public function getItems(array $conditions = array())
{
$list = $this->getList($conditions);
if (empty($list)) {
return array();
}
$handler_id = null;
$items = array();
foreach ((array) $list as $item) {
$handler_id = $item['type'];
$items[$item['entity_id']] = $item;
}
$handlers = $this->collection->getHandlers();
$entity_conditions = array(
'status' => isset($conditions['status']) ? $conditions['status'] : null,
$handlers[$handler_id]['entity'] . '_id' => array_keys($items)
);
$entities = $this->getListEntities($handler_id, $entity_conditions);
if (empty($entities)) {
return array();
}
foreach ($entities as $entity_id => &$entity) {
if (isset($items[$entity_id])) {
$entity['weight'] = $items[$entity_id]['weight'];
$entity['collection_item'] = $items[$entity_id];
$entity['collection_handler'] = $handlers[$handler_id];
}
}
gplcart_array_sort($entities);
return $entities;
} | Returns an array of collection item entities
@param array $conditions
@return array | entailment |
public function getItem(array $conditions = array())
{
$list = $this->getItems($conditions);
if (empty($list)) {
return $list;
}
return reset($list);
} | Returns a single entity item
@param array $conditions
@return array | entailment |
public function getListEntities($collection_id, array $arguments)
{
try {
$handlers = $this->collection->getHandlers();
return Handler::call($handlers, $collection_id, 'list', array($arguments));
} catch (Exception $ex) {
trigger_error($ex->getMessage());
return array();
}
} | Returns an array of entities for the given collection ID
@param string $collection_id
@param array $arguments
@return array | entailment |
public function getNextWeight($collection_id)
{
$sql = 'SELECT MAX(weight) FROM collection_item WHERE collection_id=?';
$weight = (int) $this->db->fetchColumn($sql, array($collection_id));
return ++$weight;
} | Returns the next possible weight for a collection item
@param integer $collection_id
@return integer | entailment |
public function get($imagestyle_id)
{
$result = null;
$this->hook->attach('image.style.get.before', $imagestyle_id, $result, $this);
if (isset($result)) {
return (array) $result;
}
$imagestyles = $this->getList();
$result = isset($imagestyles[$imagestyle_id]) ? $imagestyles[$imagestyle_id] : array();
$this->hook->attach('image.style.get.after', $imagestyle_id, $result, $this);
return (array) $result;
} | Loads an image style
@param integer $imagestyle_id
@return array | entailment |
public function getList()
{
$imagestyles = &gplcart_static('image.style.list');
if (isset($imagestyles)) {
return (array) $imagestyles;
}
$this->hook->attach('image.style.list.before', $imagestyles, $this);
if (isset($imagestyles)) {
return (array) $imagestyles;
}
$default = (array) gplcart_config_get(GC_FILE_CONFIG_IMAGE_STYLE);
$saved = $this->config->get('imagestyles', array());
$imagestyles = array_replace_recursive($default, $saved);
foreach ($imagestyles as $imagestyle_id => &$imagestyle) {
$imagestyle['imagestyle_id'] = $imagestyle_id;
$imagestyle['default'] = isset($default[$imagestyle_id]);
$imagestyle['in_database'] = isset($saved[$imagestyle_id]);
}
$this->hook->attach('image.style.list.after', $imagestyles, $this);
return (array) $imagestyles;
} | Returns an array of image styles
@return array | entailment |
public function add(array $data)
{
$result = null;
$this->hook->attach('image.style.add.before', $data, $result, $this);
if (isset($result)) {
return (int) $result;
}
$default = $this->getDefaultData();
$data += $default;
$imagestyle_id = count($this->getList()) + 1;
$imagestyles = $this->config->get('imagestyles', array());
$imagestyles[$imagestyle_id] = array_intersect_key($data, $default);
$this->config->set('imagestyles', $imagestyles);
$this->hook->attach('image.style.add.after', $data, $imagestyle_id, $this);
return (int) $imagestyle_id;
} | Adds an image style
@param array $data
@return integer | entailment |
public function update($imagestyle_id, array $data)
{
$result = null;
$this->hook->attach('image.style.update.before', $imagestyle_id, $data, $result, $this);
if (isset($result)) {
return (bool) $result;
}
$existing = $this->getList();
if (empty($existing[$imagestyle_id])) {
return false;
}
$saved = $this->config->select('imagestyles', array());
if (empty($saved[$imagestyle_id])) {
$data += $existing[$imagestyle_id];
} else {
$data += $saved[$imagestyle_id];
}
$default = $this->getDefaultData();
$saved[$imagestyle_id] = array_intersect_key($data, $default);
$result = $this->config->set('imagestyles', $saved);
$this->hook->attach('image.style.update.after', $imagestyle_id, $data, $result, $this);
return (bool) $result;
} | Updates an image style
@param integer $imagestyle_id
@param array $data
@return boolean | entailment |
public function delete($imagestyle_id, $check = true)
{
$result = null;
$this->hook->attach('image.style.delete.before', $imagestyle_id, $check, $result, $this);
if (isset($result)) {
return (bool) $result;
}
if ($check && !$this->canDelete($imagestyle_id)) {
return false;
}
$imagestyles = $this->config->select('imagestyles', array());
unset($imagestyles[$imagestyle_id]);
$result = $this->config->set('imagestyles', $imagestyles);
$this->hook->attach('image.style.delete.after', $imagestyle_id, $check, $result, $this);
return (bool) $result;
} | Deletes an image style
@param integer $imagestyle_id
@param bool $check
@return boolean | entailment |
public function getActions($imagestyle_id)
{
$styles = $this->getList();
if (empty($styles[$imagestyle_id]['actions'])) {
return array();
}
$actions = $styles[$imagestyle_id]['actions'];
gplcart_array_sort($actions);
return $actions;
} | Returns an array of image style actions
@param integer $imagestyle_id
@return array | entailment |
public function getActionHandlers()
{
$handlers = &gplcart_static('image.style.action.handlers');
if (isset($handlers)) {
return (array) $handlers;
}
$handlers = (array) gplcart_config_get(GC_FILE_CONFIG_IMAGE_ACTION);
$this->hook->attach('image.style.action.handlers', $handlers, $this);
return (array) $handlers;
} | Returns an array of image style action handlers
@return array | entailment |
public function getActionHandler($action_id)
{
$handlers = $this->getActionHandlers();
return empty($handlers[$action_id]) ? array() : $handlers[$action_id];
} | Returns a single image action handler
@param string $action_id
@return array | entailment |
public function applyAction(&$source, &$target, $handler, &$action)
{
$result = null;
$this->hook->attach('image.style.apply.before', $source, $target, $handler, $action, $result);
if (isset($result)) {
return $result;
}
try {
$callback = Handler::get($handler, null, 'process');
$result = call_user_func_array($callback, array(&$source, &$target, &$action));
} catch (Exception $ex) {
$result = $ex->getMessage();
}
$this->hook->attach('image.style.apply.after', $source, $target, $handler, $action, $result);
return $result;
} | Apply a single action to an image file
@param string $source
@param string $target
@param array $handler
@param array $action
@return boolean|string | entailment |
public function applyActions(array $actions, $source, $target)
{
$applied = 0;
foreach ($actions as $action_id => $data) {
$handler = $this->getActionHandler($action_id);
if (empty($handler)) {
continue;
}
$result = $this->applyAction($source, $target, $handler, $data);
if ($result === true) {
$applied++;
}
}
return $applied;
} | Apply an array of actions
@param array $actions
@param string $source
@param string $target
@return int | entailment |
public function clearCache($imagestyle_id = null)
{
$result = null;
$this->hook->attach('image.style.clear.cache.before', $imagestyle_id, $result, $this);
if (isset($result)) {
return (bool) $result;
}
$result = gplcart_file_delete_recursive($this->getDirectory($imagestyle_id));
$this->hook->attach('image.style.clear.cache.after', $imagestyle_id, $result, $this);
return (bool) $result;
} | Removes cached files for all or a certain image style
@param integer|null $imagestyle_id
@return boolean | entailment |
public function zip($file)
{
if (!function_exists('zip_open')) {
return false;
}
$zip = zip_open($file);
if (is_resource($zip)) {
zip_close($zip);
return true;
}
return false;
} | Whether the file is a ZIP file
@param string $file
@return boolean | entailment |
protected function addAnAddress($kind, $address, $name = '')
{
if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
$this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
$this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
if ($this->exceptions) {
throw new Mail\MailerException('Invalid recipient array: ' . $kind);
}
return false;
}
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!$this->validateAddress($address)) {
$this->setError($this->lang('invalid_address') . ': ' . $address);
$this->edebug($this->lang('invalid_address') . ': ' . $address);
if ($this->exceptions) {
throw new Mail\MailerException($this->lang('invalid_address') . ': ' . $address);
}
return false;
}
if ($kind != 'Reply-To') {
if (!isset($this->all_recipients[strtolower($address)])) {
array_push($this->$kind, array($address, $name));
$this->all_recipients[strtolower($address)] = true;
return true;
}
} else {
if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
$this->ReplyTo[strtolower($address)] = array($address, $name);
return true;
}
}
return false;
} | Add an address to one of the recipient arrays.
Addresses that have been added already return false, but do not throw exceptions
@param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
@param string $address The email address to send to
@param string $name
@throws phpmailerException
@return boolean true on success, false if address already used or invalid in some way
@access protected | entailment |
public function setFrom($address, $name = '', $auto = true)
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!$this->validateAddress($address)) {
$this->setError($this->lang('invalid_address') . ': ' . $address);
$this->edebug($this->lang('invalid_address') . ': ' . $address);
if ($this->exceptions) {
throw new Mail\MailerException($this->lang('invalid_address') . ': ' . $address);
}
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
} | Set the From and FromName properties.
@param string $address
@param string $name
@param boolean $auto Whether to also set the Sender address, defaults to true
@throws phpmailerException
@return boolean | entailment |
public static function validateAddress($address, $patternselect = 'auto')
{
if (!$patternselect or $patternselect == 'auto') {
//Check this constant first so it works when extension_loaded() is disabled by safe mode
//Constant was added in PHP 5.2.4
if (defined('PCRE_VERSION')) {
//This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
$patternselect = 'pcre8';
} else {
$patternselect = 'pcre';
}
} elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
//Fall back to older PCRE
$patternselect = 'pcre';
} else {
//Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
$patternselect = 'php';
} else {
$patternselect = 'noregex';
}
}
}
switch ($patternselect) {
case 'pcre8':
/**
* Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
* @link http://squiloople.com/2009/12/20/email-address-validation/
* @copyright 2009-2010 Michael Rushton
* Feel free to use and redistribute this code. But please keep this copyright notice.
*/
return (boolean)preg_match(
'/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
'((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
'(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
'([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
'(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
'(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
'|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
'|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
$address
);
case 'pcre':
//An older regex that doesn't need a recent PCRE
return (boolean)preg_match(
'/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
'[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
'(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
'@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
'(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
'[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
'::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
'[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
'::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
$address
);
case 'html5':
/**
* This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
* @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
*/
return (boolean)preg_match(
'/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
'[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
$address
);
case 'noregex':
//No PCRE! Do something _very_ approximate!
//Check the address is 3 chars or longer and contains an @ that's not the first or last char
return (strlen($address) >= 3
and strpos($address, '@') >= 1
and strpos($address, '@') != strlen($address) - 1);
case 'php':
default:
return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
}
} | Check that a string looks like an email address.
@param string $address The email address to check
@param string $patternselect A selector for the validation pattern to use :
* `auto` Pick strictest one automatically;
* `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
* `pcre` Use old PCRE implementation;
* `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
* `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
* `noregex` Don't use a regex: super fast, really dumb.
@return boolean
@static
@access public | entailment |
public function send()
{
try {
if (!$this->preSend()) {
return false;
}
return $this->postSend();
} catch (phpmailerException $exc) {
$this->mailHeader = '';
$this->setError($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
} | Create a message and send it.
Uses the sending method specified by $Mailer.
@throws phpmailerException
@return boolean false on error - See the ErrorInfo property for details of the error. | entailment |
public function getSMTPInstance()
{
if (!is_object($this->smtp)) {
$this->smtp = new Mail\Smtp();
}
return $this->smtp;
} | Get an instance to use for SMTP operations.
Override this function to load your own SMTP implementation
@return SMTP | entailment |
protected function smtpSend($header, $body)
{
$bad_rcpt = array();
if (!$this->smtpConnect()) {
throw new Mail\MailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
}
$smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
if (!$this->smtp->mail($smtp_from)) {
$this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
throw new Mail\MailerException($this->ErrorInfo, self::STOP_CRITICAL);
}
// Attempt to send to all recipients
foreach ($this->to as $to) {
if (!$this->smtp->recipient($to[0])) {
$bad_rcpt[] = $to[0];
$isSent = false;
} else {
$isSent = true;
}
$this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
}
foreach ($this->cc as $cc) {
if (!$this->smtp->recipient($cc[0])) {
$bad_rcpt[] = $cc[0];
$isSent = false;
} else {
$isSent = true;
}
$this->doCallback($isSent, array(), array($cc[0]), array(), $this->Subject, $body, $this->From);
}
foreach ($this->bcc as $bcc) {
if (!$this->smtp->recipient($bcc[0])) {
$bad_rcpt[] = $bcc[0];
$isSent = false;
} else {
$isSent = true;
}
$this->doCallback($isSent, array(), array(), array($bcc[0]), $this->Subject, $body, $this->From);
}
// Only send the DATA command if we have viable recipients
if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
throw new Mail\MailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
}
if ($this->SMTPKeepAlive) {
$this->smtp->reset();
} else {
$this->smtp->quit();
$this->smtp->close();
}
if (count($bad_rcpt) > 0) { // Create error message for any bad addresses
throw new Mail\MailerException(
$this->lang('recipients_failed') . implode(', ', $bad_rcpt),
self::STOP_CONTINUE
);
}
return true;
} | Send mail via SMTP.
Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
Uses the PHPMailerSMTP class by default.
@see PHPMailer::getSMTPInstance() to use a different class.
@param string $header The message headers
@param string $body The message body
@throws phpmailerException
@uses SMTP
@access protected
@return boolean | entailment |
public function addrFormat($addr)
{
if (empty($addr[1])) { // No name provided
return $this->secureHeader($addr[0]);
} else {
return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
$addr[0]
) . '>';
}
} | Format an address for use in a message header.
@access public
@param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
like array('[email protected]', 'Joe User')
@return string | entailment |
public function wrapText($message, $length, $qp_mode = false)
{
$soft_break = ($qp_mode) ? sprintf(' =%s', $this->LE) : $this->LE;
// If utf-8 encoding is used, we will need to make sure we don't
// split multibyte characters when we wrap
$is_utf8 = (strtolower($this->CharSet) == 'utf-8');
$lelen = strlen($this->LE);
$crlflen = strlen(self::CRLF);
$message = $this->fixEOL($message);
if (substr($message, -$lelen) == $this->LE) {
$message = substr($message, 0, -$lelen);
}
$line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE
$message = '';
for ($i = 0; $i < count($line); $i++) {
$line_part = explode(' ', $line[$i]);
$buf = '';
for ($e = 0; $e < count($line_part); $e++) {
$word = $line_part[$e];
if ($qp_mode and (strlen($word) > $length)) {
$space_left = $length - strlen($buf) - $crlflen;
if ($e != 0) {
if ($space_left > 20) {
$len = $space_left;
if ($is_utf8) {
$len = $this->utf8CharBoundary($word, $len);
} elseif (substr($word, $len - 1, 1) == '=') {
$len--;
} elseif (substr($word, $len - 2, 1) == '=') {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
$buf .= ' ' . $part;
$message .= $buf . sprintf('=%s', self::CRLF);
} else {
$message .= $buf . $soft_break;
}
$buf = '';
}
while (strlen($word) > 0) {
if ($length <= 0) {
break;
}
$len = $length;
if ($is_utf8) {
$len = $this->utf8CharBoundary($word, $len);
} elseif (substr($word, $len - 1, 1) == '=') {
$len--;
} elseif (substr($word, $len - 2, 1) == '=') {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
if (strlen($word) > 0) {
$message .= $part . sprintf('=%s', self::CRLF);
} else {
$buf = $part;
}
}
} else {
$buf_o = $buf;
$buf .= ($e == 0) ? $word : (' ' . $word);
if (strlen($buf) > $length and $buf_o != '') {
$message .= $buf_o . $soft_break;
$buf = $word;
}
}
}
$message .= $buf . self::CRLF;
}
return $message;
} | Word-wrap message.
For use with mailers that do not automatically perform wrapping
and for quoted-printable encoded messages.
Original written by philippe.
@param string $message The message to wrap
@param integer $length The line length to wrap to
@param boolean $qp_mode Whether to run in Quoted-Printable mode
@access public
@return string | entailment |
public function utf8CharBoundary($encodedText, $maxLength)
{
$foundSplitPos = false;
$lookBack = 3;
while (!$foundSplitPos) {
$lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
$encodedCharPos = strpos($lastChunk, '=');
if (false !== $encodedCharPos) {
// Found start of encoded character byte within $lookBack block.
// Check the encoded byte value (the 2 chars after the '=')
$hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
$dec = hexdec($hex);
if ($dec < 128) { // Single byte character.
// If the encoded char was found at pos 0, it will fit
// otherwise reduce maxLength to start of the encoded char
$maxLength = ($encodedCharPos == 0) ? $maxLength :
$maxLength - ($lookBack - $encodedCharPos);
$foundSplitPos = true;
} elseif ($dec >= 192) { // First byte of a multi byte character
// Reduce maxLength to split at start of character
$maxLength = $maxLength - ($lookBack - $encodedCharPos);
$foundSplitPos = true;
} elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
$lookBack += 3;
}
} else {
// No encoded character found
$foundSplitPos = true;
}
}
return $maxLength;
} | Find the last character boundary prior to $maxLength in a utf-8
quoted (printable) encoded string.
Original written by Colin Brown.
@access public
@param string $encodedText utf-8 QP text
@param integer $maxLength find last character boundary prior to this length
@return integer | entailment |
public function getMailMIME()
{
$result = '';
$ismultipart = true;
switch ($this->message_type) {
case 'inline':
$result .= $this->headerLine('Content-Type', 'multipart/related;');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
case 'attach':
case 'inline_attach':
case 'alt_attach':
case 'alt_inline_attach':
$result .= $this->headerLine('Content-Type', 'multipart/mixed;');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
case 'alt':
case 'alt_inline':
$result .= $this->headerLine('Content-Type', 'multipart/alternative;');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
default:
// Catches case 'plain': and case '':
$result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
$ismultipart = false;
break;
}
// RFC1341 part 5 says 7bit is assumed if not specified
if ($this->Encoding != '7bit') {
// RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
if ($ismultipart) {
if ($this->Encoding == '8bit') {
$result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
}
// The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
} else {
$result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
}
}
if ($this->Mailer != 'mail') {
$result .= $this->LE;
}
return $result;
} | Get the message MIME type headers.
@access public
@return string | entailment |
public function encodeHeader($str, $position = 'text')
{
$matchcount = 0;
switch (strtolower($position)) {
case 'phrase':
if (!preg_match('/[\200-\377]/', $str)) {
// Can't use addslashes as we don't know the value of magic_quotes_sybase
$encoded = addcslashes($str, "\0..\37\177\\\"");
if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
return ($encoded);
} else {
return ("\"$encoded\"");
}
}
$matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
break;
/** @noinspection PhpMissingBreakStatementInspection */
case 'comment':
$matchcount = preg_match_all('/[()"]/', $str, $matches);
// Intentional fall-through
case 'text':
default:
$matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
break;
}
if ($matchcount == 0) { // There are no chars that need encoding
return ($str);
}
$maxlen = 75 - 7 - strlen($this->CharSet);
// Try to select the encoding which should produce the shortest output
if ($matchcount > strlen($str) / 3) {
// More than a third of the content will need encoding, so B encoding will be most efficient
$encoding = 'B';
if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
// Use a custom function which correctly encodes and wraps long
// multibyte strings without breaking lines within a character
$encoded = $this->base64EncodeWrapMB($str, "\n");
} else {
$encoded = base64_encode($str);
$maxlen -= $maxlen % 4;
$encoded = trim(chunk_split($encoded, $maxlen, "\n"));
}
} else {
$encoding = 'Q';
$encoded = $this->encodeQ($str, $position);
$encoded = $this->wrapText($encoded, $maxlen, true);
$encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
}
$encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
$encoded = trim(str_replace("\n", $this->LE, $encoded));
return $encoded;
} | Encode a header string optimally.
Picks shortest of Q, B, quoted-printable or none.
@access public
@param string $str
@param string $position
@return string | entailment |
public function hasMultiBytes($str)
{
if (function_exists('mb_strlen')) {
return (strlen($str) > mb_strlen($str, $this->CharSet));
} else { // Assume no multibytes (we can't handle without mbstring functions anyway)
return false;
}
} | Check if a string contains multi-byte characters.
@access public
@param string $str multi-byte text to wrap encode
@return boolean | entailment |
public function base64EncodeWrapMB($str, $linebreak = null)
{
$start = '=?' . $this->CharSet . '?B?';
$end = '?=';
$encoded = '';
if ($linebreak === null) {
$linebreak = $this->LE;
}
$mb_length = mb_strlen($str, $this->CharSet);
// Each line must have length <= 75, including $start and $end
$length = 75 - strlen($start) - strlen($end);
// Average multi-byte ratio
$ratio = $mb_length / strlen($str);
// Base64 has a 4:3 ratio
$avgLength = floor($length * $ratio * .75);
for ($i = 0; $i < $mb_length; $i += $offset) {
$lookBack = 0;
do {
$offset = $avgLength - $lookBack;
$chunk = mb_substr($str, $i, $offset, $this->CharSet);
$chunk = base64_encode($chunk);
$lookBack++;
} while (strlen($chunk) > $length);
$encoded .= $chunk . $linebreak;
}
// Chomp the last linefeed
$encoded = substr($encoded, 0, -strlen($linebreak));
return $encoded;
} | Encode and wrap long multibyte strings for mail headers
without breaking lines within a character.
Adapted from a function by paravoid
@link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
@access public
@param string $str multi-byte text to wrap encode
@param string $linebreak string to use as linefeed/end-of-line
@return string | entailment |
public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
{
if (!@is_file($path)) {
$this->setError($this->lang('file_access') . $path);
return false;
}
// If a MIME type is not specified, try to work it out from the file name
if ($type == '') {
$type = self::filenameToType($path);
}
$filename = basename($path);
if ($name == '') {
$name = $filename;
}
// Append to $attachment array
$this->attachment[] = array(
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => $disposition,
7 => $cid
);
return true;
} | Add an embedded (inline) attachment from a file.
This can include images, sounds, and just about any other document type.
These differ from 'regular' attachments in that they are intended to be
displayed inline with the message, not just attached for download.
This is used in HTML messages that embed the images
the HTML refers to using the $cid value.
@param string $path Path to the attachment.
@param string $cid Content ID of the attachment; Use this to reference
the content when using an embedded image in HTML.
@param string $name Overrides the attachment name.
@param string $encoding File encoding (see $Encoding).
@param string $type File MIME type.
@param string $disposition Disposition to use
@return boolean True on successfully adding an attachment | entailment |
public function clearCCs()
{
foreach ($this->cc as $cc) {
unset($this->all_recipients[strtolower($cc[0])]);
}
$this->cc = array();
} | Clear all CC recipients.
@return void | entailment |
protected function setError($msg)
{
$this->error_count++;
if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
$lasterror = $this->smtp->getError();
if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
$msg .= '<p>' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
}
}
$this->ErrorInfo = $msg;
} | Add an error message to the error container.
@access protected
@param string $msg
@return void | entailment |
protected function serverHostname()
{
$result = 'localhost.localdomain';
if (!empty($this->Hostname)) {
$result = $this->Hostname;
} elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
$result = $_SERVER['SERVER_NAME'];
} elseif (function_exists('gethostname') && gethostname() !== false) {
$result = gethostname();
} elseif (php_uname('n') !== false) {
$result = php_uname('n');
}
return $result;
} | Get the server hostname.
Returns 'localhost.localdomain' if unknown.
@access protected
@return string | entailment |
protected function lang($key)
{
if (count($this->language) < 1) {
$this->setLanguage('en'); // set the default language
}
if (isset($this->language[$key])) {
return $this->language[$key];
} else {
return 'Language string failed to load: ' . $key;
}
} | Get an error message in the current language.
@access protected
@param string $key
@return string | entailment |
public function fixEOL($str)
{
// Normalise to \n
$nstr = str_replace(array("\r\n", "\r"), "\n", $str);
// Now convert LE as needed
if ($this->LE !== "\n") {
$nstr = str_replace("\n", $this->LE, $nstr);
}
return $nstr;
} | Ensure consistent line endings in a string.
Changes every end of line from CRLF, CR or LF to $this->LE.
@access public
@param string $str String to fixEOL
@return string | entailment |
public function msgHTML($message, $basedir = '', $advanced = false)
{
preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
if (isset($images[2])) {
foreach ($images[2] as $imgindex => $url) {
// Convert data URIs into embedded images
if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
$data = substr($url, strpos($url, ','));
if ($match[2]) {
$data = base64_decode($data);
} else {
$data = rawurldecode($data);
}
$cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
$message = str_replace(
$images[0][$imgindex],
$images[1][$imgindex] . '="cid:' . $cid . '"',
$message
);
}
} elseif (!preg_match('#^[A-z]+://#', $url)) {
// Do not change urls for absolute images (thanks to corvuscorax)
$filename = basename($url);
$directory = dirname($url);
if ($directory == '.') {
$directory = '';
}
$cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
$basedir .= '/';
}
if (strlen($directory) > 1 && substr($directory, -1) != '/') {
$directory .= '/';
}
if ($this->addEmbeddedImage(
$basedir . $directory . $filename,
$cid,
$filename,
'base64',
self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
)
) {
$message = preg_replace(
'/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
$images[1][$imgindex] . '="cid:' . $cid . '"',
$message
);
}
}
}
}
$this->isHTML(true);
// Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
$this->Body = $this->normalizeBreaks($message);
$this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
if (empty($this->AltBody)) {
$this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
self::CRLF . self::CRLF;
}
return $this->Body;
} | Create a message from an HTML string.
Automatically makes modifications for inline images and backgrounds
and creates a plain-text version by converting the HTML.
Overwrites any existing values in $this->Body and $this->AltBody
@access public
@param string $message HTML message string
@param string $basedir baseline directory for path
@param boolean|callable $advanced Whether to use the internal HTML to text converter
or your own custom converter @see html2text()
@return string $message | entailment |
public function html2text($html, $advanced = false)
{
if (is_callable($advanced)) {
return $advanced($html);
}
return html_entity_decode(
trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
ENT_QUOTES,
$this->CharSet
);
} | Convert an HTML string into plain text.
This is used by msgHTML().
Note - older versions of this function used a bundled advanced converter
which was been removed for license reasons in #232
Example usage:
<code>
// Use default conversion
$plain = $mail->html2text($html);
// Use your own custom converter
$plain = $mail->html2text($html, function($html) {
$converter = new MyHtml2text($html);
return $converter->get_text();
});
</code>
@param string $html The HTML text to convert
@param boolean|callable $advanced Any boolean value to use the internal converter,
or provide your own callable for custom conversion.
@return string | entailment |
public function DKIM_Sign($signHeader)
{
if (!defined('PKCS7_TEXT')) {
if ($this->exceptions) {
throw new Mail\MailerException($this->lang('signing') . ' OpenSSL extension missing.');
}
return '';
}
$privKeyStr = file_get_contents($this->DKIM_private);
if ($this->DKIM_passphrase != '') {
$privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
} else {
$privKey = $privKeyStr;
}
if (openssl_sign($signHeader, $signature, $privKey)) {
return base64_encode($signature);
}
return '';
} | Generate a DKIM signature.
@access public
@param string $signHeader
@throws phpmailerException
@return string | entailment |
public function DKIM_BodyC($body)
{
if ($body == '') {
return "\r\n";
}
// stabilize line endings
$body = str_replace("\r\n", "\n", $body);
$body = str_replace("\n", "\r\n", $body);
// END stabilize line endings
while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
$body = substr($body, 0, strlen($body) - 2);
}
return $body;
} | Generate a DKIM canonicalization body.
@access public
@param string $body Message Body
@return string | entailment |
public function get($key, $default = null)
{
if (!GC_CLI && isset($_SESSION)) {
$value = gplcart_array_get($_SESSION, $key);
}
return isset($value) ? $value : $default;
} | Returns a session data
@param string|array $key
@param mixed $default
@return mixed | entailment |
public function set($key, $value = null)
{
if (!GC_CLI && isset($_SESSION)) {
gplcart_array_set($_SESSION, $key, $value);
return true;
}
return false;
} | Set a session data
@param string|array $key
@param mixed $value
@return bool | entailment |
public function delete($key = null)
{
if (!$this->isInitialized()) {
return false;
}
if (!isset($key)) {
session_unset();
if (!session_destroy()) {
throw new RuntimeException('Failed to delete the session');
}
return true;
}
gplcart_array_unset($_SESSION, $key);
return true;
} | Deletes a data from the session
@param mixed $key
@return bool
@throws RuntimeException | entailment |
public function setMessage($message, $type = 'info', $key = 'messages')
{
if ($message !== '') {
$messages = (array) $this->get("$key.$type", array());
if (!in_array($message, $messages)) {
$messages[] = $message;
$this->set("$key.$type", $messages);
}
}
} | Sets a message to be displayed to the user
@param string $message
@param string $type
@param string $key | entailment |
public function getMessage($type = null, $key = 'messages')
{
if (isset($type)) {
$key .= ".$type";
}
$message = $this->get($key, array());
$this->delete($key);
return $message;
} | Returns messages from the session
@param string $type
@param string $key
@return string|array | entailment |
public function city(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateCity();
$this->validateBool('status');
$this->validateName();
$this->validateStateCity();
$this->validateZoneCity();
$this->validateCountryCity();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full city data validation
@param array $submitted
@param array $options
@return boolean|array | entailment |
protected function validateCity()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->city->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('City'));
return false;
}
$this->setUpdating($data);
return true;
} | Validates a city to be updated
@return boolean|null | entailment |
protected function validateCountryCity()
{
$field = 'country';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$label = $this->translation->text('Country');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
$country = $this->country->get($value);
if (empty($country['code'])) {
$this->setErrorUnavailable($field, $label);
return false;
}
$this->setSubmitted('country', $country['code']);
return true;
} | Validates a country code
@return boolean|null | entailment |
public function createService(ServiceLocatorInterface $serviceLocator)
{
$context = new RequestContext();
$context->fromRequest($serviceLocator->get('Request'));
return $context;
} | Create and return the router.
@param ServiceLocatorInterface $serviceLocator
@return \PPI\Framework\Router\RouterListener | entailment |
protected function processConfiguration(array $config, ServiceLocatorInterface $serviceLocator = null)
{
$defaults = $this->getConfigurationDefaults();
$defaults = $defaults['framework']['router'];
return isset($config['framework']['router']) ?
$this->mergeConfiguration($defaults, $config['framework']['router']) :
$defaults;
} | {@inheritDoc} | entailment |
public function file(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateFile();
$this->validateTitleFile();
$this->validateDescription();
$this->validateWeight();
$this->validateTranslation();
$this->validateUploadFile();
$this->validatePathFile();
$this->validateEntityFile();
$this->validateEntityIdFile();
$this->validateFileTypeFile();
$this->validateMimeTypeFile();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full file data validation
@param array $submitted
@param array $options
@return boolean|array | entailment |
protected function validateFile()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->file->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('File'));
return false;
}
$this->setSubmitted('update', $data);
return true;
} | Validates a file to be updated
@return boolean|null | entailment |
protected function validateTitleFile()
{
$field = 'title';
$value = $this->getSubmitted($field);
if (isset($value) && mb_strlen($value) > 255) {
$this->setErrorLengthRange($field, $this->translation->text('Title'), 0, 255);
return false;
}
return true;
} | Validates a title field
@return boolean | entailment |
protected function validatePathFile()
{
$field = 'path';
$value = $this->getSubmitted($field);
if ($this->isExcluded($field) || $this->isError()) {
return null;
}
if (!isset($value) && $this->isUpdating()) {
return null;
}
$label = $this->translation->text('File');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
if (!is_readable(gplcart_file_absolute($value))) {
$this->setErrorUnavailable($field, $label);
return false;
}
return true;
} | Validates a file path
@return boolean|null | entailment |
protected function validateUploadFile()
{
$file = $this->request->file('file');
if (empty($file)) {
return null;
}
$result = $this->file_transfer->upload($file, null);
if ($result !== true) {
$this->setError('path', (string) $result);
return false;
}
$this->setSubmitted('path', $this->file_transfer->getTransferred(true));
return true;
} | Validates file upload
@return bool|null | entailment |
protected function validateEntityIdFile()
{
$field = 'entity_id';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (!isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$label = $this->translation->text('Entity ID');
if (!is_numeric($value)) {
$this->setErrorInteger($field, $label);
return false;
}
if (strlen($value) > 10) {
$this->setErrorLengthRange($field, $label, 0, 10);
return false;
}
return true;
} | Validates entity ID
@return bool|null | entailment |
public function createService(ServiceLocatorInterface $serviceLocator)
{
$router = $serviceLocator->get('Router');
$requestContext = $serviceLocator->get('RouterRequestContext');
$logger = $serviceLocator->has('Logger') ? $serviceLocator->get('Logger') : null;
$requestStack = $serviceLocator->get('RequestStack');
return new RouterListener($router, $requestContext, $logger, $requestStack);
} | Create and return the router.
@param ServiceLocatorInterface $serviceLocator
@return \PPI\Framework\Router\RouterListener | entailment |
public function update($cart_id, array $data)
{
$result = null;
$this->hook->attach('cart.update.before', $cart_id, $data, $result, $this);
if (isset($result)) {
return (bool) $result;
}
$data['modified'] = GC_TIME;
$result = (bool) $this->db->update('cart', $data, array('cart_id' => $cart_id));
gplcart_static_clear();
$this->hook->attach('cart.update.after', $cart_id, $data, $result, $this);
return (bool) $result;
} | Updates a cart
@param integer $cart_id
@param array $data
@return boolean | entailment |
public function getContent(array $data)
{
$result = &gplcart_static(gplcart_array_hash(array('cart.get.content' => $data)));
if (isset($result)) {
return $result;
}
$this->hook->attach('cart.get.content.before', $data, $result, $this);
if (isset($result)) {
return $result;
}
$data['order_id'] = 0;
$items = $this->getList($data);
if (empty($items)) {
return array();
}
$result = array(
'store_id' => $data['store_id'],
'currency' => $this->currency->getCode()
);
$total = $quantity = 0;
foreach ((array) $items as $item) {
$prepared = $this->prepareItem($item, $result);
if (!empty($prepared)) {
$result['items'][$item['sku']] = $prepared;
$total += (int) $prepared['total'];
$quantity += (int) $prepared['quantity'];
}
}
$result['total'] = $total;
$result['quantity'] = $quantity;
$this->hook->attach('cart.get.content.after', $data, $result, $this);
return $result;
} | Returns a cart content
@param array $data
@return array | entailment |
public function getUid()
{
$session_user_id = $this->user->getId();
if (!empty($session_user_id)) {
return (string) $session_user_id;
}
$cookie_name = $this->getCookieUserName();
$cookie_user_id = $this->request->cookie($cookie_name, '', 'string');
if (!empty($cookie_user_id)) {
return $cookie_user_id;
}
$generated_user_id = '_' . gplcart_string_random(6);
$this->request->setCookie($cookie_name, $generated_user_id, $this->getCookieLifespan());
return $generated_user_id;
} | Returns the cart user ID
@return string | entailment |
public function getQuantity(array $options, $type = null)
{
$options += array('order_id' => 0);
$result = array(
'total' => 0,
'sku' => array()
);
foreach ((array) $this->getList($options) as $item) {
$result['total'] += (int) $item['quantity'];
$result['sku'][$item['sku']] = (int) $item['quantity'];
}
if (isset($type)) {
return $result[$type];
}
return $result;
} | Returns cart quantity
@param array $options
@param string $type
@return array|integer | entailment |
public function getLimits($item = null)
{
$limits = array(
'sku' => (int) $this->config->get('cart_sku_limit', 10),
'item' => (int) $this->config->get('cart_item_limit', 20)
);
return isset($item) ? $limits[$item] : $limits;
} | Returns cart limits
@param null|string $item
@return array|integer | entailment |
protected function prepareItem(array $item, array $data)
{
$product = $this->product->getBySku($item['sku'], $item['store_id']);
if (empty($product['status']) || $data['store_id'] != $product['store_id']) {
return array();
}
$product['price'] = $this->currency->convert($product['price'], $product['currency'], $data['currency']);
$calculated = $this->product->calculate($product);
if ($calculated != $product['price']) {
$item['original_price'] = $product['price'];
}
$item['product'] = $product;
$item['price'] = $calculated;
$item['total'] = $item['price'] * $item['quantity'];
return $item;
} | Prepare a cart item
@param array $item
@param array $data
@return array | entailment |
public function attach(EventManagerInterface $events)
{
$options = $this->getOptions();
$configListener = $this->getConfigListener();
// High priority, we assume module autoloading (for FooNamespace\Module classes) should be available before anything else
$this->listeners[] = $events->attach(new ModuleLoaderListener($options));
$this->listeners[] = $events->attach(ModuleEvent::EVENT_LOAD_MODULE_RESOLVE, new ModuleResolverListener());
// High priority, because most other loadModule listeners will assume the module's classes are available via autoloading
$this->listeners[] = $events->attach(ModuleEvent::EVENT_LOAD_MODULE, new AutoloaderListener($options), 9000);
if ($options->getCheckDependencies()) {
$this->listeners[] = $events->attach(ModuleEvent::EVENT_LOAD_MODULE, new ModuleDependencyCheckerListener(), 8000);
}
$this->listeners[] = $events->attach(ModuleEvent::EVENT_LOAD_MODULE, new InitTrigger($options));
$this->listeners[] = $events->attach($configListener);
// This process can be expensive and affect perf if enabled. So we have
// the flexibility to skip it.
//if ($options->routingEnabled) {
$this->listeners[] = $events->attach(ModuleEvent::EVENT_LOAD_MODULE, array($this, 'routesTrigger'), 3000);
//}
// @todo - this could be moved to a ZF event, so no need to make this ourselves.
$this->listeners[] = $events->attach(ModuleEvent::EVENT_LOAD_MODULE, array($this, 'getServicesTrigger'), 3000);
return $this;
} | Override of attach(). Customising the events to be triggered upon the
'loadModule' event.
@param EventManagerInterface $events
@return $this | entailment |
public function routesTrigger(ModuleEvent $e)
{
$module = $e->getModule();
if (is_callable(array($module, 'getRoutes'))) {
$routes = $module->getRoutes();
$this->routes[$e->getModuleName()] = $routes;
}
return $this;
} | Callback for 'routesTrigger' event.
@param ModuleEvent $e
@throws \Exception if the module returns an invalid route type
@return $this | entailment |
public function getServicesTrigger(ModuleEvent $e)
{
$module = $e->getModule();
if (method_exists($module, 'getServiceConfig') && is_callable(array($module, 'getServiceConfig'))) {
$services = $module->getServiceConfig();
if (is_array($services) && isset($services['factories'])) {
$this->services[$e->getModuleName()] = $services['factories'];
}
}
return $this;
} | Event callback for 'initServicesTrigger'.
@param ModuleEvent $e
@return $this | entailment |
public function getServices()
{
$mergedModuleServices = array();
foreach ($this->services as $services) {
$mergedModuleServices = ArrayUtils::merge($mergedModuleServices, $services);
}
return $mergedModuleServices;
} | Get the registered services.
@return mixed | entailment |
public function update($review_id, array $data)
{
$result = null;
$this->hook->attach('review.update.before', $review_id, $data, $result, $this);
if (isset($result)) {
return (bool) $result;
}
$data['modified'] = GC_TIME;
$result = $this->db->update('review', $data, array('review_id' => $review_id));
$this->hook->attach('review.update.after', $review_id, $data, $result, $this);
return (bool) $result;
} | Updates a review
@param integer $review_id
@param array $data
@return boolean | entailment |
public function delete($review_id)
{
$result = null;
$this->hook->attach('review.delete.before', $review_id, $result, $this);
if (isset($result)) {
return (bool) $result;
}
settype($review_id, 'array');
$placeholders = rtrim(str_repeat('?,', count($review_id)), ',');
$sql = "DELETE FROM review WHERE review_id IN($placeholders)";
$result = (bool) $this->db->run($sql, $review_id)->rowCount();
$this->hook->attach('review.delete.after', $review_id, $result, $this);
return (bool) $result;
} | Deletes a review
@param integer|array $review_id
@return boolean | entailment |
public function rating(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateProductRating();
$this->validateUserId();
$this->validateValueRating();
return $this->getResult();
} | Performs full rating data validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validateValueRating()
{
$field = 'rating';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
$label = $this->translation->text('Rating');
if (!isset($value)) {
$this->setErrorRequired($field, $label);
return false;
}
if (!is_numeric($value)) {
$this->setErrorNumeric($field, $label);
return false;
}
if ($value > 5) {
$this->setErrorInvalid($field, $label);
return false;
}
return true;
} | Validates a rating value
@return boolean | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.