sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
$templateVars['data']['actions'] = $this->actionManager->createActionsViewData($this->createActions($options));
$view->setTemplateData($templateVars);
return $view;
} | {@inheritdoc} | entailment |
public function process(OrderInterface $order)
{
$shipment = $this->getOrderShipment($order);
$this->calculate($shipment, $order);
} | {@inheritdoc} | entailment |
private function getOrderShipment(OrderInterface $order)
{
if ($order->getShipment()) {
return $order->getShipment();
}
/** @var ShipmentInterface $shipment */
$shipment = $this->shipmentFactory->createNew();
$order->setShipment($shipment);
$shipment->setMethod($this->defaultShippingMethodResolver->getDefaultShippingMethod($shipment));
return $shipment;
} | @param OrderInterface $order
@throws UnresolvedDefaultShippingMethodException
@return ShipmentInterface | entailment |
public function resolveGroups($formType)
{
$formGroups = null;
if (isset($this->formConfig[$formType]['default_groups'])) {
$formGroups = $this->formConfig[$formType]['default_groups'];
}
if(is_array($formGroups)) {
$groups = $formGroups;
} else {
$groups = $this->defaultGroups;
}
return $this->groupManager->getGroupsByCodes($groups);
} | Return groups by form type
@param string $formType
@return Group[] | entailment |
protected function write(array $record)
{
$chat_id = $this->bot->getChatLog();
// Check chat_id is valid
if ($chat_id !== "") {
$this->bot->withChatId($chat_id, 'sendMessage', $record['message']);
}
} | \brief Send the message to telegram chat
@param array $record | entailment |
public function clearLock($name)
{
if (!isset($this->locks[$name])) {
return false;
}
unset($this->locks[$name]);
return true;
} | Clear lock without releasing it
Do not use this method unless you know what you do
@param string $name name of lock
@return bool | entailment |
public function submitAction(Request $request)
{
$name = $request->get('name');
/** @var RequestConfiguration $configuration */
$configuration = $this->requestConfigurationFactory->createSimple($request);
$formConfiguration = $this->configurationFactory->create($name);
$form = $this->createForm($formConfiguration->getForm());
$form->handleRequest($request);
$sent = false;
if($form->isSubmitted()) {
if($form->isValid()) {
$model = $form->getData();
$this->contactMailer->send($name, $model);
$form = $this->createForm($formConfiguration->getForm());
$sent = true;
if($request->isXmlHttpRequest()) {
return new JsonResponse(array(
'message' => $this->translator->trans('contact.form.message.success', [], 'EnhavoContactBundle')
));
}
} else {
$errors = $this->formErrorResolver->getErrors($form);
if($request->isXmlHttpRequest()) {
return new JsonResponse(array(
'message' => $errors[0]
), 400);
} else {
$this->addFlash('error', $errors);
}
}
}
$redirectRoute = null;
if($request->get('_redirect_route')) {
$redirectRoute = ($request->get('_redirect_route'));
}
$redirectParameters = [];
if($request->get('_redirect_route_parameters')) {
$redirectParameters = json_decode($request->get('_redirect_route_parameters'));
}
if($redirectRoute) {
return $this->redirectToRoute($redirectRoute, $redirectParameters, 302);
}
$template = $configuration->getTemplate($formConfiguration->getPageTemplate());
return $this->render($template, [
'form' => $form->createView(),
'name' => $name,
'sent' => $sent
]);
} | @param Request $request
@return JsonResponse | entailment |
public function process(OrderInterface $order)
{
$items = $order->getItems();
foreach($items as $orderItem) {
$this->processItem($orderItem);
}
} | {@inheritdoc} | entailment |
public function load(array $config, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $config);
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$this->registerResources('enhavo_newsletter', $config['driver'], $config['resources'], $container);
$container->setParameter('enhavo_newsletter.newsletter.mail', $config['newsletter']['mail']);
$container->setParameter('enhavo_newsletter.newsletter.template.base', $config['newsletter']['template']['base']);
$container->setParameter('enhavo_newsletter.newsletter.template.show', $config['newsletter']['template']['show']);
$container->setParameter('enhavo_newsletter.storage', $config['storage']['default']);
$container->setParameter('enhavo_newsletter.strategy', $config['strategy']['default']);
if(isset($config['forms'])) {
$container->setParameter('enhavo_newsletter.forms', $config['forms']);
} else {
$container->setParameter('enhavo_newsletter.forms', []);
}
$this->setStrategySettings($config, $container);
$this->setStorageSettings($config, $container);
$configFiles = array(
'services/services.yml',
'services/newsletter.yml',
'services/subscriber.yml',
);
foreach ($configFiles as $configFile) {
$loader->load($configFile);
}
} | {@inheritdoc} | entailment |
public function acquireLock($name, $timeout = null)
{
$blocking = $timeout === null;
$start = microtime(true);
$end = $start + $timeout / 1000;
$locked = false;
while (!(empty($this->locks[$name]) && $locked = $this->getLock($name, $blocking)) && ($blocking || ($timeout > 0 && microtime(true) < $end))) {
usleep(static::USLEEP_TIME);
}
if ($locked) {
$this->locks[$name] = true;
return true;
}
return false;
} | Acquire lock
@param string $name name of lock
@param null|int $timeout 1. null if you want blocking lock
2. 0 if you want just lock and go
3. $timeout > 0 if you want to wait for lock some time (in milliseconds)
@return bool | entailment |
public function dispatchPostEvent($eventName, RequestConfiguration $requestConfiguration, ResourceInterface $resource)
{
$eventName = $requestConfiguration->getEvent() ?: $eventName;
$this->eventDispatcher->dispatch(sprintf('enhavo_app.post_%s', $eventName), new ResourceControllerEvent($resource));
} | {@inheritdoc} | entailment |
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
if($options['tabs'] == null) {
$tabs = [
'main' => [
'label' => '',
'template' => $options['form_template']
],
];
} else {
$tabs = $options['tabs'];
}
$templateVars['tabs'] = $tabs;
$templateVars['data']['tabs'] = $this->createTabViewData($tabs, $options['translation_domain']);
$templateVars['data']['messages'] = $this->getFlashMessages();
if($options['resource']) {
$templateVars['data']['resource'] = [
'id' => $options['resource']->getId()
];
}
$templateVars['form'] = $options['form']->createView();
$templateVars['form_themes'] = $this->formThemes;
$view->setTemplateData($templateVars);
return $view;
} | {@inheritdoc} | entailment |
public function get($name, $registeredLockImplementorName = null)
{
if (null === $registeredLockImplementorName) {
$registeredLockImplementorName = $this->getDefaultLockImplementorName();
}
if (!isset($this->mutexes[$registeredLockImplementorName][$name])) {
$this->createMutex($name, $registeredLockImplementorName);
}
return $this->mutexes[$registeredLockImplementorName][$name];
} | Create and/or get mutex
@param string $name
@param string $registeredLockImplementorName
@return Mutex | entailment |
protected function processMessage($message) {
// Check if the message was forward
isset($message['forward_from']) ? $index = 'forward_from' : $index = 'from';
$response = $this->prepareResponse($message[$index]);
$this->sendMessage($response);
} | get information about its author (if forwarded, its original author). | entailment |
public function addCategory(\Enhavo\Bundle\CategoryBundle\Entity\Category $category)
{
$category->setCollection($this);
$this->categories[] = $category;
return $this;
} | Add categories
@param \Enhavo\Bundle\CategoryBundle\Entity\Category $categories
@return Collection | entailment |
public function removeCategory(\Enhavo\Bundle\CategoryBundle\Entity\Category $category)
{
$category->setCollection(null);
$this->categories->removeElement($category);
} | Remove categories
@param \Enhavo\Bundle\CategoryBundle\Entity\Category $categories | entailment |
protected function setAssoc($handle, $assoc)
{
$oldSession = session_id();
session_commit();
session_id($assoc['handle']);
session_start();
$_SESSION['assoc'] = $assoc;
session_commit();
if($oldSession) {
session_id($oldSession);
session_start();
}
} | Stores an association.
If you want to use php sessions in your provider code, you have to replace it.
@param String $handle Association handle -- should be used as a key.
@param Array $assoc Association data. | entailment |
protected function getAssoc($handle)
{
$oldSession = session_id();
session_commit();
session_id($handle);
session_start();
$assoc = null;
if(!empty($_SESSION['assoc'])) {
$assoc = $_SESSION['assoc'];
}
session_commit();
if($oldSession) {
session_id($oldSession);
session_start();
}
return $assoc;
} | Retreives association data.
If you want to use php sessions in your provider code, you have to replace it.
@param String $handle Association handle.
@return Array Association data. | entailment |
protected function delAssoc($handle)
{
$oldSession = session_id();
session_commit();
session_id($handle);
session_start();
session_destroy();
if($oldSession) {
session_id($oldSession);
session_start();
}
} | Deletes an association.
If you want to use php sessions in your provider code, you have to replace it.
@param String $handle Association handle. | entailment |
protected function shared_secret($hash)
{
$length = 20;
if($hash == 'sha256') {
$length = 256;
}
$secret = '';
for($i = 0; $i < $length; $i++) {
$secret .= mt_rand(0,255);
}
return $secret;
} | Generates a random shared secret.
@return string | entailment |
protected function keygen($length)
{
$key = '';
for($i = 1; $i < $length; $i++) {
$key .= mt_rand(0,9);
}
$key .= mt_rand(1,9);
return $key;
} | Generates a private key.
@param int $length Length of the key. | entailment |
function xrds($force=null)
{
if($force) {
echo $this->xrdsContent();
die();
} elseif($force === false) {
header('X-XRDS-Location: '. $this->xrdsLocation);
return;
}
if (isset($_GET['xrds'])
|| (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xrds+xml') !== false)
) {
header('Content-Type: application/xrds+xml');
echo $this->xrdsContent();
die();
}
header('X-XRDS-Location: ' . $this->xrdsLocation);
} | Displays an XRDS document, or redirects to it.
By default, it detects whether it should display or redirect automatically.
@param bool|null $force When true, always display the document, when false always redirect. | entailment |
protected function xrdsContent()
{
$lines = array(
'<?xml version="1.0" encoding="UTF-8"?>',
'<xrds:XRDS xmlns:xrds="xri://$xrds" xmlns="xri://$xrd*($v*2.0)">',
'<XRD>',
' <Service>',
' <Type>' . $this->ns . '/' . ($this->select_id ? 'server' : 'signon') .'</Type>',
' <URI>' . $this->serverLocation . '</URI>',
' </Service>',
'</XRD>',
'</xrds:XRDS>'
);
return implode("\n", $lines);
} | Returns the content of the XRDS document
@return String The XRDS document. | entailment |
function server()
{
if(isset($this->data['openid_assoc_handle'])) {
$this->assoc = $this->getAssoc($this->data['openid_assoc_handle']);
if(isset($this->assoc['data'])) {
# We have additional data stored for setup.
$this->data += $this->assoc['data'];
unset($this->assoc['data']);
}
}
if (isset($this->data['openid_ns'])
&& $this->data['openid_ns'] == $this->ns
) {
if(!isset($this->data['openid_mode'])) $this->errorResponse();
switch($this->data['openid_mode'])
{
case 'checkid_immediate':
case 'checkid_setup':
$this->checkRealm();
# We support AX xor SREG.
$attributes = $this->ax();
if(!$attributes) {
$attributes = $this->sreg();
}
# Even if some user is authenticated, we need to know if it's
# the same one that want's to authenticate.
# Of course, if we use select_id, we accept any user.
if (($identity = $this->checkid($this->data['openid_realm'], $attrValues))
&& ($this->select_id || $identity == $this->data['openid_identity'])
) {
$this->positiveResponse($identity, $attrValues);
} elseif($this->data['openid_mode'] == 'checkid_immediate') {
$this->redirect($this->response(array('openid.mode' => 'setup_needed')));
} else {
if(!$this->assoc) {
$this->generateAssociation();
$this->assoc['private'] = true;
}
$this->assoc['data'] = $this->data;
$this->setAssoc($this->assoc['handle'], $this->assoc);
$this->setup($this->data['openid_identity'],
$this->data['openid_realm'],
$this->assoc['handle'],
$attributes);
}
break;
case 'associate':
$this->associate();
break;
case 'check_authentication':
$this->checkRealm();
if($this->verify()) {
echo "ns:$this->ns\nis_valid:true";
if(strpos($this->data['openid_signed'],'invalidate_handle') !== false) {
echo "\ninvalidate_handle:" . $this->data['openid_invalidate_handle'];
}
} else {
echo "ns:$this->ns\nis_valid:false";
}
die();
break;
default:
$this->errorResponse();
}
} else {
$this->xrds();
}
} | Does everything that a provider has to -- in one function. | entailment |
protected function verify()
{
# Firstly, we need to make sure that there's an association.
# Otherwise the verification will fail,
# because we've signed assoc_handle in the assertion
if(empty($this->assoc)) {
return false;
}
# Next, we check that it's a private association,
# i.e. one made without RP input.
# Otherwise, the RP shouldn't ask us to verify.
if(empty($this->assoc['private'])) {
return false;
}
# Now we have to check if the nonce is correct, to prevent replay attacks.
if($this->data['openid_response_nonce'] != $this->assoc['nonce']) {
return false;
}
# Getting the signed fields for signature.
$sig = array();
$signed = explode(',', $this->data['openid_signed']);
foreach($signed as $field) {
$name = strtr($field, '.', '_');
if(!isset($this->data['openid_' . $name])) {
return false;
}
$sig[$field] = $this->data['openid_' . $name];
}
# Computing the signature and checking if it matches.
$sig = $this->keyValueForm($sig);
if ($this->data['openid_sig'] !=
base64_encode(hash_hmac($this->assoc['hash'], $sig, $this->assoc['mac'], true))
) {
return false;
}
# Clearing the nonce, so that it won't be used again.
$this->assoc['nonce'] = null;
if(empty($this->assoc['private'])) {
# Commiting changes to the association.
$this->setAssoc($this->assoc['handle'], $this->assoc);
} else {
# Private associations shouldn't be used again, se we can as well delete them.
$this->delAssoc($this->assoc['handle']);
}
# Nothing has failed, so the verification was a success.
return true;
} | Aids an RP in assertion verification.
@return bool Information whether the verification suceeded. | entailment |
protected function associate()
{
# Rejecting no-encryption without TLS.
if(empty($_SERVER['HTTPS']) && $this->data['openid_session_type'] == 'no-encryption') {
$this->directErrorResponse();
}
# Checking whether we support DH at all.
if (!$this->dh && substr($this->data['openid_session_type'], 0, 2) == 'DH') {
$this->redirect($this->response(array(
'openid.error' => 'DH not supported',
'openid.error_code' => 'unsupported-type',
'openid.session_type' => 'no-encryption'
)));
}
# Creating the association
$this->assoc = array();
$this->assoc['hash'] = $this->data['openid_assoc_type'] == 'HMAC-SHA256' ? 'sha256' : 'sha1';
$this->assoc['handle'] = $this->assoc_handle();
# Getting the shared secret
if($this->data['openid_session_type'] == 'no-encryption') {
$this->assoc['mac'] = base64_encode($this->shared_secret($this->assoc['hash']));
} else {
$this->dh();
}
# Preparing the direct response...
$response = array(
'ns' => $this->ns,
'assoc_handle' => $this->assoc['handle'],
'assoc_type' => $this->data['openid_assoc_type'],
'session_type' => $this->data['openid_session_type'],
'expires_in' => $this->assoc_lifetime
);
if(isset($this->assoc['dh_server_public'])) {
$response['dh_server_public'] = $this->assoc['dh_server_public'];
$response['enc_mac_key'] = $this->assoc['mac'];
} else {
$response['mac_key'] = $this->assoc['mac'];
}
# ...and sending it.
echo $this->keyValueForm($response);
die();
} | Performs association with an RP. | entailment |
protected function generateAssociation()
{
$this->assoc = array();
# We use sha1 by default.
$this->assoc['hash'] = 'sha1';
$this->assoc['mac'] = $this->shared_secret('sha1');
$this->assoc['handle'] = $this->assoc_handle();
} | Creates a private association. | entailment |
protected function dh()
{
if(empty($this->data['openid_dh_modulus'])) {
$this->data['openid_dh_modulus'] = $this->default_modulus;
}
if(empty($this->data['openid_dh_gen'])) {
$this->data['openid_dh_gen'] = $this->default_gen;
}
if(empty($this->data['openid_dh_consumer_public'])) {
$this->directErrorResponse();
}
$modulus = $this->b64dec($this->data['openid_dh_modulus']);
$gen = $this->b64dec($this->data['openid_dh_gen']);
$consumerKey = $this->b64dec($this->data['openid_dh_consumer_public']);
$privateKey = $this->keygen(strlen($modulus));
$publicKey = $this->powmod($gen, $privateKey, $modulus);
$ss = $this->powmod($consumerKey, $privateKey, $modulus);
$mac = $this->x_or(hash($this->assoc['hash'], $ss, true), $this->shared_secret($this->assoc['hash']));
$this->assoc['dh_server_public'] = $this->decb64($publicKey);
$this->assoc['mac'] = base64_encode($mac);
} | Encrypts the MAC key using DH key exchange. | entailment |
protected function x_or($a, $b)
{
$length = strlen($a);
for($i = 0; $i < $length; $i++) {
$a[$i] = $a[$i] ^ $b[$i];
}
return $a;
} | XORs two strings.
@param String $a
@param String $b
@return String $a ^ $b | entailment |
protected function response($params)
{
$params += array('openid.ns' => $this->ns);
return $this->data['openid_return_to']
. (strpos($this->data['openid_return_to'],'?') ? '&' : '?')
. http_build_query($params, '', '&');
} | Prepares an indirect response url.
@param array $params Parameters to be sent. | entailment |
protected function errorResponse()
{
if(!empty($this->data['openid_return_to'])) {
$response = array(
'openid.mode' => 'error',
'openid.error' => 'Invalid request'
);
$this->redirect($this->response($response));
} else {
header('HTTP/1.1 400 Bad Request');
$response = array(
'ns' => $this->ns,
'error' => 'Invalid request'
);
echo $this->keyValueForm($response);
}
die();
} | Outputs a direct error. | entailment |
protected function positiveResponse($identity, $attributes)
{
# We generate a private association if there is none established.
if(!$this->assoc) {
$this->generateAssociation();
$this->assoc['private'] = true;
}
# We set openid.identity (and openid.claimed_id if necessary) to our $identity
if($this->data['openid_identity'] == $this->data['openid_claimed_id'] || $this->select_id) {
$this->data['openid_claimed_id'] = $identity;
}
$this->data['openid_identity'] = $identity;
# Preparing fields to be signed
$params = array(
'op_endpoint' => $this->serverLocation,
'claimed_id' => $this->data['openid_claimed_id'],
'identity' => $this->data['openid_identity'],
'return_to' => $this->data['openid_return_to'],
'realm' => $this->data['openid_realm'],
'response_nonce' => gmdate("Y-m-d\TH:i:s\Z"),
'assoc_handle' => $this->assoc['handle'],
);
$params += $this->responseAttributes($attributes);
# Has the RP used an invalid association handle?
if (isset($this->data['openid_assoc_handle'])
&& $this->data['openid_assoc_handle'] != $this->assoc['handle']
) {
$params['invalidate_handle'] = $this->data['openid_assoc_handle'];
}
# Signing the $params
$sig = hash_hmac($this->assoc['hash'], $this->keyValueForm($params), $this->assoc['mac'], true);
$req = array(
'openid.mode' => 'id_res',
'openid.signed' => implode(',', array_keys($params)),
'openid.sig' => base64_encode($sig),
);
# Saving the nonce and commiting the association.
$this->assoc['nonce'] = $params['response_nonce'];
$this->setAssoc($this->assoc['handle'], $this->assoc);
# Preparing and sending the response itself
foreach($params as $name => $value) {
$req['openid.' . $name] = $value;
}
$this->redirect($this->response($req));
} | Sends an positive assertion.
@param String $identity the OP-Local Identifier that is being authenticated.
@param Array $attributes User attributes to be sent. | entailment |
protected function responseAttributes($attributes)
{
if(!$attributes) return array();
$ns = 'http://axschema.org/';
$response = array();
if(isset($this->data['ax'])) {
$response['ns.ax'] = 'http://openid.net/srv/ax/1.0';
foreach($attributes as $name => $value) {
$alias = strtr($name, '/', '_');
$response['ax.type.' . $alias] = $ns . $name;
$response['ax.value.' . $alias] = $value;
}
return $response;
}
foreach($attributes as $name => $value) {
if(!isset($this->ax_to_sreg[$name])) {
continue;
}
$response['sreg.' . $this->ax_to_sreg[$name]] = $value;
}
return $response;
} | Prepares an array of attributes to send | entailment |
protected function b64dec($str)
{
$bytes = unpack('C*', base64_decode($str));
$n = 0;
foreach($bytes as $byte) {
$n = $this->add($this->mul($n, 256), $byte);
}
return $n;
} | Converts base64 encoded number to it's decimal representation.
@param String $str base64 encoded number.
@return String Decimal representation of that number. | entailment |
protected function decb64($num)
{
$bytes = array();
while($num) {
array_unshift($bytes, $this->mod($num, 256));
$num = $this->div($num, 256);
}
if($bytes && $bytes[0] > 127) {
array_unshift($bytes,0);
}
array_unshift($bytes, 'C*');
return base64_encode(call_user_func_array('pack', $bytes));
} | Complements b64dec. | entailment |
public function setParameter($key, $value)
{
if (!$this->parameters) {
$this->parameters = array();
}
$this->parameters[$key] = $value;
return $this;
} | Sets the parameter $key to value $value
@param string $key
@param string $value
@return File | entailment |
public function setGarbage($garbage, \DateTime $garbageTimestamp = null)
{
$this->garbage = $garbage;
if ($garbageTimestamp == null)
{
$garbageTimestamp = new \DateTime();
}
$this->setGarbageTimestamp($garbageTimestamp);
return $this;
} | @param boolean $garbage
@param \DateTime $garbageTimestamp
@return File | entailment |
public function resolvePaymentState(OrderInterface $order)
{
$payment = $order->getPayment();
if($payment->getState() === PaymentInterface::STATE_COMPLETED) {
$order->setPaymentState('completed');
}
return;
} | {@inheritdoc} | entailment |
public function preFlush(PreFlushEventArgs $event)
{
$em = $event->getEntityManager();
$uow = $em->getUnitOfWork();
/*
* We need to use the IdentityMap, because the update and persist collection stores entities, that have
* computed changes, but translation data might have changed without changing it underlying model!
*/
foreach($uow->getIdentityMap() as $className) {
foreach($className as $object) {
$this->translator->storeTranslationData($object);
}
}
} | Before flushing the data, we have to check if some translation data was stored for an object.
@param PreFlushEventArgs $event | entailment |
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->translator->deleteTranslationData($entity);
} | If entity will be deleted, we need to delete all its translation data as well
@param LifecycleEventArgs $args | entailment |
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->translator->translate($entity, $this->localeResolver->getLocale());
} | Load TranslationData into to entity if it's fetched from the database
@param LifecycleEventArgs $args | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('enhavo_shop');
$rootNode
->children()
->scalarNode('driver')->defaultValue('doctrine/orm')->end()
->end()
->children()
->arrayNode('mailer')
->addDefaultsIfNotSet()
->children()
->arrayNode('confirm')
->addDefaultsIfNotSet()
->children()
->scalarNode('service')->defaultValue('enhavo_shop.mailer.confirm_mailer_default')->end()
->scalarNode('template')->defaultValue('EnhavoShopBundle:Mailer:confirm.html.twig')->end()
->scalarNode('subject')->defaultValue('mailer.confirm.subject')->end()
->scalarNode('translationDomain')->defaultValue('EnhavoShopBundle')->end()
->scalarNode('from')->defaultValue('[email protected]')->end()
->scalarNode('sender_name')->defaultValue('enhavo')->end()
->end()
->end()
->arrayNode('tracking')
->addDefaultsIfNotSet()
->children()
->scalarNode('service')->defaultValue('enhavo_shop.mailer.tracking_mailer_default')->end()
->scalarNode('template')->defaultValue('EnhavoShopBundle:Mailer:tracking.html.twig')->end()
->scalarNode('subject')->defaultValue('mailer.tracking.subject')->end()
->scalarNode('translationDomain')->defaultValue('EnhavoShopBundle')->end()
->scalarNode('from')->defaultValue('[email protected]')->end()
->scalarNode('sender_name')->defaultValue('enhavo')->end()
->end()
->end()
->arrayNode('notification')
->addDefaultsIfNotSet()
->children()
->booleanNode('notify')->defaultValue(false)->end()
->scalarNode('service')->defaultValue('enhavo_shop.mailer.notification_mailer_default')->end()
->scalarNode('template')->defaultValue('EnhavoShopBundle:Mailer:notification.html.twig')->end()
->scalarNode('subject')->defaultValue('mailer.notification.subject')->end()
->scalarNode('translationDomain')->defaultValue('EnhavoShopBundle')->end()
->scalarNode('from')->defaultValue('[email protected]')->end()
->scalarNode('to')->defaultValue('[email protected]')->end()
->scalarNode('sender_name')->defaultValue('enhavo')->end()
->end()
->end()
->end()
->end()
->end()
->children()
->arrayNode('document')
->addDefaultsIfNotSet()
->children()
->arrayNode('billing')
->addDefaultsIfNotSet()
->children()
->scalarNode('generator')->defaultValue('enhavo_shop.document.billing_generator')->end()
->variableNode('options')->end()
->end()
->end()
->arrayNode('packing_slip')
->addDefaultsIfNotSet()
->children()
->scalarNode('generator')->defaultValue('enhavo_shop.document.packing_slip_generator')->end()
->variableNode('options')->end()
->end()
->end()
->end()
->end()
->end()
->children()
->arrayNode('payment')
->addDefaultsIfNotSet()
->children()
->arrayNode('paypal')
->addDefaultsIfNotSet()
->children()
->scalarNode('logo')->defaultValue(null)->end()
->variableNode('branding')->defaultValue(null)->end()
->end()
->end()
->end()
->end()
->end()
->children()
->arrayNode('resources')
->addDefaultsIfNotSet()
->children()
->arrayNode('voucher')
->addDefaultsIfNotSet()
->children()
->variableNode('options')->end()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(Voucher::class)->end()
->scalarNode('controller')->defaultValue(ResourceController::class)->end()
->scalarNode('repository')->defaultValue(VoucherRepository::class)->end()
->scalarNode('factory')->defaultValue(VoucherFactory::class)->end()
->scalarNode('form')->defaultValue(VoucherType::class)->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | {@inheritdoc} | entailment |
public function editMessageText(int $message_id, string $text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = true)
{
$this->parameters = [
'chat_id' => $this->chat_id,
'message_id' => $message_id,
'text' => $text,
'reply_markup' => $reply_markup,
'parse_mode' => $parse_mode,
'disable_web_page_preview' => $disable_web_preview,
];
return $this->processRequest('editMessageText', 'Message');
} | \brief Edit text of a message sent by the bot.
\details Use this method to edit text and game messages sent by the bot. [API reference](https://core.telegram.org/bots/api#editmessagetext)
@param int $message_id Unique identifier of the sent message.
@param string $text New text of the message.
@param string $reply_markup Reply markup of the message will have (will be removed if this is null).
@param string $parse_mode <i>Optional</i>. Send Markdown or HTML.
@param bool $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
@return Message|false Message edited, false otherwise. | entailment |
public function editInlineMessageText(string $inline_message_id, string $text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = false) : bool
{
$parameters = [
'inline_message_id' => $inline_message_id,
'text' => $text,
'reply_markup' => $reply_markup,
'parse_mode' => $parse_mode,
'disable_web_page_preview' => $disable_web_preview,
];
return $this->execRequest('editMessageText?' . http_build_query($parameters));
} | \brief Edit text of a message sent via the bot.
\details Use this method to edit text messages sent via the bot (for inline queries). [API reference](https://core.telegram.org/bots/api#editmessagetext)
@param string $inline_message_id Identifier of the inline message.
@param string $text New text of the message.
@param string $reply_markup Reply markup of the message will have (will be removed if this is null).
@param string $parse_mode <i>Optional</i>. Send Markdown or HTML.
@param bool $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
@return bool True on success. | entailment |
public function editMessageReplyMarkup(int $message_id, string $inline_keyboard)
{
$this->parameters = [
'chat_id' => $this->chat_id,
'message_id' => $message_id,
'reply_markup' => $inline_keyboard,
];
return $this->processRequest('editMessageReplyMarkup', 'Message');
} | \brief Edit only the inline keyboard of a message.
\details[API reference](https://core.telegram.org/bots/api#editmessagereplymarkup)
@param int $message_id Identifier of the message to edit
@param string $inline_keyboard Inlike keyboard array. [API reference](https://core.telegram.org/bots/api#inlinekeyboardmarkup)
@return Message|false Message edited, false otherwise. | entailment |
public function duplicate(\Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration $requestConfiguration, FactoryInterface $factory, ResourceInterface $originalResource)
{
if (null === $method = $requestConfiguration->getFactoryMethod()) {
$method = 'duplicate';
}
if (!method_exists($factory, $method)) {
throw new BadMethodCallException('Method "' . $method . '" not found in factory class');
}
$callable = [$factory, $method];
$arguments = array_merge([$originalResource], $requestConfiguration->getFactoryArguments());
return call_user_func_array($callable, $arguments);
} | {@inheritdoc} | entailment |
public function load(ObjectManager $manager)
{
$this->manager = $manager;
$this->loadData($this->getName());
} | {@inheritDoc} | entailment |
public function loadData($name) {
$file = sprintf('%s/../Resources/fixtures/%s.yml', __DIR__ , $name);
if(!file_exists($file)) {
throw new \Exception(sprintf('fixtures file "%s" not found for name "%s"', $file, $name));
}
$data = Yaml::parse($file);
$items = [];
foreach ($data as $args) {
$item = $this->create($args);
$this->manager->persist($item);
$items[] = $item;
}
$this->manager->flush();
} | Load the data from fixture file and insert it into the database
@param $name
@throws \Exception | entailment |
protected function createImage($path)
{
$path = sprintf('%s/../Resources/images/%s', __DIR__, $path);
$file = $this->container->get('enhavo_media.factory.file')->createFromPath($path);
return $this->container->get('enhavo_media.media.media_manager')->saveFile($file);
} | Save file and return its model.
@param $path
@return \Enhavo\Bundle\MediaBundle\Model\FileInterface
@throws \Exception | entailment |
public function createDateTime($value)
{
$date = null;
if(is_string($value)) {
$date = new \DateTime($value);
}
if(is_int($value)) {
$date = new \DateTime();
$date->setTimestamp($value);
}
return $date;
} | Return DateTime object
@param $value
@return \DateTime | entailment |
public static function compressIp($ip)
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return current(unpack('A4', inet_pton($ip)));
}
elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return current(unpack('A16', inet_pton($ip)));
}
return false;
} | Converts a printable IP into an unpacked binary string
@author Mike Mackintosh - [email protected]
@link http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php
@param string $ip
@return string $bin | entailment |
public static function expandIp($str)
{
if (strlen($str) == 16 OR strlen($str) == 4) {
return inet_ntop(pack("A".strlen($str), $str));
}
return false;
} | Converts an unpacked binary string into a printable IP
@author Mike Mackintosh - [email protected]
@link http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php
@param string $str
@return string $ip | entailment |
public function run(int $type = WEBHOOK)
{
if ($type == WEBHOOK) {
$this->_is_webhook = true;
$this->init();
$this->processWebhookUpdate();
return;
}
if ($type == DEBUG) {
$this->debug = true;
}
$this->init();
$this->getUpdatesLocal();
} | \brief Start the bot.
@param int $type How should the bot run? | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('enhavo_user');
$rootNode
// Driver used by the resource bundle
->addDefaultsIfNotSet()
->children()
->scalarNode('driver')->defaultValue(SyliusResourceBundle::DRIVER_DOCTRINE_ORM)->end()
->end()
->children()
->arrayNode('resources')
->addDefaultsIfNotSet()
->children()
->arrayNode('user')
->addDefaultsIfNotSet()
->children()
->variableNode('options')->end()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(User::class)->end()
->scalarNode('controller')->defaultValue(ResourceController::class)->end()
->scalarNode('repository')->defaultValue(UserRepository::class)->end()
->scalarNode('factory')->defaultValue(Factory::class)->end()
->scalarNode('form')->defaultValue(UserType::class)->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->arrayNode('group')
->addDefaultsIfNotSet()
->children()
->variableNode('options')->end()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(Group::class)->end()
->scalarNode('controller')->defaultValue(ResourceController::class)->end()
->scalarNode('repository')->defaultValue(GroupRepository::class)->end()
->scalarNode('factory')->defaultValue(Factory::class)->end()
->scalarNode('form')->defaultValue(GroupType::class)->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function addSubscriber(\Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber)
{
$this->subscriber[] = $subscriber;
return $this;
} | Add subscriber
@param \Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber
@return Group | entailment |
public function removeSubscriber(\Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber)
{
$this->subscriber->removeElement($subscriber);
} | Remove subscriber
@param \Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber | entailment |
public function load(array $config, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $config);
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$this->registerResources('enhavo_setting', $config['driver'], $config['resources'], $container);
$configFiles = array(
'services.yml',
);
foreach ($configFiles as $configFile) {
$loader->load($configFile);
}
} | {@inheritdoc} | entailment |
public function setOpenGraphImage(\Enhavo\Bundle\MediaBundle\Entity\File $openGraphImage = null)
{
$this->openGraphImage = $openGraphImage;
return $this;
} | Set openGraphImage
@param \Enhavo\Bundle\MediaBundle\Entity\File $openGraphImage
@return Content | entailment |
public function setShipment(ShipmentInterface $shipment = null)
{
$shipment->setOrder($this);
$this->shipment = $shipment;
return $this;
} | Set shipment
@param ShipmentInterface $shipment
@return Order | entailment |
public function getBotID() : int
{
// If it is not valid
if (!isset($this->_bot_id) || $this->_bot_id == 0) {
// get it again
$this->_bot_id = ($this->getMe())['id'];
}
return $this->_bot_id ?? 0;
} | \brief Get bot ID using `getMe` method.
@return int Bot id, 0 on errors. | entailment |
protected function processRequest(string $method, string $class = '', $file = false)
{
$url = "$method?" . http_build_query($this->parameters);
// If there is a file to upload
if ($file === false) {
$response = $this->execRequest($url);
} else {
$response = $this->execMultipartRequest($url);
}
if ($response === false) {
return false;
}
if ($class !== '') {
$object_class = "PhpBotFramework\Entities\\$class";
return new $object_class($response);
}
return $response;
} | \@internal
brief Process an API method by taking method and parameter.
\details optionally create a object of $class class name with the response as constructor param.
@param string $method Method to call.
@param array $param Parameter for the method.
@param string $class Class name of the object to create using response.
@return mixed Response or object of $class class name. | entailment |
public function withChatId($chat_id, $method, ...$param)
{
$last_chat = $this->chat_id;
$this->chat_id = $chat_id;
$value = $this->$method(...$param);
$this->chat_id = $last_chat;
return $value;
} | \brief Call a single api method using another chat_id without changing the current one.
@param string|int $chat_id API method target chat_id.
@param string $method Bot API method name.
@param mixed ...$param Parameters for the API method.
@return mixed The return value of the API method. | entailment |
public function useChatId($chat_id, \closure $closure)
{
$last_chat = $this->chat_id;
$this->chat_id = $chat_id;
$value = $closure();
$this->chat_id = $last_chat;
return $value;
} | \brief Call the closure with the selected `chat_id`.
\detail At the end of the method, $chat_id will still contain the original value.
@param string|int $chat_id Target chat while executing the closure.
@param closure $closure Closure to execute with the selected `chat_id`.
@return mixed The return value of the closure. | entailment |
public function releaseLock($name)
{
if (isset($this->files[$name])) {
flock($this->files[$name], LOCK_UN); // @todo Can LOCK_UN fail?
unset($this->locks[$name]);
fclose($this->files[$name]);
unset($this->files[$name]);
return true;
}
return false;
} | Release lock
@param string $name name of lock
@return bool | entailment |
protected function getProperty($resource, $property)
{
if($property == '_self') {
return $resource;
}
$propertyPath = explode('.', $property);
if(count($propertyPath) > 1) {
$property = array_shift($propertyPath);
$newResource = $this->getProperty($resource, $property);
if($newResource !== null) {
$propertyPath = implode('.', $propertyPath);
return $this->getProperty($newResource, $propertyPath);
} else {
return null;
}
} else {
$method = sprintf('is%s', ucfirst($property));
if(method_exists($resource, $method)) {
return call_user_func(array($resource, $method));
}
$method = sprintf('get%s', ucfirst($property));
if(method_exists($resource, $method)) {
return call_user_func(array($resource, $method));
}
}
throw new PropertyNotExistsException(sprintf(
'Trying to call "get%s" or "is%s" on class "%s", but method does not exists. Maybe you spelled it wrong or you didn\'t add the getter for property "%s"',
ucfirst($property),
ucfirst($property),
get_class($resource),
$property
));
} | Return the value the given property and object.
@param $resource
@param $property
@return mixed
@throws PropertyNotExistsException | entailment |
public function addTranslationData($entity, $propertyPath, $data)
{
$metadata = $this->metadataCollection->getMetadata($entity);
$property = $metadata->getProperty($propertyPath);
$strategy = $this->strategyResolver->getStrategy($property->getStrategy());
$strategy->addTranslationData($entity, $property, $data, $metadata);
} | Add translation data, but does not store it.
@param $entity
@param string $propertyPath Property of the entity, that should be added
@param mixed $data
@throws \Exception | entailment |
public function normalizeToTranslationData($entity, $propertyPath, $formData)
{
$metadata = $this->metadataCollection->getMetadata($entity);
$property = $metadata->getProperty($propertyPath);
$strategy = $this->strategyResolver->getStrategy($property->getStrategy());
return $strategy->normalizeToTranslationData($entity, $property, $formData, $metadata);
} | Normalize the form data. The data that a form contains after submit is a mix of the model data and the translation data.
This function will return only the translation data.
@param $entity
@param $propertyPath
@param $formData
@return mixed
@throws \Exception | entailment |
public function deleteTranslationData($entity)
{
$metadata = $this->metadataCollection->getMetadata($entity);
if($metadata === null) {
return null;
}
$strategies = $this->strategyResolver->getStrategies();
foreach($strategies as $strategy) {
$strategy->deleteTranslationData($entity, $metadata);
}
} | Prepare deleting all translation data. Because this function should be called inside a doctrine hook, it contains
no flush.
@param $entity
@return null
@throws \Exception | entailment |
public function getTranslationData($entity, Property $property)
{
$metadata = $this->metadataCollection->getMetadata($entity);
if($metadata === null) {
return null;
}
$metaProperty = $metadata->getProperty($property->getName());
if($metaProperty === null) {
throw new TranslationException(
sprintf('The property "%s" was used for translation, but no metadata was found. Maybe you forgot to define one for the entity "%s"',
$property->getName(),
get_class($entity)
));
}
$strategy = $this->strategyResolver->getStrategy($metaProperty->getStrategy());
return $strategy->getTranslationData($entity, $metaProperty, $metadata);
} | Return the translation data, that is already stored in the database
@param $entity
@param Property $property
@return null
@throws \Exception | entailment |
public function postFlush()
{
$strategies = $this->strategyResolver->getStrategies();
foreach($strategies as $strategy) {
$strategy->postFlush();
}
} | This function should be called after the flush was executed. | entailment |
public function translate($entity, $locale)
{
$metadata = $this->metadataCollection->getMetadata($entity);
if($metadata === null) {
return null;
}
//translation data is stored inside the object
if($locale === $this->defaultLocale) {
return;
}
$accessor = PropertyAccess::createPropertyAccessor();
if($metadata !== null) {
foreach($metadata->getProperties() as $property) {
$strategy = $this->strategyResolver->getStrategy($property->getStrategy());
$value = $strategy->getTranslation($entity, $property, $locale, $metadata);
$accessor->setValue($entity, $property->getName(), $value);
}
}
} | Translate an entity. All stored translation data will be applied to this object. It should be called only inside the
doctrine postLoad hook, because it doesn't handle recursive connections.
@param $entity
@param $locale
@return null
@throws \Exception | entailment |
public function getTranslation($entity, $property, $locale)
{
$metadata = $this->metadataCollection->getMetadata($entity);
if($metadata === null) {
return null;
}
$property = $metadata->getProperty($property);
if($property === null) {
return null;
}
$strategy = $this->strategyResolver->getStrategy($property->getStrategy());
return $strategy->getTranslation($entity, $property, $locale, $metadata);
} | Translate a single property of an entity.
@param $entity
@param $property
@param $locale
@return null
@throws \Exception | entailment |
public function setFile(\Enhavo\Bundle\MediaBundle\Model\FileInterface $file = null)
{
$this->file = $file;
return $this;
} | Set file
@param \Enhavo\Bundle\MediaBundle\Entity\File $file
@return Setting | entailment |
public function addFile(\Enhavo\Bundle\MediaBundle\Entity\File $file)
{
$this->files[] = $file;
return $this;
} | Add file
@param \Enhavo\Bundle\MediaBundle\Entity\File $file
@return Setting | entailment |
public function removeFile(\Enhavo\Bundle\MediaBundle\Entity\File $file)
{
$this->files->removeElement($file);
} | Remove file
@param \Enhavo\Bundle\MediaBundle\Entity\File $file | entailment |
public function init()
{
if (!isset($this->dom->documentElement)) {
return false;
}
// Assume successful outcome
$this->success = true;
$bodyElems = $this->dom->getElementsByTagName('body');
// WTF multiple body nodes?
if (null === $this->bodyCache) {
$this->bodyCache = '';
foreach ($bodyElems as $bodyNode) {
$this->bodyCache .= trim($bodyNode->getInnerHTML());
}
}
if ($bodyElems->length > 0 && null === $this->body) {
$this->body = $bodyElems->item(0);
}
$this->prepDocument();
// Build readability's DOM tree.
$overlay = $this->dom->createElement('div');
$innerDiv = $this->dom->createElement('div');
$articleTitle = $this->getArticleTitle();
$articleContent = $this->grabArticle();
if (!$articleContent) {
$this->success = false;
$articleContent = $this->dom->createElement('div');
$articleContent->setAttribute('class', 'readability-content');
$articleContent->setInnerHtml('<p>Sorry, Readability was unable to parse this page for content.</p>');
}
$overlay->setAttribute('class', 'readOverlay');
$innerDiv->setAttribute('class', 'readInner');
// Glue the structure of our document together.
$innerDiv->appendChild($articleTitle);
$innerDiv->appendChild($articleContent);
$overlay->appendChild($innerDiv);
// Clear the old HTML, insert the new content.
$this->body->setInnerHtml('');
$this->body->appendChild($overlay);
$this->body->removeAttribute('style');
$this->postProcessContent($articleContent);
// Set title and content instance variables.
$this->articleTitle = $articleTitle;
$this->articleContent = $articleContent;
return $this->success;
} | Runs readability.
Workflow:
1. Prep the document by removing script tags, css, etc.
2. Build readability's DOM tree.
3. Grab the article content from the current dom tree.
4. Replace the current DOM tree with the new one.
5. Read peacefully.
@return bool true if we found content, false otherwise | entailment |
public function postProcessContent(\DOMElement $articleContent)
{
if ($this->convertLinksToFootnotes && !preg_match('/\bwiki/', $this->url)) {
$this->addFootnotes($articleContent);
}
} | Run any post-process modifications to article content as necessary.
@param \DOMElement $articleContent | entailment |
public function addFootnotes(\DOMElement $articleContent)
{
$footnotesWrapper = $this->dom->createElement('footer');
$footnotesWrapper->setAttribute('class', 'readability-footnotes');
$footnotesWrapper->setInnerHtml('<h3>References</h3>');
$articleFootnotes = $this->dom->createElement('ol');
$articleFootnotes->setAttribute('class', 'readability-footnotes-list');
$footnotesWrapper->appendChild($articleFootnotes);
$articleLinks = $articleContent->getElementsByTagName('a');
$linkCount = 0;
for ($i = 0; $i < $articleLinks->length; ++$i) {
$articleLink = $articleLinks->item($i);
$footnoteLink = $articleLink->cloneNode(true);
$refLink = $this->dom->createElement('a');
$footnote = $this->dom->createElement('li');
$linkDomain = @parse_url($footnoteLink->getAttribute('href'), PHP_URL_HOST);
if (!$linkDomain && isset($this->url)) {
$linkDomain = @parse_url($this->url, PHP_URL_HOST);
}
$linkText = $this->getInnerText($articleLink);
if ((false !== strpos($articleLink->getAttribute('class'), 'readability-DoNotFootnote')) || preg_match($this->regexps['skipFootnoteLink'], $linkText)) {
continue;
}
++$linkCount;
// Add a superscript reference after the article link.
$refLink->setAttribute('href', '#readabilityFootnoteLink-' . $linkCount);
$refLink->setInnerHtml('<small><sup>[' . $linkCount . ']</sup></small>');
$refLink->setAttribute('class', 'readability-DoNotFootnote');
$refLink->setAttribute('style', 'color: inherit;');
if ($articleLink->parentNode->lastChild->isSameNode($articleLink)) {
$articleLink->parentNode->appendChild($refLink);
} else {
$articleLink->parentNode->insertBefore($refLink, $articleLink->nextSibling);
}
$articleLink->setAttribute('style', 'color: inherit; text-decoration: none;');
$articleLink->setAttribute('name', 'readabilityLink-' . $linkCount);
$footnote->setInnerHtml('<small><sup><a href="#readabilityLink-' . $linkCount . '" title="Jump to Link in Article">^</a></sup></small> ');
$footnoteLink->setInnerHtml(('' !== $footnoteLink->getAttribute('title') ? $footnoteLink->getAttribute('title') : $linkText));
$footnoteLink->setAttribute('name', 'readabilityFootnoteLink-' . $linkCount);
$footnote->appendChild($footnoteLink);
if ($linkDomain) {
$footnote->setInnerHtml($footnote->getInnerHTML() . '<small> (' . $linkDomain . ')</small>');
}
$articleFootnotes->appendChild($footnote);
}
if ($linkCount > 0) {
$articleContent->appendChild($footnotesWrapper);
}
} | For easier reading, convert this document to have footnotes at the bottom rather than inline links.
@see http://www.roughtype.com/archives/2010/05/experiments_in.php
@param \DOMElement $articleContent | entailment |
public function prepArticle(\DOMNode $articleContent)
{
if (!$articleContent instanceof \DOMElement) {
return;
}
$this->logger->debug($this->lightClean ? 'Light clean enabled.' : 'Standard clean enabled.');
$this->cleanStyles($articleContent);
$this->killBreaks($articleContent);
$xpath = new \DOMXPath($articleContent->ownerDocument);
if ($this->revertForcedParagraphElements) {
/*
* Reverts P elements with class 'readability-styled' to text nodes:
* which is what they were before.
*/
$elems = $xpath->query('.//p[@data-readability-styled]', $articleContent);
for ($i = $elems->length - 1; $i >= 0; --$i) {
$e = $elems->item($i);
$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
}
}
// Remove service data-candidate attribute.
$elems = $xpath->query('.//*[@data-candidate]', $articleContent);
for ($i = $elems->length - 1; $i >= 0; --$i) {
$elems->item($i)->removeAttribute('data-candidate');
}
// Clean out junk from the article content.
$this->clean($articleContent, 'input');
$this->clean($articleContent, 'button');
$this->clean($articleContent, 'nav');
$this->clean($articleContent, 'object');
$this->clean($articleContent, 'iframe');
$this->clean($articleContent, 'canvas');
$this->clean($articleContent, 'h1');
/*
* If there is only one h2, they are probably using it as a main header, so remove it since we
* already have a header.
*/
$h2s = $articleContent->getElementsByTagName('h2');
if (1 === $h2s->length && mb_strlen($this->getInnerText($h2s->item(0), true, true)) < 100) {
$this->clean($articleContent, 'h2');
}
$this->cleanHeaders($articleContent);
// Do these last as the previous stuff may have removed junk that will affect these.
$this->cleanConditionally($articleContent, 'form');
$this->cleanConditionally($articleContent, 'table');
$this->cleanConditionally($articleContent, 'ul');
$this->cleanConditionally($articleContent, 'div');
// Remove extra paragraphs.
$articleParagraphs = $articleContent->getElementsByTagName('p');
for ($i = $articleParagraphs->length - 1; $i >= 0; --$i) {
$item = $articleParagraphs->item($i);
$imgCount = $item->getElementsByTagName('img')->length;
$embedCount = $item->getElementsByTagName('embed')->length;
$objectCount = $item->getElementsByTagName('object')->length;
$videoCount = $item->getElementsByTagName('video')->length;
$audioCount = $item->getElementsByTagName('audio')->length;
$iframeCount = $item->getElementsByTagName('iframe')->length;
if (0 === $iframeCount && 0 === $imgCount && 0 === $embedCount && 0 === $objectCount && 0 === $videoCount && 0 === $audioCount && 0 === mb_strlen(preg_replace('/\s+/is', '', $this->getInnerText($item, false, false)))) {
$item->parentNode->removeChild($item);
}
// add extra text to iframe tag to avoid an auto-closing iframe and then break the html code
if ($iframeCount) {
$iframe = $item->getElementsByTagName('iframe');
$iframe->item(0)->nodeValue = ' ';
$item->parentNode->replaceChild($iframe->item(0), $item);
}
}
if (!$this->flagIsActive(self::FLAG_DISABLE_POSTFILTER)) {
try {
foreach ($this->post_filters as $search => $replace) {
$articleContent->setInnerHtml(preg_replace($search, $replace, $articleContent->getInnerHTML()));
}
unset($search, $replace);
} catch (\Exception $e) {
$this->logger->error('Cleaning output HTML failed. Ignoring: ' . $e->getMessage());
}
}
} | Prepare the article node for display. Clean out any inline styles,
iframes, forms, strip extraneous <p> tags, etc.
@param \DOMNode $articleContent | entailment |
public function getInnerText($e, $normalizeSpaces = true, $flattenLines = false)
{
if (null === $e || !isset($e->textContent) || '' === $e->textContent) {
return '';
}
$textContent = trim($e->textContent);
if ($flattenLines) {
$textContent = mb_ereg_replace('(?:[\r\n](?:\s| )*)+', '', $textContent);
} elseif ($normalizeSpaces) {
$textContent = mb_ereg_replace('\s\s+', ' ', $textContent);
}
return $textContent;
} | Get the inner text of a node.
This also strips out any excess whitespace to be found.
@param \DOMElement $e
@param bool $normalizeSpaces (default: true)
@param bool $flattenLines (default: false)
@return string | entailment |
public function cleanStyles($e)
{
if (!\is_object($e)) {
return;
}
$elems = $e->getElementsByTagName('*');
foreach ($elems as $elem) {
$elem->removeAttribute('style');
}
} | Remove the style attribute on every $e and under.
@param \DOMElement $e | entailment |
public function getLinkDensity(\DOMElement $e, $excludeExternal = false)
{
$links = $e->getElementsByTagName('a');
$textLength = mb_strlen($this->getInnerText($e, true, true));
$linkLength = 0;
for ($dRe = $this->domainRegExp, $i = 0, $il = $links->length; $i < $il; ++$i) {
if ($excludeExternal && $dRe && !preg_match($dRe, $links->item($i)->getAttribute('href'))) {
continue;
}
$linkLength += mb_strlen($this->getInnerText($links->item($i)));
}
if ($textLength > 0 && $linkLength > 0) {
return $linkLength / $textLength;
}
return 0;
} | Get the density of links as a percentage of the content
This is the amount of text that is inside a link divided by the total text in the node.
Can exclude external references to differentiate between simple text and menus/infoblocks.
@param \DOMElement $e
@param bool $excludeExternal
@return int | entailment |
public function getWeight(\DOMElement $e)
{
if (!$this->flagIsActive(self::FLAG_WEIGHT_ATTRIBUTES)) {
return 0;
}
$weight = 0;
// Look for a special classname
$weight += $this->weightAttribute($e, 'class');
// Look for a special ID
$weight += $this->weightAttribute($e, 'id');
return $weight;
} | Get an element relative weight.
@param \DOMElement $e
@return int | entailment |
public function killBreaks(\DOMElement $node)
{
$html = $node->getInnerHTML();
$html = preg_replace($this->regexps['killBreaks'], '<br />', $html);
$node->setInnerHtml($html);
} | Remove extraneous break tags from a node.
@param \DOMElement $node | entailment |
public function clean(\DOMElement $e, $tag)
{
$currentItem = null;
$targetList = $e->getElementsByTagName($tag);
$isEmbed = ('audio' === $tag || 'video' === $tag || 'iframe' === $tag || 'object' === $tag || 'embed' === $tag);
for ($y = $targetList->length - 1; $y >= 0; --$y) {
// Allow youtube and vimeo videos through as people usually want to see those.
$currentItem = $targetList->item($y);
if ($isEmbed) {
$attributeValues = $currentItem->getAttribute('src') . ' ' . $currentItem->getAttribute('href');
// First, check the elements attributes to see if any of them contain known media hosts
if (preg_match($this->regexps['media'], $attributeValues)) {
continue;
}
// Then check the elements inside this element for the same.
if (preg_match($this->regexps['media'], $targetList->item($y)->getInnerHTML())) {
continue;
}
}
$currentItem->parentNode->removeChild($currentItem);
}
} | Clean a node of all elements of type "tag".
(Unless it's a youtube/vimeo video. People love movies.).
Updated 2012-09-18 to preserve youtube/vimeo iframes
@param \DOMElement $e
@param string $tag | entailment |
public function cleanConditionally(\DOMElement $e, $tag)
{
if (!$this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {
return;
}
$tagsList = $e->getElementsByTagName($tag);
$curTagsLength = $tagsList->length;
$node = null;
/*
* Gather counts for other typical elements embedded within.
* Traverse backwards so we can remove nodes at the same time without effecting the traversal.
*
* TODO: Consider taking into account original contentScore here.
*/
for ($i = $curTagsLength - 1; $i >= 0; --$i) {
$node = $tagsList->item($i);
$weight = $this->getWeight($node);
$contentScore = ($node->hasAttribute('readability')) ? (int) $node->getAttribute('readability') : 0;
$this->logger->debug('Start conditional cleaning of ' . $node->getNodePath() . ' (class=' . $node->getAttribute('class') . '; id=' . $node->getAttribute('id') . ')' . (($node->hasAttribute('readability')) ? (' with score ' . $node->getAttribute('readability')) : ''));
if ($weight + $contentScore < 0) {
$this->logger->debug('Removing...');
$node->parentNode->removeChild($node);
} elseif ($this->getCommaCount($this->getInnerText($node)) < self::MIN_COMMAS_IN_PARAGRAPH) {
/*
* If there are not very many commas, and the number of
* non-paragraph elements is more than paragraphs or other ominous signs, remove the element.
*/
$p = $node->getElementsByTagName('p')->length;
$img = $node->getElementsByTagName('img')->length;
$li = $node->getElementsByTagName('li')->length - 100;
$input = $node->getElementsByTagName('input')->length;
$a = $node->getElementsByTagName('a')->length;
$embedCount = 0;
$embeds = $node->getElementsByTagName('embed');
for ($ei = 0, $il = $embeds->length; $ei < $il; ++$ei) {
if (preg_match($this->regexps['media'], $embeds->item($ei)->getAttribute('src'))) {
++$embedCount;
}
}
$embeds = $node->getElementsByTagName('iframe');
for ($ei = 0, $il = $embeds->length; $ei < $il; ++$ei) {
if (preg_match($this->regexps['media'], $embeds->item($ei)->getAttribute('src'))) {
++$embedCount;
}
}
$linkDensity = $this->getLinkDensity($node, true);
$contentLength = mb_strlen($this->getInnerText($node));
$toRemove = false;
if ($this->lightClean) {
if ($li > $p && 'ul' !== $tag && 'ol' !== $tag) {
$this->logger->debug(' too many <li> elements, and parent is not <ul> or <ol>');
$toRemove = true;
} elseif ($input > floor($p / 3)) {
$this->logger->debug(' too many <input> elements');
$toRemove = true;
} elseif ($contentLength < 6 && (0 === $embedCount && (0 === $img || $img > 2))) {
$this->logger->debug(' content length less than 6 chars, 0 embeds and either 0 images or more than 2 images');
$toRemove = true;
} elseif ($weight < 25 && $linkDensity > 0.25) {
$this->logger->debug(' weight is ' . $weight . ' < 25 and link density is ' . sprintf('%.2f', $linkDensity) . ' > 0.25');
$toRemove = true;
} elseif ($a > 2 && ($weight >= 25 && $linkDensity > 0.5)) {
$this->logger->debug(' more than 2 links and weight is ' . $weight . ' > 25 but link density is ' . sprintf('%.2f', $linkDensity) . ' > 0.5');
$toRemove = true;
} elseif ($embedCount > 3) {
$this->logger->debug(' more than 3 embeds');
$toRemove = true;
}
} else {
if ($img > $p) {
$this->logger->debug(' more image elements than paragraph elements');
$toRemove = true;
} elseif ($li > $p && 'ul' !== $tag && 'ol' !== $tag) {
$this->logger->debug(' too many <li> elements, and parent is not <ul> or <ol>');
$toRemove = true;
} elseif ($input > floor($p / 3)) {
$this->logger->debug(' too many <input> elements');
$toRemove = true;
} elseif ($contentLength < 10 && (0 === $img || $img > 2)) {
$this->logger->debug(' content length less than 10 chars and 0 images, or more than 2 images');
$toRemove = true;
} elseif ($weight < 25 && $linkDensity > 0.2) {
$this->logger->debug(' weight is ' . $weight . ' lower than 0 and link density is ' . sprintf('%.2f', $linkDensity) . ' > 0.2');
$toRemove = true;
} elseif ($weight >= 25 && $linkDensity > 0.5) {
$this->logger->debug(' weight above 25 but link density is ' . sprintf('%.2f', $linkDensity) . ' > 0.5');
$toRemove = true;
} elseif ((1 === $embedCount && $contentLength < 75) || $embedCount > 1) {
$this->logger->debug(' 1 embed and content length smaller than 75 chars, or more than one embed');
$toRemove = true;
}
}
if ($toRemove) {
$this->logger->debug('Removing...');
$node->parentNode->removeChild($node);
}
}
}
} | Clean an element of all tags of type "tag" if they look fishy.
"Fishy" is an algorithm based on content length, classnames,
link density, number of images & embeds, etc.
@param \DOMElement $e
@param string $tag | entailment |
public function cleanHeaders(\DOMElement $e)
{
for ($headerIndex = 1; $headerIndex < 3; ++$headerIndex) {
$headers = $e->getElementsByTagName('h' . $headerIndex);
for ($i = $headers->length - 1; $i >= 0; --$i) {
if ($this->getWeight($headers->item($i)) < 0 || $this->getLinkDensity($headers->item($i)) > 0.33) {
$headers->item($i)->parentNode->removeChild($headers->item($i));
}
}
}
} | Clean out spurious headers from an Element. Checks things like classnames and link density.
@param \DOMElement $e | entailment |
protected function getArticleTitle()
{
try {
$curTitle = $origTitle = $this->getInnerText($this->dom->getElementsByTagName('title')->item(0));
} catch (\Exception $e) {
$curTitle = '';
$origTitle = '';
}
if (preg_match('/ [\|\-] /', $curTitle)) {
$curTitle = preg_replace('/(.*)[\|\-] .*/i', '$1', $origTitle);
if (\count(explode(' ', $curTitle)) < 3) {
$curTitle = preg_replace('/[^\|\-]*[\|\-](.*)/i', '$1', $origTitle);
}
} elseif (false !== strpos($curTitle, ': ')) {
$curTitle = preg_replace('/.*:(.*)/i', '$1', $origTitle);
if (\count(explode(' ', $curTitle)) < 3) {
$curTitle = preg_replace('/[^:]*[:](.*)/i', '$1', $origTitle);
}
} elseif (mb_strlen($curTitle) > 150 || mb_strlen($curTitle) < 15) {
$hOnes = $this->dom->getElementsByTagName('h1');
if (1 === $hOnes->length) {
$curTitle = $this->getInnerText($hOnes->item(0));
}
}
$curTitle = trim($curTitle);
if (\count(explode(' ', $curTitle)) <= 4) {
$curTitle = $origTitle;
}
$articleTitle = $this->dom->createElement('h1');
$articleTitle->setInnerHtml($curTitle);
return $articleTitle;
} | Get the article title as an H1.
@return \DOMElement | entailment |
protected function prepDocument()
{
/*
* In some cases a body element can't be found (if the HTML is totally hosed for example)
* so we create a new body node and append it to the document.
*/
if (null === $this->body) {
$this->body = $this->dom->createElement('body');
$this->dom->documentElement->appendChild($this->body);
}
$this->body->setAttribute('class', 'readabilityBody');
// Remove all style tags in head.
$styleTags = $this->dom->getElementsByTagName('style');
for ($i = $styleTags->length - 1; $i >= 0; --$i) {
$styleTags->item($i)->parentNode->removeChild($styleTags->item($i));
}
$linkTags = $this->dom->getElementsByTagName('link');
for ($i = $linkTags->length - 1; $i >= 0; --$i) {
$linkTags->item($i)->parentNode->removeChild($linkTags->item($i));
}
} | Prepare the HTML document for readability to scrape it.
This includes things like stripping javascript, CSS, and handling terrible markup. | entailment |
protected function initializeNode(\DOMElement $node)
{
if (!isset($node->tagName)) {
return;
}
$readability = $this->dom->createAttribute('readability');
// this is our contentScore
$readability->value = 0;
$node->setAttributeNode($readability);
// using strtoupper just in case
switch (strtoupper($node->tagName)) {
case 'ARTICLE':
$readability->value += 15;
// no break
case 'DIV':
$readability->value += 5;
break;
case 'PRE':
case 'CODE':
case 'TD':
case 'BLOCKQUOTE':
case 'FIGURE':
$readability->value += 3;
break;
case 'SECTION':
// often misused
// $readability->value += 2;
break;
case 'OL':
case 'UL':
case 'DL':
case 'DD':
case 'DT':
case 'LI':
$readability->value -= 2 * round($this->getLinkDensity($node), 0, PHP_ROUND_HALF_UP);
break;
case 'ASIDE':
case 'FOOTER':
case 'HEADER':
case 'ADDRESS':
case 'FORM':
case 'BUTTON':
case 'TEXTAREA':
case 'INPUT':
case 'NAV':
$readability->value -= 3;
break;
case 'H1':
case 'H2':
case 'H3':
case 'H4':
case 'H5':
case 'H6':
case 'TH':
case 'HGROUP':
$readability->value -= 5;
break;
}
$readability->value += $this->getWeight($node);
} | Initialize a node with the readability object. Also checks the
className/id for special names to add to its score.
@param \DOMElement $node | entailment |
protected function grabArticle(\DOMElement $page = null)
{
if (!$page) {
$page = $this->dom;
}
$xpath = null;
$nodesToScore = [];
if ($page instanceof \DOMDocument && isset($page->documentElement)) {
$xpath = new \DOMXPath($page);
}
$allElements = $page->getElementsByTagName('*');
for ($nodeIndex = 0; ($node = $allElements->item($nodeIndex)); ++$nodeIndex) {
$tagName = $node->tagName;
// Some well known site uses sections as paragraphs.
if (0 === strcasecmp($tagName, 'p') || 0 === strcasecmp($tagName, 'td') || 0 === strcasecmp($tagName, 'pre') || 0 === strcasecmp($tagName, 'section')) {
$nodesToScore[] = $node;
}
// Turn divs into P tags where they have been used inappropriately
// (as in, where they contain no other block level elements).
if (0 === strcasecmp($tagName, 'div') || 0 === strcasecmp($tagName, 'article') || 0 === strcasecmp($tagName, 'section')) {
if (!preg_match($this->regexps['divToPElements'], $node->getInnerHTML())) {
$newNode = $this->dom->createElement('p');
try {
$newNode->setInnerHtml($node->getInnerHTML());
$node->parentNode->replaceChild($newNode, $node);
--$nodeIndex;
$nodesToScore[] = $newNode;
} catch (\Exception $e) {
$this->logger->error('Could not alter div/article to p, reverting back to div: ' . $e->getMessage());
}
} else {
// Will change these P elements back to text nodes after processing.
for ($i = 0, $il = $node->childNodes->length; $i < $il; ++$i) {
$childNode = $node->childNodes->item($i);
// it looks like sometimes the loop is going too far and we are retrieving a non-existant child
if (null === $childNode) {
continue;
}
// executable tags (<?php or <?xml) warning
if (\is_object($childNode) && 'DOMProcessingInstruction' === \get_class($childNode)) {
$childNode->parentNode->removeChild($childNode);
continue;
}
if (XML_TEXT_NODE === $childNode->nodeType) {
$p = $this->dom->createElement('p');
$p->setInnerHtml($childNode->nodeValue);
$p->setAttribute('data-readability-styled', 'true');
$childNode->parentNode->replaceChild($p, $childNode);
}
}
}
}
}
/*
* Loop through all paragraphs, and assign a score to them based on how content-y they look.
* Then add their score to their parent node.
*
* A score is determined by things like number of commas, class names, etc.
* Maybe eventually link density.
*/
for ($pt = 0, $scored = \count($nodesToScore); $pt < $scored; ++$pt) {
$parentNode = $nodesToScore[$pt]->parentNode;
// No parent node? Move on...
if (!$parentNode) {
continue;
}
$grandParentNode = $parentNode->parentNode instanceof \DOMElement ? $parentNode->parentNode : null;
$innerText = $this->getInnerText($nodesToScore[$pt]);
// If this paragraph is less than MIN_PARAGRAPH_LENGTH (default:20) characters, don't even count it.
if (mb_strlen($innerText) < self::MIN_PARAGRAPH_LENGTH) {
continue;
}
// Initialize readability data for the parent.
if (!$parentNode->hasAttribute('readability')) {
$this->initializeNode($parentNode);
$parentNode->setAttribute('data-candidate', 'true');
}
// Initialize readability data for the grandparent.
if ($grandParentNode && !$grandParentNode->hasAttribute('readability') && isset($grandParentNode->tagName)) {
$this->initializeNode($grandParentNode);
$grandParentNode->setAttribute('data-candidate', 'true');
}
// Add a point for the paragraph itself as a base.
$contentScore = 1;
// Add points for any commas within this paragraph.
$contentScore += $this->getCommaCount($innerText);
// For every SCORE_CHARS_IN_PARAGRAPH (default:100) characters in this paragraph, add another point. Up to 3 points.
$contentScore += min(floor(mb_strlen($innerText) / self::SCORE_CHARS_IN_PARAGRAPH), 3);
// For every SCORE_WORDS_IN_PARAGRAPH (default:20) words in this paragraph, add another point. Up to 3 points.
$contentScore += min(floor($this->getWordCount($innerText) / self::SCORE_WORDS_IN_PARAGRAPH), 3);
/* TEST: For every positive/negative parent tag, add/substract half point. Up to 3 points. *\/
$up = $nodesToScore[$pt];
$score = 0;
while ($up->parentNode instanceof \DOMElement) {
$up = $up->parentNode;
if (preg_match($this->regexps['positive'], $up->getAttribute('class') . ' ' . $up->getAttribute('id'))) {
$score += 0.5;
} elseif (preg_match($this->regexps['negative'], $up->getAttribute('class') . ' ' . $up->getAttribute('id'))) {
$score -= 0.5;
}
}
$score = floor($score);
$contentScore += max(min($score, 3), -3);/**/
// Add the score to the parent. The grandparent gets half.
$parentNode->getAttributeNode('readability')->value += $contentScore;
if ($grandParentNode) {
$grandParentNode->getAttributeNode('readability')->value += $contentScore / self::GRANDPARENT_SCORE_DIVISOR;
}
}
/*
* Node prepping: trash nodes that look cruddy (like ones with the class name "comment", etc).
* This is faster to do before scoring but safer after.
*/
if ($this->flagIsActive(self::FLAG_STRIP_UNLIKELYS) && $xpath) {
$candidates = $xpath->query('.//*[(self::footer and count(//footer)<2) or (self::aside and count(//aside)<2)]', $page->documentElement);
$node = null;
for ($c = $candidates->length - 1; $c >= 0; --$c) {
$node = $candidates->item($c);
// node should be readable but not inside of an article otherwise it's probably non-readable block
if ($node->hasAttribute('readability') && (int) $node->getAttributeNode('readability')->value < 40 && ($node->parentNode ? 0 !== strcasecmp($node->parentNode->tagName, 'article') : true)) {
$this->logger->debug('Removing unlikely candidate (using note) ' . $node->getNodePath() . ' by "' . $node->tagName . '" with readability ' . ($node->hasAttribute('readability') ? (int) $node->getAttributeNode('readability')->value : 0));
$node->parentNode->removeChild($node);
}
}
$candidates = $xpath->query('.//*[not(self::body) and (@class or @id or @style) and ((number(@readability) < 40) or not(@readability))]', $page->documentElement);
$node = null;
for ($c = $candidates->length - 1; $c >= 0; --$c) {
$node = $candidates->item($c);
// Remove unlikely candidates
$unlikelyMatchString = $node->getAttribute('class') . ' ' . $node->getAttribute('id') . ' ' . $node->getAttribute('style');
if (mb_strlen($unlikelyMatchString) > 3 && // don't process "empty" strings
preg_match($this->regexps['unlikelyCandidates'], $unlikelyMatchString) &&
!preg_match($this->regexps['okMaybeItsACandidate'], $unlikelyMatchString)
) {
$this->logger->debug('Removing unlikely candidate (using conf) ' . $node->getNodePath() . ' by "' . $unlikelyMatchString . '" with readability ' . ($node->hasAttribute('readability') ? (int) $node->getAttributeNode('readability')->value : 0));
$node->parentNode->removeChild($node);
--$nodeIndex;
}
}
unset($candidates);
}
/*
* After we've calculated scores, loop through all of the possible candidate nodes we found
* and find the one with the highest score.
*/
$topCandidate = null;
if ($xpath) {
// Using array of DOMElements after deletion is a path to DOOMElement.
$candidates = $xpath->query('.//*[@data-candidate]', $page->documentElement);
for ($c = $candidates->length - 1; $c >= 0; --$c) {
$item = $candidates->item($c);
// Scale the final candidates score based on link density. Good content should have a
// relatively small link density (5% or less) and be mostly unaffected by this operation.
// If not for this we would have used XPath to find maximum @readability.
$readability = $item->getAttributeNode('readability');
$readability->value = round($readability->value * (1 - $this->getLinkDensity($item)), 0, PHP_ROUND_HALF_UP);
if (!$topCandidate || $readability->value > (int) $topCandidate->getAttribute('readability')) {
$this->logger->debug('Candidate: ' . $item->getNodePath() . ' (' . $item->getAttribute('class') . ':' . $item->getAttribute('id') . ') with score ' . $readability->value);
$topCandidate = $item;
}
}
unset($candidates);
}
/*
* If we still have no top candidate, just use the body as a last resort.
* We also have to copy the body node so it is something we can modify.
*/
if (null === $topCandidate || 0 === strcasecmp($topCandidate->tagName, 'body')) {
$topCandidate = $this->dom->createElement('div');
if ($page instanceof \DOMDocument) {
if (!isset($page->documentElement)) {
// we don't have a body either? what a mess! :)
$this->logger->debug('The page has no body!');
} else {
$this->logger->debug('Setting body to a raw HTML of original page!');
$topCandidate->setInnerHtml($page->documentElement->getInnerHTML());
$page->documentElement->setInnerHtml('');
$this->reinitBody();
$page->documentElement->appendChild($topCandidate);
}
} else {
$topCandidate->setInnerHtml($page->getInnerHTML());
$page->setInnerHtml('');
$page->appendChild($topCandidate);
}
$this->initializeNode($topCandidate);
}
// Set table as the main node if resulted data is table element.
$tagName = $topCandidate->tagName;
if (0 === strcasecmp($tagName, 'td') || 0 === strcasecmp($tagName, 'tr')) {
$up = $topCandidate;
if ($up->parentNode instanceof \DOMElement) {
$up = $up->parentNode;
if (0 === strcasecmp($up->tagName, 'table')) {
$topCandidate = $up;
}
}
}
$this->logger->debug('Top candidate: ' . $topCandidate->getNodePath());
/*
* Now that we have the top candidate, look through its siblings for content that might also be related.
* Things like preambles, content split by ads that we removed, etc.
*/
$articleContent = $this->dom->createElement('div');
$articleContent->setAttribute('class', 'readability-content');
$siblingScoreThreshold = max(10, ((int) $topCandidate->getAttribute('readability')) * 0.2);
$siblingNodes = $topCandidate->parentNode->childNodes;
if (null === $siblingNodes) {
$siblingNodes = new \stdClass();
$siblingNodes->length = 0;
}
for ($s = 0, $sl = $siblingNodes->length; $s < $sl; ++$s) {
$siblingNode = $siblingNodes->item($s);
$siblingNodeName = $siblingNode->nodeName;
$append = false;
$this->logger->debug('Looking at sibling node: ' . $siblingNode->getNodePath() . ((XML_ELEMENT_NODE === $siblingNode->nodeType && $siblingNode->hasAttribute('readability')) ? (' with score ' . $siblingNode->getAttribute('readability')) : ''));
if ($siblingNode->isSameNode($topCandidate)) {
$append = true;
}
$contentBonus = 0;
// Give a bonus if sibling nodes and top candidates have the same classname.
if (XML_ELEMENT_NODE === $siblingNode->nodeType && $siblingNode->getAttribute('class') === $topCandidate->getAttribute('class') && '' !== $topCandidate->getAttribute('class')) {
$contentBonus += ((int) $topCandidate->getAttribute('readability')) * 0.2;
}
if (XML_ELEMENT_NODE === $siblingNode->nodeType && $siblingNode->hasAttribute('readability') && (((int) $siblingNode->getAttribute('readability')) + $contentBonus) >= $siblingScoreThreshold) {
$append = true;
}
if (0 === strcasecmp($siblingNodeName, 'p')) {
$linkDensity = $this->getLinkDensity($siblingNode);
$nodeContent = $this->getInnerText($siblingNode, true, true);
$nodeLength = mb_strlen($nodeContent);
if (($nodeLength > self::MIN_NODE_LENGTH && $linkDensity < self::MAX_LINK_DENSITY)
|| ($nodeLength < self::MIN_NODE_LENGTH && 0 === $linkDensity && preg_match('/\.( |$)/', $nodeContent))) {
$append = true;
}
}
if ($append) {
$this->logger->debug('Appending node: ' . $siblingNode->getNodePath());
if (0 !== strcasecmp($siblingNodeName, 'div') && 0 !== strcasecmp($siblingNodeName, 'p')) {
// We have a node that isn't a common block level element, like a form or td tag. Turn it into a div so it doesn't get filtered out later by accident.
$this->logger->debug('Altering siblingNode "' . $siblingNodeName . '" to "div".');
$nodeToAppend = $this->dom->createElement('div');
try {
$nodeToAppend->setAttribute('alt', $siblingNodeName);
$nodeToAppend->setInnerHtml($siblingNode->getInnerHTML());
} catch (\Exception $e) {
$this->logger->debug('Could not alter siblingNode "' . $siblingNodeName . '" to "div", reverting to original.');
$nodeToAppend = $siblingNode;
--$s;
--$sl;
}
} else {
$nodeToAppend = $siblingNode;
--$s;
--$sl;
}
// To ensure a node does not interfere with readability styles, remove its classnames & ids.
// Now done via RegExp post_filter.
//$nodeToAppend->removeAttribute('class');
//$nodeToAppend->removeAttribute('id');
// Append sibling and subtract from our list as appending removes a node.
$articleContent->appendChild($nodeToAppend);
}
}
unset($xpath);
// So we have all of the content that we need. Now we clean it up for presentation.
$this->prepArticle($articleContent);
/*
* Now that we've gone through the full algorithm, check to see if we got any meaningful content.
* If we didn't, we may need to re-run grabArticle with different flags set. This gives us a higher
* likelihood of finding the content, and the sieve approach gives us a higher likelihood of
* finding the -right- content.
*/
if (mb_strlen($this->getInnerText($articleContent, false)) < self::MIN_ARTICLE_LENGTH) {
$this->reinitBody();
if ($this->flagIsActive(self::FLAG_STRIP_UNLIKELYS)) {
$this->removeFlag(self::FLAG_STRIP_UNLIKELYS);
$this->logger->debug('...content is shorter than ' . self::MIN_ARTICLE_LENGTH . " letters, trying not to strip unlikely content.\n");
return $this->grabArticle($this->body);
} elseif ($this->flagIsActive(self::FLAG_WEIGHT_ATTRIBUTES)) {
$this->removeFlag(self::FLAG_WEIGHT_ATTRIBUTES);
$this->logger->debug('...content is shorter than ' . self::MIN_ARTICLE_LENGTH . " letters, trying not to weight attributes.\n");
return $this->grabArticle($this->body);
} elseif ($this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {
$this->removeFlag(self::FLAG_CLEAN_CONDITIONALLY);
$this->logger->debug('...content is shorter than ' . self::MIN_ARTICLE_LENGTH . " letters, trying not to clean at all.\n");
return $this->grabArticle($this->body);
}
return false;
}
return $articleContent;
} | Using a variety of metrics (content score, classname, element types), find the content that is
most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
@param \DOMElement $page
@return \DOMElement|false | entailment |
protected function weightAttribute(\DOMElement $element, $attribute)
{
if (!$element->hasAttribute($attribute)) {
return 0;
}
$weight = 0;
// $attributeValue = trim($element->getAttribute('class')." ".$element->getAttribute('id'));
$attributeValue = trim($element->getAttribute($attribute));
if ('' !== $attributeValue) {
if (preg_match($this->regexps['negative'], $attributeValue)) {
$weight -= 25;
}
if (preg_match($this->regexps['positive'], $attributeValue)) {
$weight += 25;
}
if (preg_match($this->regexps['unlikelyCandidates'], $attributeValue)) {
$weight -= 5;
}
if (preg_match($this->regexps['okMaybeItsACandidate'], $attributeValue)) {
$weight += 5;
}
}
return $weight;
} | Get an element weight by attribute.
Uses regular expressions to tell if this element looks good or bad.
@param \DOMElement $element
@param string $attribute
@return int | entailment |
protected function reinitBody()
{
if (!isset($this->body->childNodes)) {
$this->body = $this->dom->createElement('body');
$this->body->setInnerHtml($this->bodyCache);
}
} | Will recreate previously deleted body property. | entailment |
private function loadHtml()
{
$this->original_html = $this->html;
$this->logger->debug('Parsing URL: ' . $this->url);
if ($this->url) {
$this->domainRegExp = '/' . strtr(preg_replace('/www\d*\./', '', parse_url($this->url, PHP_URL_HOST)), ['.' => '\.']) . '/';
}
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_regex_encoding('UTF-8');
// HACK: dirty cleanup to replace some stuff; shouldn't use regexps with HTML but well...
if (!$this->flagIsActive(self::FLAG_DISABLE_PREFILTER)) {
foreach ($this->pre_filters as $search => $replace) {
$this->html = preg_replace($search, $replace, $this->html);
}
unset($search, $replace);
}
if ('' === trim($this->html)) {
$this->html = '<html></html>';
}
/*
* Use tidy (if it exists).
* This fixes problems with some sites which would otherwise trouble DOMDocument's HTML parsing.
* Although sometimes it makes matters worse, which is why there is an option to disable it.
*/
if ($this->useTidy) {
$this->logger->debug('Tidying document');
$tidy = tidy_repair_string($this->html, $this->tidy_config, 'UTF8');
if (false !== $tidy && $this->html !== $tidy) {
$this->tidied = true;
$this->html = $tidy;
$this->html = preg_replace('/[\r\n]+/is', "\n", $this->html);
}
unset($tidy);
}
$this->html = mb_convert_encoding($this->html, 'HTML-ENTITIES', 'UTF-8');
if ('html5lib' === $this->parser) {
$this->dom = Parser::parse($this->html);
}
if ('libxml' === $this->parser) {
libxml_use_internal_errors(true);
$this->dom = new \DOMDocument();
$this->dom->preserveWhiteSpace = false;
$this->dom->loadHTML($this->html, LIBXML_NOBLANKS | LIBXML_COMPACT | LIBXML_NOERROR);
libxml_use_internal_errors(false);
}
$this->dom->registerNodeClass('DOMElement', 'Readability\JSLikeHTMLElement');
} | Load HTML in a DOMDocument.
Apply Pre filters
Cleanup HTML using Tidy (or not).
@todo This should be called in init() instead of from __construct | entailment |
public function validate($value, Constraint $constraint)
{
if($value instanceof SubscriberInterface) {
if($this->manager->exists($value, $value->getType())) {
$this->context->buildViolation($constraint->message)
->setParameter('%email%', $value->getEmail())
->addViolation();
}
}
} | @param mixed $value
@param Constraint $constraint | entailment |
public function loadAllLanguages(string $dir = './localization') : bool
{
if ($handle = opendir($dir)) {
// Iterate over all files
while (false !== ($file = readdir($handle))) {
// If the file is a JSON data file
if (strlen($file) > 6 && substr($file, -5) === '.json') {
try {
// Add the contents of the file to the $local variable, after converting it to a PHP object.
// The contents will be added with the 2 letter of the file as the index
$this->local[substr($file, 0, 2)] = json_decode(file_get_contents("$dir/$file"), true);
} catch (BotException $e) {
echo $e->getMessage();
}
}
}
return true;
}
return false;
} | \brief Load all localization files (like JSON) from a folder and set them in <code>$local</code> variable.
\details Save all localization files, using JSON format, from a directory and put
the contents in <code>$local</code> variable.
Each file will be saved into <code>$local</code> with the first two letters of the filename as the index.
@param string $dir Source directory for localization files.
@return bool True if the directory could be opened without errors. | entailment |
public function addFiles(FileInterface $file)
{
if ($this->files === null) {
$this->files = new ArrayCollection();
}
$this->files[] = $file;
return $this;
} | Add files
@param FileInterface $file
@return GalleryItem | entailment |
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
if(isset($config['forms']) && is_array($config['forms'])) {
foreach($config['forms'] as $name => $form) {
$container->setParameter(sprintf('enhavo_contact.%s.model', $name), $form['model']);
$container->setParameter(sprintf('enhavo_contact.%s.form', $name), $form['form']);
$container->setParameter(sprintf('enhavo_contact.%s.template.form', $name), $form['template']['form']);
$container->setParameter(sprintf('enhavo_contact.%s.template.recipient', $name), $form['template']['recipient']);
$container->setParameter(sprintf('enhavo_contact.%s.template.confirm', $name), $form['template']['confirm']);
$container->setParameter(sprintf('enhavo_contact.%s.template.page', $name), $form['template']['page']);
$container->setParameter(sprintf('enhavo_contact.%s.recipient', $name), $form['recipient']);
$container->setParameter(sprintf('enhavo_contact.%s.from', $name), $form['from']);
$container->setParameter(sprintf('enhavo_contact.%s.sender_name', $name), $form['sender_name']);
$container->setParameter(sprintf('enhavo_contact.%s.subject', $name), $form['subject']);
$container->setParameter(sprintf('enhavo_contact.%s.translation_domain', $name), $form['translation_domain']);
$container->setParameter(sprintf('enhavo_contact.%s.confirm_mail', $name), $form['confirm_mail']);
}
$container->setParameter('enhavo_contact.forms', $config['forms']);
}
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
} | {@inheritdoc} | entailment |
public function getStatus(int $default_status = -1) : int
{
$chat_id = $this->bot->chat_id;
$redis = $this->bot->getRedis();
if ($redis->exists($chat_id . ':status')) {
$this->status = $redis->get($chat_id . ':status');
return $this->status;
}
$redis->set($chat_id . ':status', $default_status);
$this->status = $default_status;
return $this->status;
} | \brief Get current user status from Redis and set it in status variable.
\details Throws an exception if the Redis connection is missing.
@param int $default_status <i>Optional</i>. The default status to return
if there is no status for the current user.
@return int The status for the current user, $default_status if missing. | entailment |
public function setStatus(int $status)
{
$redis = $this->bot->getRedis();
$redis->set($this->bot->chat_id . ':status', $status);
$this->status = $status;
} | \brief Set the status of the bot in both Redis and $status.
\details Throws an exception if the Redis connection is missing.
@param int $status The new status of the bot. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.