* Developed by Alexander Hass, http://www.yaml-for-drupal.com/.
*/
+use Drupal\Component\Utility\Crypt;
+use Drupal\Component\Utility\Html;
+use Drupal\Component\Utility\Unicode;
+use Drupal\Component\Utility\UrlHelper;
+use Drupal\Component\Utility\Timer;
+use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Routing\RouteMatchInterface;
+use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\UserSession;
+use Drupal\Core\Url;
+use Drupal\field\FieldConfigInterface;
+use Drupal\filter\Entity;
+use Drupal\field\Entity\FieldStorageConfig;
+use Drupal\filter\Entity\FilterFormat;
+use Drupal\node\Entity\Node;
+use Drupal\node\Entity\NodeType;
+use Drupal\node\NodeInterface;
use Drupal\node\NodeTypeInterface;
-use GuzzleHttp\Exception\RequestException;
-
+use GuzzleHttp\Exception\ClientException;
/**
* Defines the maximum limit of links collected in one chunk if content is
* translate.
* @param $severity
* The severity of the message; one of the following values as defined in
- * @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
+ * @param $link
+ * A link to associate with the message.
+ *
+ * @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
* - WATCHDOG_EMERGENCY: Emergency, system is unusable.
- * - WATCHDOG_ALERT: Alert, action must be taken immediately.
- * - WATCHDOG_CRITICAL: Critical conditions.
+ * - RfcLogLevel::ALERT: Alert, action must be taken immediately.
+ * - RfcLogLevel::CRITICAL: Critical conditions.
* - WATCHDOG_ERROR: Error conditions.
* - WATCHDOG_WARNING: Warning conditions.
- * - WATCHDOG_NOTICE: (default) Normal but significant conditions.
+ * - RfcLogLevel::NOTICE: (default) Normal but significant conditions.
* - WATCHDOG_INFO: Informational messages.
* - WATCHDOG_DEBUG: Debug-level messages.
- * @param $link
- * A link to associate with the message.
- *
* @see watchdog_severity_levels()
* @see watchdog()
*/
-function linkchecker_watchdog_log($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
- if ($severity <= variable_get('linkchecker_log_level', WATCHDOG_INFO)) {
- watchdog($type, $message, $variables, $severity, $link);
+function linkchecker_watchdog_log($type, $message, $variables = [], $severity = RfcLogLevel::NOTICE, $link = NULL) {
+ // @FIXME: $link is missing, could be in $variables.
+ if ($severity <= \Drupal::config('linkchecker.settings')->get('logging.level')) {
+ $logger = \Drupal::logger($type);
+ $logger->log($severity, $message, $variables);
}
}
* @return int|bool
*/
function _linkchecker_user_access_account_broken_links_report($account) {
- global $user;
+ $user = \Drupal::currentUser();
// Users with 'access own broken links report' permission can only view their
// own report. Users with the 'access broken links report' permission can
// view the report for any authenticated user.
- return $account->uid && (($user->uid == $account->uid && user_access('access own broken links report')) || user_access('access broken links report'));
+ return $account->id() && (($user->id() == $account->id() && \Drupal::currentUser()->hasPermission('access own broken links report')) || \Drupal::currentUser()->hasPermission('access broken links report'));
}
/**
* TRUE if the current user has the requested permission.
*/
function _linkchecker_user_access_edit_link_settings($link) {
- return user_access('edit link settings') && _linkchecker_link_access($link);
+ return \Drupal::currentUser()->hasPermission('edit link settings') && _linkchecker_link_access($link);
}
/**
* user may be allowed to view.
*/
function _linkchecker_link_node_ids($link, $node_author_account = NULL) {
- static $fields_with_node_links = array();
+ static $fields_with_node_links = [];
// Exit if all node types are disabled or if the user cannot access content,
// there is no need to check further.
$linkchecker_scan_nodetypes = linkchecker_scan_node_types();
- if (empty($linkchecker_scan_nodetypes) || !user_access('access content')) {
- return array();
+ if (empty($linkchecker_scan_nodetypes) || !\Drupal::currentUser()->hasPermission('access content')) {
+ return [];
}
// Get a list of nodes containing the link, using addTag('node_access') to
// allow node access modules to exclude nodes that the current user does not
// have access to view.
if (!empty($node_author_account)) {
- $query = db_select('node', 'n');
+ $query = \Drupal::database()->select('node', 'n');
$query->addTag('node_access');
$query->innerJoin('linkchecker_node', 'ln', 'ln.nid = n.nid');
$query->innerJoin('node_revision', 'r', 'r.vid = n.vid');
$query->condition('ln.lid', $link->lid);
- $query->condition(db_or()
- ->condition('n.uid', $node_author_account->uid)
- ->condition('r.uid', $node_author_account->uid)
- );
- $query->fields('n', array('nid'));
+ $or_condition_group = $query->orConditionGroup()
+ ->condition('n.uid', $node_author_account->id())
+ ->condition('r.uid', $node_author_account->id());
+ $query->condition($or_condition_group);
+
+ $query->fields('n', ['nid']);
}
else {
- $query = db_select('node', 'n');
+ $query = \Drupal::database()->select('node', 'n');
$query->addTag('node_access');
$query->innerJoin('linkchecker_node', 'ln', 'ln.nid = n.nid');
$query->condition('ln.lid', $link->lid);
- $query->fields('n', array('nid'));
+ $query->fields('n', ['nid']);
}
$nodes = $query->execute();
// Check if the current user has access to view the link in each node.
// However, for performance reasons, as soon as we find one node where that
// is the case, stop checking and return the remainder of the list.
- $nids = array();
+ $nids = [];
$access_allowed = FALSE;
foreach ($nodes as $node) {
if ($access_allowed) {
- $nids[] = $node->nid;
+ $nids[] = $node->id();
continue;
}
- $node = node_load($node->nid);
+ $node = Node::load($node->id());
// We must check whether the link is currently part of the node; if not, we
// do not want to return it (and it is not safe to, since we cannot know if
// it contained access restrictions for the current user at the point which
// it was originally extracted by the Link checker module).
- if (!isset($fields_with_node_links[$node->nid])) {
- $fields_with_node_links[$node->nid] = _linkchecker_extract_node_links($node, TRUE);
+ if (!isset($fields_with_node_links[$node->id()])) {
+ $fields_with_node_links[$node->id()] = _linkchecker_extract_node_links($node, TRUE);
}
- if (empty($fields_with_node_links[$node->nid][$link->url])) {
+ if (empty($fields_with_node_links[$node->id()][$link->url])) {
continue;
}
// If the link appears in fields and a field access module is being used,
// we must check that the current user has access to view at least one field
// that contains the link; if they don't, we should not return the node.
- $fields = $fields_with_node_links[$node->nid][$link->url];
- if (module_implements('field_access')) {
- $fields_with_access = array();
+ $fields = $fields_with_node_links[$node->id()][$link->url];
+ if (\Drupal::moduleHandler()->getImplementations('field_access')) {
+ $fields_with_access = [];
- $bundle_instances = field_info_instances('node', $node->type);
+ $bundle_instances = field_info_instances('node', $node->bundle());
foreach ($bundle_instances as $field_name => $field_instance) {
$field = field_info_field($field_name);
// Field types supported by linkchecker.
- $fields_supported = array(
+ $fields_supported = [
'text_with_summary',
'text_long',
'text',
'link_field',
- );
+ ];
// Only check link and text fields, since those are the only types we
// extract links from.
continue;
}
}
- $nids[] = $node->nid;
+ $nids[] = $node->id();
$access_allowed = TRUE;
}
// Exit if comments are disabled or if the user cannot access comments, there
// is no need to check further.
$comment_types = linkchecker_scan_comment_types();
- if (empty($comment_types) || !user_access('access comments')) {
- return array();
+ if (empty($comment_types) || !\Drupal::currentUser()->hasPermission('access comments')) {
+ return [];
}
// Get a list of comments containing the link, using addTag('node_access') to
// allow comment access modules to exclude comments that the current user
// does not have access to view.
if (!empty($comment_author_account)) {
- $query = db_select('comment', 'c');
+ $query = \Drupal::database()->select('comment', 'c');
$query->addMetaData('base_table', 'comment');
$query->addTag('node_access');
$query->innerJoin('linkchecker_comment', 'lc', 'lc.cid = c.cid');
$query->condition('lc.lid', $link->lid);
$query->condition('c.uid', $comment_author_account->uid);
- $query->fields('c', array('cid'));
+ $query->fields('c', ['cid']);
}
else {
- $query = db_select('comment', 'c');
+ $query = \Drupal::database()->select('comment', 'c');
$query->addMetaData('base_table', 'comment');
$query->addTag('node_access');
$query->innerJoin('linkchecker_comment', 'lc', 'lc.cid = c.cid');
$query->condition('lc.lid', $link->lid);
- $query->fields('c', array('cid'));
+ $query->fields('c', ['cid']);
}
$cids = $query->execute()->fetchCol();
* current user is allowed to view.
*/
function _linkchecker_link_block_ids($link) {
+ $user = Drupal::currentUser();
// Exit if blocks are disabled.
- if (!variable_get('linkchecker_scan_blocks', 0)) {
- return array();
+ if (!\Drupal::config('linkchecker.settings')->get('scan_blocks')) {
+ return [];
}
// Get the initial list of block IDs.
- $bids = db_query('SELECT bid FROM {linkchecker_block_custom} WHERE lid = :lid', array(':lid' => $link->lid))->fetchCol();
+ $connection = \Drupal::database();
+ $query = $connection->query('SELECT bid FROM {linkchecker_block_custom} WHERE lid = :lid', [':lid' => $link->lid]);
+ $bids = $query->fetchCol();
// If the user can administer blocks, they're able to see all block content.
- if (user_access('administer blocks')) {
+ if ($user->hasPermission('administer blocks')) {
return $bids;
}
// Otherwise, only return blocks that this user (or anonymous users) have
// access to.
- global $user;
- $rids = array_keys($user->roles);
- $rids[] = DRUPAL_ANONYMOUS_RID;
+ $rids = array_keys($user->getRoles());
+ $rids[] = AccountInterface::ANONYMOUS_ROLE;
- $query = db_select('block', 'b');
+ $query = \Drupal::database()->select('block', 'b');
$query->leftJoin('block_role', 'r', 'b.module = r.module AND b.delta = r.delta');
$query->condition('b.module', 'block');
- $query->condition(db_or()
+ $or_condition_group = $query->orConditionGroup()
->condition('r.rid', $rids, 'IN')
- ->isNull('r.rid')
- );
- $query->fields('b', array('delta'));
+ ->isNull('r.rid');
+ $query->condition($or_condition_group);
+ $query->fields('b', ['delta']);
$query->distinct();
$allowed_bids = $query->execute()->fetchCol();
\Drupal::state()->set('linkchecker.cleanup_links_last', REQUEST_TIME);
}
+ /* httprl module does not exists yet for D8
// Run link checker in a new process, independent of cron.
if (\Drupal::moduleHandler()->moduleExists('httprl') && \Drupal::config('linkchecker.settings')->get('check.library') == 'httprl') {
// Setup callback options array; call _linkchecker_check_links() in the
// background.
- $callback_options = array(array('function' => '_linkchecker_check_links'));
+ $callback_options = [['function' => '_linkchecker_check_links']];
// Queue up the request.
httprl_queue_background_callback($callback_options);
// Execute request.
// Exit here so we don't call _linkchecker_check_links() in this process.
return;
- }
+ }*/
// Run the link checks the normal way.
_linkchecker_check_links();
}
// Make sure this is the only process trying to run this function.
$lock = \Drupal::lock();
if ($lock->acquire(__FUNCTION__, $max_execution_time)) {
- linkchecker_watchdog_log('linkchecker', 'Attempted to re-run link checks while they are already running.', array(), WATCHDOG_WARNING);
- return FALSE;
- }
- $has_httprl = (\Drupal::moduleHandler()->moduleExists('httprl') && $config->get('check.library') == 'httprl');
+ // httprl module does not exists yet for D8
+ // $has_httprl = (\Drupal::moduleHandler()->moduleExists('httprl') && $config->get('check.library') == 'httprl');
+ $has_httprl = FALSE;
- // Do not confuse admins with a setting of maximum checkable links per cron
- // run and guess that 2 links can be checked per second with 1 thread, what is
- // nevertheless uncommon. The max_execution_time can be used to calculate
- // a useful value that is higher, but not totally out of scope and limits the
- // query result set to a reasonable size.
- $linkchecker_check_connections_max = $config->get('check.connections_max');
- $check_links_max_per_cron_run = ($has_httprl) ? ($linkchecker_check_connections_max * $max_execution_time) : $max_execution_time;
+ // Do not confuse admins with a setting of maximum checkable links per cron
+ // run and guess that 2 links can be checked per second with 1 thread, what is
+ // nevertheless uncommon. The max_execution_time can be used to calculate
+ // a useful value that is higher, but not totally out of scope and limits the
+ // query result set to a reasonable size.
+ $linkchecker_check_connections_max = $config->get('check.connections_max');
- $linkchecker_check_links_interval = $config->get('check.interval');
- $linkchecker_check_useragent = $config->get('check.useragent');
+ $check_links_max_per_cron_run = ($has_httprl) ? ($linkchecker_check_connections_max * $max_execution_time) : $max_execution_time;
- // Connection limit can be overridden via settings.php. Two connections is the
- // limit defined in RFC http://www.ietf.org/rfc/rfc2616.txt. Modern browsers
- // are typically using 6-8 connections and no more. Never use more and keep
- // in mind that you can overload other people servers.
- $linkchecker_check_domain_connections = $config->get('check.connections_max_per_domain');
+ $linkchecker_check_links_interval = $config->get('check.interval');
+ $linkchecker_check_useragent = $config->get('check.useragent');
- // Get URLs for checking.
- $links = db_query_range('SELECT * FROM {linkchecker_link} WHERE last_checked < :last_checked AND status = :status ORDER BY last_checked, lid ASC', 0, $check_links_max_per_cron_run, [':last_checked' => REQUEST_TIME - $linkchecker_check_links_interval, ':status' => 1]);
- $links_remaining = $links->rowCount();
+ // Connection limit can be overridden via settings.php. Two connections is the
+ // limit defined in RFC http://www.ietf.org/rfc/rfc2616.txt. Modern browsers
+ // are typically using 6-8 connections and no more. Never use more and keep
+ // in mind that you can overload other people servers.
+ $linkchecker_check_domain_connections = $config->get('check.connections_max_per_domain');
- foreach ($links as $link) {
- $headers = [];
- $headers['User-Agent'] = $linkchecker_check_useragent;
+ // Get URLs for checking.
+ $connection = \Drupal::database();
+ $links = $connection->queryRange('SELECT * FROM {linkchecker_link} WHERE last_checked < :last_checked AND status = :status ORDER BY last_checked, lid ASC', 0, $check_links_max_per_cron_run, [':last_checked' => REQUEST_TIME - $linkchecker_check_links_interval, ':status' => 1]);
+ $links_remaining = Database::RETURN_AFFECTED;
- $uri = @parse_url($link->url);
+ foreach ($links as $link) {
+ $headers = [];
+ $headers['User-Agent'] = $linkchecker_check_useragent;
- // URL contains a fragment.
- if (in_array($link->method, ['HEAD', 'GET']) && !empty($uri['fragment'])) {
- // We need the full content and not only the HEAD.
- $link->method = 'GET';
- // Request text content only (like Firefox/Chrome).
- $headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
- }
- elseif ($link->method == 'GET') {
- // Range: Only request the first 1024 bytes from remote server. This is
- // required to prevent timeouts on URLs that are large downloads.
- $headers['Range'] = 'bytes=0-1024';
- }
+ $uri = @parse_url($link->url);
- // Add in the headers.
- $options = [
- 'headers' => $headers,
- 'method' => $link->method,
- 'max_redirects' => 0,
- ];
+ // URL contains a fragment.
+ if (in_array($link->method, ['HEAD', 'GET']) && !empty($uri['fragment'])) {
+ // We need the full content and not only the HEAD.
+ $link->method = 'GET';
+ // Request text content only (like Firefox/Chrome).
+ $headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
+ }
+ elseif ($link->method == 'GET') {
+ // Range: Only request the first 1024 bytes from remote server. This is
+ // required to prevent timeouts on URLs that are large downloads.
+ $headers['Range'] = 'bytes=0-1024';
+ }
- if ($has_httprl) {
- // Define the callback and add the $link object to it.
- // Notes:
- // - 'global_timeout' does not require a timer_read('page'), as this job
- // runs in a new process, independent of cron.
- $options += [
- 'global_connections' => $linkchecker_check_connections_max,
- 'global_timeout' => $max_execution_time - 30,
- 'domain_connections' => $linkchecker_check_domain_connections,
- 'callback' => [
- [
- 'function' => '_linkchecker_status_handling',
- ],
- $link, // This need to be passed or it's not send back to _linkchecker_status_handling()
- ],
+ // Add in the headers.
+ $options = [
+ 'headers' => $headers,
+ 'method' => $link->method,
+ 'max_redirects' => 0,
];
- // Queue up the requests.
- httprl_request($link->url, $options);
- $links_remaining--;
- // After all links are queued, run the url checks.
- if ($links_remaining == 0) {
- httprl_send_request();
- }
- }
- else {
- // Drupal core.
- try {
- // @fixme: Object is totally different in D8.
- $response = \Drupal::httpClient()->request($link->method, $link->url, $options);
- //$response = drupal_http_request($link->url, $options);
-
- // @fixme
- // Add 'redirect_code' property to core response object for consistency
- // with HTTPRL object.
- //if ($response->code == 301 && !isset($response->redirect_code)) {
- // $response->redirect_code = $response->code;
- //}
- // Add 'uri' property to core response object for 'fragment' check and
- // consistency with HTTPRL object.
- //$response->uri = $uri;
-
- _linkchecker_status_handling($response, $link);
-
- if ((timer_read('page') / 1000) > ($max_execution_time / 2)) {
- // Stop once we have used over half of the maximum execution time.
- break;
+ if ($has_httprl) {
+ // Define the callback and add the $link object to it.
+ // Notes:
+ // - 'global_timeout' does not require a timer_read('page'), as this job
+ // runs in a new process, independent of cron.
+ $options += [
+ 'global_connections' => $linkchecker_check_connections_max,
+ 'global_timeout' => $max_execution_time - 30,
+ 'domain_connections' => $linkchecker_check_domain_connections,
+ 'callback' => [
+ [
+ 'function' => '_linkchecker_status_handling',
+ ],
+ $link, // This need to be passed or it's not send back to _linkchecker_status_handling()
+ ],
+ ];
+ // Queue up the requests.
+ httprl_request($link->url, $options);
+ $links_remaining--;
+
+ // After all links are queued, run the url checks.
+ if ($links_remaining == 0) {
+ httprl_send_request();
}
}
- catch (RequestException $exception) {
- watchdog_exception('linkchecker', $exception);
+ else {
+ // Drupal core.
+ try {
+ // @fixme: Object is totally different in D8.
+
+ $response = \Drupal::httpClient()->request($link->method, $link->url, $options);
+
+ // @fixme
+ // Add 'redirect_code' property to core response object for consistency
+ // with HTTPRL object.
+ // if ($response->code == 301 && !isset($response->redirect_code)) {
+ // $response->redirect_code = $response->code;
+ // }
+ // Add 'uri' property to core response object for 'fragment' check and
+ // consistency with HTTPRL object.
+ // $response->uri = $uri;
+
+ _linkchecker_status_handling($response, $link);
+
+ if ((Timer::read('page') / 1000) > ($max_execution_time / 2)) {
+ // Stop once we have used over half of the maximum execution time.
+ break;
+ }
+ }
+ catch (ClientException $e) {
+ $response = $e->getResponse();
+ _linkchecker_status_handling($response, $link);
+ if ((Timer::read('page') / 1000) > ($max_execution_time / 2)) {
+ // Stop for loop.
+ break;
+ }
+
+ }
}
}
- }
- // Release the lock.
- $lock->release(__FUNCTION__);
- linkchecker_watchdog_log('linkchecker', 'Link checks completed.', array(), WATCHDOG_INFO);
- linkchecker_watchdog_log('linkchecker', 'Memory usage: @memory_get_usage, Peak memory usage: @memory_get_peak_usage.', array('@memory_get_peak_usage' => format_size(memory_get_peak_usage()), '@memory_get_usage' => format_size(memory_get_usage())), WATCHDOG_DEBUG);
- return TRUE;
+ // Release the lock.
+ $lock->release(__FUNCTION__);
+ linkchecker_watchdog_log('linkchecker', 'Link checks completed.', [], RfcLogLevel::INFO);
+ linkchecker_watchdog_log('linkchecker', 'Memory usage: @memory_get_usage, Peak memory usage: @memory_get_peak_usage.', ['@memory_get_peak_usage' => format_size(memory_get_peak_usage()), '@memory_get_usage' => format_size(memory_get_usage())], RfcLogLevel::DEBUG);
+ return TRUE;
+
+ }
+ else {
+ linkchecker_watchdog_log('linkchecker', 'Attempted to re-run link checks while they are already running.', [], RfcLogLevel::WARNING);
+ return FALSE;
+ }
}
/**
*/
function _linkchecker_status_handling(&$response, $link) {
$config = \Drupal::config('linkchecker.settings');
- $ignore_response_codes = preg_split('/(\r\n?|\n)/', variable_get('linkchecker_ignore_response_codes', "200\n206\n302\n304\n401\n403"));
+ $ignore_response_codes = preg_split('/(\r\n?|\n)/', \Drupal::config('linkchecker.settings')->get('error.ignore_response_codes'));
// - Prevent E_ALL warnings in DB updates for non-existing $response->error.
// - @todo drupal_http_request() may not provide an UTF8 encoded error message
if (!isset($response->status_message)) {
$response->status_message = '';
}
- $response->error = trim(drupal_convert_to_utf8($response->error, 'ISO-8859-1'));
- $response->status_message = trim(drupal_convert_to_utf8($response->status_message, 'ISO-8859-1'));
+ $response->error = trim(Unicode::convertToUtf8($response->error, 'ISO-8859-1'));
+ $response->status_message = trim(Unicode::convertToUtf8($response->status_message, 'ISO-8859-1'));
// Destination anchors in HTML documents may be specified either by:
// - the A element (naming it with the name attribute)
// - and must not contain '/' or ',' as this are not normal anchors.
// - and '#top' is a reserved fragment that must not exist in a page.
// See http://www.w3.org/TR/html401/struct/links.html
+
+ $response->code = $response->getStatusCode();
if ($response->code == 200
- && !empty($response->data)
- && !empty($response->headers['content-type'])
- && !empty($response->uri['fragment'])
- && preg_match('/=|\/|,/', $response->uri['fragment']) == FALSE
- && !in_array($response->uri['fragment'], array('#top'))
- && in_array($response->headers['content-type'], array('text/html', 'application/xhtml+xml', 'application/xml'))
- && !preg_match('/(\s[^>]*(name|id)(\s+)?=(\s+)?["\'])(' . preg_quote($response->uri['fragment'], '/') . ')(["\'][^>]*>)/i', $response->data)
+ && !empty($response->getBody())
+ && !empty($response->getHeader('Content-Type'))
+ && !empty($response->getHeader('Link'))
+ && preg_match('/=|\/|,/', $response->getHeader('Link')[1]) == FALSE
+ && !in_array($response->getHeader('Link')[1], ['#top'])
+ && in_array($response->getHeader('Content-Type'), ['text/html', 'application/xhtml+xml', 'application/xml'])
+ && !preg_match('/(\s[^>]*(name|id)(\s+)?=(\s+)?["\'])(' . preg_quote($response->getHeader('Link')[1], '/') . ')(["\'][^>]*>)/i', $response->getBody())
) {
// Override status code 200 with status code 404 so it can be handled with
// default status code 404 logic and custom error text.
case -2: // HTTPRL: maximum allowed redirects exhausted.
case 301:
// Remote site send status code 301 and link needs an update.
- db_update('linkchecker_link')
+ \Drupal::database()->update('linkchecker_link')
->condition('lid', $link->lid)
- ->fields(array(
+ ->fields([
'code' => $response->redirect_code,
'error' => $response->status_message,
'fail_count' => 0,
'last_checked' => time(),
- ))
+ ])
->expression('fail_count', 'fail_count + 1')
->execute();
// a new link. The remote site owner was so kind to provide us the new
// link and if we trust this change we are able to replace the old link
// with the new one without any hand work.
- $auto_repair_301 = variable_get('linkchecker_action_status_code_301', 0);
- if ($auto_repair_301 && $auto_repair_301 <= ($link->fail_count + 1) && valid_url($response->redirect_url, TRUE)) {
+ $auto_repair_301 = \Drupal::config('linkchecker.settings')->get('error.action_status_code_301');
+ if ($auto_repair_301 && $auto_repair_301 <= ($link->fail_count + 1) && UrlHelper::isValid($response->redirect_url, TRUE)) {
// Switch anonymous user to an admin.
$accountSwitcher = Drupal::service('account_switcher');
- $accountSwitcher->switchTo(new UserSession(array('uid' => user_load_by_name($config->get('error.impersonate_account')))));
+ $accountSwitcher->switchTo(new UserSession(['uid' => user_load_by_name($config->get('error.impersonate_account'))]));
// NODES: Autorepair all nodes having this outdated link.
- $result = db_query('SELECT nid FROM {linkchecker_node} WHERE lid = :lid', array(':lid' => $link->lid));
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT nid FROM {linkchecker_node} WHERE lid = :lid', [':lid' => $link->lid]);
+
foreach ($result as $row) {
- // Explicitly don't use node_load_multiple() or the module may run
+ // Explicitly don't use Node::load_multiple() or the module may run
// into issues like http://drupal.org/node/1210606. With this logic
// nodes can be updated until an out of memory occurs and further
// updates will be made on the remaining nodes only.
- $node = node_load($row->nid);
+ $node = Node::load($row->nid);
// Has the node object loaded successfully?
if (is_object($node)) {
$node_original = clone $node;
- $node = _linkchecker_replace_fields('node', $node->type, $node, $link->url, $response->redirect_url);
+ $node = _linkchecker_replace_fields('node', $node->bundle(), $node, $link->url, $response->redirect_url);
if ($node_original != $node) {
// Always use the default revision setting. For more information,
// see node_object_prepare().
- $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
+ $node_options = \Drupal::config('linkchecker.settings')->get('node_options_' . $node->bundle());
$node->revision = in_array('revision', $node_options);
// Generate a log message for the node_revisions table, visible on
// the node's revisions tab.
- $node->log = t('Changed permanently moved link in %node from %src to %dst.', array('%node' => url('node/' . $node->nid), '%src' => $link->url, '%dst' => $response->redirect_url));
+ $node->log = t('Changed permanently moved link in %node from %src to %dst.',
+ [
+ '%node' => url('node/' . $node->id()),
+ '%src' => $link->url,
+ '%dst' => $response->redirect_url
+ ]
+ );
// Save changed node and update the node link list.
- node_save($node);
- linkchecker_watchdog_log('linkchecker', 'Changed permanently moved link in %node from %src to %dst.', array('%node' => url('node/' . $node->nid), '%src' => $link->url, '%dst' => $response->redirect_url), WATCHDOG_INFO);
+ $node->save();
+ linkchecker_watchdog_log('linkchecker', 'Changed permanently moved link in %node from %src to %dst.',
+ [
+ '%node' => url('node/' . $node->id()),
+ '%src' => $link->url,
+ '%dst' => $response->redirect_url
+ ],
+ RfcLogLevel::INFO
+ );
}
else {
- linkchecker_watchdog_log('linkchecker', 'Link update in node failed. Permanently moved link %src not found in node %node. Manual fix required.', array('%node' => url('node/' . $row->nid), '%src' => $link->url), WATCHDOG_WARNING);
+ linkchecker_watchdog_log('linkchecker', 'Link update in node failed. Permanently moved link %src not found in node %node. Manual fix required.',
+ ['%node' => url('node/' . $row->nid), '%src' => $link->url],
+ RfcLogLevel::WARNING
+ );
}
}
else {
- linkchecker_watchdog_log('linkchecker', 'Loading node %node for update failed. Manual fix required.', array('%node' => $row->nid), WATCHDOG_ERROR);
+ linkchecker_watchdog_log('linkchecker', 'Loading node %node for update failed. Manual fix required.',
+ ['%node' => $row->nid],
+ WATCHDOG_ERROR
+ );
}
}
// COMMENTS: Autorepair all comments having this outdated link.
- $result = db_query('SELECT cid FROM {linkchecker_comment} WHERE lid = :lid', array(':lid' => $link->lid));
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT cid FROM {linkchecker_comment} WHERE lid = :lid', [':lid' => $link->lid]);
+
foreach ($result as $row) {
// Explicitly don't use comment_load_multiple() or the module may run
// into issues like http://drupal.org/node/1210606. With this logic
// Save changed comment and update the comment link list.
if ($comment_original != $comment) {
comment_save($comment);
- linkchecker_watchdog_log('linkchecker', 'Changed permanently moved link in comment %comment from %src to %dst.', array('%comment' => $comment->cid, '%src' => $link->url, '%dst' => $response->redirect_url), WATCHDOG_INFO);
+ linkchecker_watchdog_log('linkchecker', 'Changed permanently moved link in comment %comment from %src to %dst.', ['%comment' => $comment->cid, '%src' => $link->url, '%dst' => $response->redirect_url], RfcLogLevel::INFO);
}
else {
- linkchecker_watchdog_log('linkchecker', 'Link update in comment failed. Permanently moved link %src not found in comment %comment. Manual fix required.', array('%comment' => $comment->cid, '%src' => $link->url), WATCHDOG_WARNING);
+ linkchecker_watchdog_log('linkchecker', 'Link update in comment failed. Permanently moved link %src not found in comment %comment. Manual fix required.', ['%comment' => $comment->cid, '%src' => $link->url], RfcLogLevel::WARNING);
}
}
else {
- linkchecker_watchdog_log('linkchecker', 'Loading comment %comment for update failed. Manual fix required.', array('%comment' => $comment->cid), WATCHDOG_ERROR);
+ linkchecker_watchdog_log('linkchecker', 'Loading comment %comment for update failed. Manual fix required.', ['%comment' => $comment->cid], WATCHDOG_ERROR);
}
}
// CUSTOM BLOCKS: Autorepair all custom blocks having this outdated
// link.
- $result = db_query('SELECT bid FROM {linkchecker_block_custom} WHERE lid = :lid', array(':lid' => $link->lid));
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT bid FROM {linkchecker_block_custom} WHERE lid = :lid', [':lid' => $link->lid]);
foreach ($result as $row) {
$block_custom = linkchecker_block_custom_block_get($row->bid);
// There is no hook that fires on block_custom_block_save(),
// therefore do link extraction programmatically.
_linkchecker_add_block_custom_links($block_custom, $block_custom->delta);
- linkchecker_watchdog_log('linkchecker', 'Changed permanently moved link in custom block %bid from %src to %dst.', array('%bid' => $block_custom->delta, '%src' => $link->url, '%dst' => $response->redirect_url), WATCHDOG_INFO);
+ linkchecker_watchdog_log('linkchecker', 'Changed permanently moved link in custom block %bid from %src to %dst.', ['%bid' => $block_custom->delta, '%src' => $link->url, '%dst' => $response->redirect_url], RfcLogLevel::INFO);
}
else {
- linkchecker_watchdog_log('linkchecker', 'Link update in block failed. Permanently moved link %src not found in block %bid. Manual fix required.', array('%bid' => $block_custom->delta, '%src' => $link->url), WATCHDOG_WARNING);
+ linkchecker_watchdog_log('linkchecker', 'Link update in block failed. Permanently moved link %src not found in block %bid. Manual fix required.', ['%bid' => $block_custom->delta, '%src' => $link->url], RfcLogLevel::WARNING);
}
}
else {
- linkchecker_watchdog_log('linkchecker', 'Loading block %bid for update failed. Manual fix required.', array('%bid' => $block_custom->delta), WATCHDOG_ERROR);
+ linkchecker_watchdog_log('linkchecker', 'Loading block %bid for update failed. Manual fix required.', ['%bid' => $block_custom->delta], RfcLogLevel::ERROR);
}
}
$accountSwitcher->switchBack();
}
else {
- linkchecker_watchdog_log('linkchecker', 'Link %link has changed and needs to be updated.', array('%link' => $link->url), WATCHDOG_NOTICE, l(t('Broken links'), 'admin/reports/linkchecker'));
+ linkchecker_watchdog_log('linkchecker', 'Link %link has changed and needs to be updated.', ['%link' => $link->url], RfcLogLevel::NOTICE, l(t('Broken links'), 'admin/reports/linkchecker'));
}
break;
case 404:
- db_update('linkchecker_link')
+ \Drupal::database()->update('linkchecker_link')
->condition('lid', $link->lid)
- ->fields(array(
+ ->fields([
'code' => $response->code,
'error' => $response->error,
'fail_count' => 0,
'last_checked' => time(),
- ))
+ ])
->expression('fail_count', 'fail_count + 1')
->execute();
- linkchecker_watchdog_log('linkchecker', 'Broken link %link has been found.', array('%link' => $link->url), WATCHDOG_NOTICE, l(t('Broken links'), 'admin/reports/linkchecker'));
+ $linkchecker_report_url = Url::fromRoute('linkchecker.admin_report_page', ['attributes' => ['target' => '_blank']]);
+ linkchecker_watchdog_log('linkchecker', 'Broken link %link has been found.', ['%link' => $link->url], RfcLogLevel::NOTICE, Drupal::l(t('Broken links'), $linkchecker_report_url));
// If unpublishing limit is reached, unpublish all nodes having this link.
- $linkchecker_action_status_code_404 = variable_get('linkchecker_action_status_code_404', 0);
+ $linkchecker_action_status_code_404 = \Drupal::config('linkchecker.settings')->get('error.action_status_code_404');
if ($linkchecker_action_status_code_404 && $linkchecker_action_status_code_404 <= ($link->fail_count + 1)) {
// Switch anonymous user to an admin.
$accountSwitcher = Drupal::service('account_switcher');
- $accountSwitcher->switchTo(new UserSession(array('uid' => user_load_by_name($config->get('error.impersonate_account')))));
+ $accountSwitcher->switchTo(new UserSession(['uid' => user_load_by_name($config->get('error.impersonate_account'))]));
_linkchecker_unpublish_nodes($link->lid);
$accountSwitcher->switchBack();
}
case 405:
// - 405: Special error handling if method is not allowed. Switch link
// checking to GET method and try again.
- db_update('linkchecker_link')
+ \Drupal::database()->update('linkchecker_link')
->condition('lid', $link->lid)
- ->fields(array(
+ ->fields([
'method' => 'GET',
'code' => $response->code,
'error' => $response->error,
'fail_count' => 0,
'last_checked' => time(),
- ))
+ ])
->expression('fail_count', 'fail_count + 1')
->execute();
- linkchecker_watchdog_log('linkchecker', 'Method HEAD is not allowed for link %link. Method has been changed to GET.', array('%link' => $link->url), WATCHDOG_INFO, l(t('Broken links'), 'admin/reports/linkchecker'));
+ $linkchecker_report_url = Url::fromRoute('linkchecker.admin_report_page', ['attributes' => ['target' => '_blank']]);
+ linkchecker_watchdog_log('linkchecker', 'Method HEAD is not allowed for link %link. Method has been changed to GET.', ['%link' => $link->url], RfcLogLevel::NOTICE, Drupal::l(t('Broken links'), $linkchecker_report_url));
break;
case 500:
// - 500: Like WGET, try with GET on "500 Internal server error".
// - If GET also fails with status code 500, than the link is broken.
if ($link->method == 'GET' && $response->code == 500) {
- db_update('linkchecker_link')
- ->condition('lid', $link->lid)
- ->fields(array(
- 'code' => $response->code,
- 'error' => $response->error,
- 'fail_count' => 0,
- 'last_checked' => time(),
- ))
- ->expression('fail_count', 'fail_count + 1')
- ->execute();
+ \Drupal::database()->update('linkchecker_link')
+ ->condition('lid', $link->lid)
+ ->fields([
+ 'code' => $response->code,
+ 'error' => $response->error,
+ 'fail_count' => 0,
+ 'last_checked' => time(),
+ ])
+ ->expression('fail_count', 'fail_count + 1')
+ ->execute();
- linkchecker_watchdog_log('linkchecker', 'Broken link %link has been found.', array('%link' => $link->url), WATCHDOG_NOTICE, l(t('Broken links'), 'admin/reports/linkchecker'));
+ $linkchecker_report_url = Url::fromRoute('linkchecker.admin_report_page', ['attributes' => ['target' => '_blank']]);
+ linkchecker_watchdog_log('linkchecker', 'Broken link %link has been found.', ['%link' => $link->url], RfcLogLevel::NOTICE, Drupal::l(t('Broken links'), $linkchecker_report_url));
}
else {
- db_update('linkchecker_link')
- ->condition('lid', $link->lid)
- ->fields(array(
- 'method' => 'GET',
- 'code' => $response->code,
- 'error' => $response->error,
- 'fail_count' => 0,
- 'last_checked' => time(),
- ))
- ->expression('fail_count', 'fail_count + 1')
- ->execute();
+ \Drupal::database()->update('linkchecker_link')
+ ->condition('lid', $link->lid)
+ ->fields([
+ 'method' => 'GET',
+ 'code' => $response->code,
+ 'error' => $response->error,
+ 'fail_count' => 0,
+ 'last_checked' => time(),
+ ])
+ ->expression('fail_count', 'fail_count + 1')
+ ->execute();
+
+ $linkchecker_report_url = Url::fromRoute('linkchecker.admin_report_page', ['attributes' => ['target' => '_blank']]);
+ linkchecker_watchdog_log('linkchecker', 'Internal server error for link %link. Method has been changed to GET.', ['%link' => $link->url], RfcLogLevel::NOTICE, Drupal::l(t('Broken links'), $linkchecker_report_url));
- linkchecker_watchdog_log('linkchecker', 'Internal server error for link %link. Method has been changed to GET.', array('%link' => $link->url), WATCHDOG_INFO, l(t('Broken links'), 'admin/reports/linkchecker'));
}
break;
default:
// Don't treat ignored response codes as errors.
if (in_array($response->code, $ignore_response_codes)) {
- db_update('linkchecker_link')
+ \Drupal::database()->update('linkchecker_link')
->condition('lid', $link->lid)
- ->fields(array(
+ ->fields([
'code' => $response->code,
'error' => $response->error,
'fail_count' => 0,
'last_checked' => time(),
- ))
+ ])
->execute();
- // linkchecker_watchdog_log('linkchecker', 'Unhandled link error %link has been found.', array('%link' => $link->url), WATCHDOG_ERROR, l(t('Broken links'), 'admin/reports/linkchecker'));
+ // linkchecker_watchdog_log('linkchecker', 'Unhandled link error %link has been found.', array('%link' => $link->url), RfcLogLevel::ERROR, l(t('Broken links'), 'admin/reports/linkchecker'));
}
else {
- db_update('linkchecker_link')
+ \Drupal::database()->update('linkchecker_link')
->condition('lid', $link->lid)
- ->fields(array(
+ ->fields([
'code' => $response->code,
'error' => $response->error,
'fail_count' => 0,
'last_checked' => time(),
- ))
+ ])
->expression('fail_count', 'fail_count + 1')
->execute();
- // linkchecker_watchdog_log('linkchecker', 'Unhandled link error %link has been found.', array('%link' => $link->url), WATCHDOG_ERROR, l(t('Broken links'), 'admin/reports/linkchecker'));
+ // linkchecker_watchdog_log('linkchecker', 'Unhandled link error %link has been found.', array('%link' => $link->url), RfcLogLevel::ERROR, l(t('Broken links'), 'admin/reports/linkchecker'));
}
}
* @fixme: remove after migration
* Implements hook_node_type_delete().
*/
+
function linkchecker_node_type_delete($info) {
- variable_del('linkchecker_scan_node_' . $info->type);
- variable_del('linkchecker_scan_comment_' . $info->type);
+ // @todo: Refactor this under D8.
+ //variable_del('linkchecker_scan_node_' . $info->type);
+ //variable_del('linkchecker_scan_comment_' . $info->type);
+ //Drupal::configFactory()->getEditable('linkchecker_scan_node_' . $info->type)->delete();
+ //Drupal::configFactory()->getEditable('linkchecker_scan_comment_' . $info->type)->delete();
}
/**
* Implements hook_node_prepare().
*/
-function linkchecker_node_prepare($node) {
+function linkchecker_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
// Node edit tab is viewed.
- if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'edit' && isset($node->nid)) {
+ // @todo: Review if this is the correct upgrade path to D8
+ // if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'edit' && isset($node->nid)) {
+ if (!$node->isNew()) {
// Show a message on node edit page if a link check failed once or more.
- $ignore_response_codes = preg_split('/(\r\n?|\n)/', variable_get('linkchecker_ignore_response_codes', "200\n206\n302\n304\n401\n403"));
- $links = db_query('SELECT ll.* FROM {linkchecker_node} ln INNER JOIN {linkchecker_link} ll ON ln.lid = ll.lid WHERE ln.nid = :nid AND ll.fail_count > :fail_count AND ll.status = :status AND ll.code NOT IN (:codes)', array(':nid' => $node->nid, ':fail_count' => 0, ':status' => 1, ':codes' => $ignore_response_codes));
+ $ignore_response_codes = preg_split('/(\r\n?|\n)/', \Drupal::config('linkchecker.settings')->get('error.ignore_response_codes'));
+ $connection = \Drupal::database();
+ $links = $connection->query('SELECT ll.* FROM {linkchecker_node} ln INNER JOIN {linkchecker_link} ll ON ln.lid = ll.lid WHERE ln.nid = :nid AND ll.fail_count > :fail_count AND ll.status = :status AND ll.code NOT IN (:codes[])', [':nid' => $node->id(), ':fail_count' => 0, ':status' => 1, ':codes[]' => $ignore_response_codes]);
foreach ($links as $link) {
if (_linkchecker_link_access($link)) {
- drupal_set_message(format_plural($link->fail_count, 'Link check of <a href="@url">@url</a> failed once (status code: @code).', 'Link check of <a href="@url">@url</a> failed @count times (status code: @code).', array('@url' => $link->url, '@code' => $link->code)), 'warning', FALSE);
+ drupal_set_message(\Drupal::translation()->formatPlural($link->fail_count, 'Link check of <a href="@url">@url</a> failed once (status code: @code).', 'Link check of <a href="@url">@url</a> failed @count times (status code: @code).', ['@url' => $link->url, '@code' => $link->code]), 'warning', FALSE);
}
}
}
* Implements hook_node_delete().
*/
function linkchecker_node_delete($node) {
- _linkchecker_delete_node_links($node->nid);
+ _linkchecker_delete_node_links($node->id());
}
/**
// Every moderation module saving a forward revision needs to exit here.
// Please see _linkchecker_isdefaultrevision() for more details.
// @todo: Refactor this workaround under D8.
- if (!_linkchecker_isdefaultrevision($node)) {
+ if (!$node->isDefaultRevision()) {
return;
}
+ // @fixme
+ //if (!_linkchecker_isdefaultrevision($node)) {
+ // return;
+ // }
+ $node_type = NodeType::load($node->bundle());
// The node is going to be published.
- if (variable_get('linkchecker_scan_node_' . $node->type, FALSE) && $node->status == NODE_PUBLISHED) {
+ if ($node_type->getThirdPartySetting('linkchecker', 'scan_node', FALSE) && $node->isPublished()) {
_linkchecker_add_node_links($node);
}
}
// Every moderation module saving a forward revision needs to exit here.
// Please see _linkchecker_isdefaultrevision() for more details.
// @todo: Refactor this workaround under D8.
- if (!_linkchecker_isdefaultrevision($node)) {
+ //if (!_linkchecker_isdefaultrevision($node)) {
+ // return;
+ //}
+ if (!$node->isDefaultRevision()) {
return;
}
// The node is going to be published.
- if (variable_get('linkchecker_scan_node_' . $node->type, FALSE) && $node->status == NODE_PUBLISHED) {
+ $node_type = NodeType::load($node->bundle());
+ if ($node_type->getThirdPartySetting('linkchecker', 'scan_node', FALSE) && $node->isPublished()) {
_linkchecker_add_node_links($node);
}
else {
*/
function linkchecker_comment_insert($comment) {
// The comment is going to be published.
- $node_type = db_query('SELECT type FROM {node} WHERE nid = :nid', array(':nid' => $comment->nid))->fetchField();
- if (variable_get('linkchecker_scan_comment_' . $node_type, FALSE) && $comment->status == COMMENT_PUBLISHED) {
+ $connection = \Drupal::database();
+ $node_type = $connection->query('SELECT type FROM {node} WHERE nid = :nid', [':nid' => $comment->getCommentedEntityId()])->fetchField();
+ if (\Drupal::config('linkchecker.settings')->get('linkchecker_scan_comment_' . $node_type) && $comment->getStatus() == COMMENT_PUBLISHED) {
_linkchecker_add_comment_links($comment);
}
}
*/
function linkchecker_comment_update($comment) {
// The node is going to be published.
- $node_type = db_query('SELECT type FROM {node} WHERE nid = :nid', array(':nid' => $comment->nid))->fetchField();
- if (variable_get('linkchecker_scan_comment_' . $node_type, FALSE) && $comment->status == COMMENT_PUBLISHED) {
+ $connection = \Drupal::database();
+ $node_type = $connection->query('SELECT type FROM {node} WHERE nid = :nid', [':nid' => $comment->getCommentedEntityId()])->fetchField();
+ if (\Drupal::config('linkchecker.settings')->get('linkchecker_scan_comment_' . $node_type) && $comment->getStatus() == COMMENT_PUBLISHED) {
_linkchecker_add_comment_links($comment);
}
else {
$form['#submit'][] = 'linkchecker_block_custom_add_form_submit';
break;
+ // @todo block_admin_configure has been removed in D8
case 'block_admin_configure':
// When displaying the form, show the broken links warning.
+ // @ $form_state is an object in D7
if (empty($form_state['input']) && is_numeric(arg(5))) {
// Show a message on custom block edit page if a link check failed once
// or more often.
$ignore_response_codes = preg_split('/(\r\n?|\n)/', \Drupal::config('linkchecker.settings')->get('error.ignore_response_codes'));
- $links = db_query('SELECT ll.* FROM {linkchecker_block_custom} lb INNER JOIN {linkchecker_link} ll ON lb.lid = ll.lid WHERE lb.bid = :bid AND ll.fail_count > :fail_count AND ll.status = :status AND ll.code NOT IN (:codes)', array(':bid' => arg(5), ':fail_count' => 0, ':status' => 1, ':codes' => $ignore_response_codes));
+ $connection = \Drupal::database();
+ $links = $connection->query('SELECT ll.* FROM {linkchecker_block_custom} lb INNER JOIN {linkchecker_link} ll ON lb.lid = ll.lid WHERE lb.bid = :bid AND ll.fail_count > :fail_count AND ll.status = :status AND ll.code NOT IN (:codes[])', [':bid' => arg(5), ':fail_count' => 0, ':status' => 1, ':codes[]' => $ignore_response_codes]);
foreach ($links as $link) {
if (_linkchecker_link_access($link)) {
- drupal_set_message(format_plural($link->fail_count, 'Link check of <a href=":url">:url</a> failed once (status code: @code).', 'Link check of <a href=":url">:url</a> failed @count times (status code: @code).', array(':url' => $link->url, '@code' => $link->code)), 'warning', FALSE);
+ drupal_set_message(\Drupal::translation()->formatPlural($link->fail_count, 'Link check of <a href=":url">:url</a> failed once (status code: @code).', 'Link check of <a href=":url">:url</a> failed @count times (status code: @code).', [':url' => $link->url, '@code' => $link->code]), 'warning', FALSE);
}
}
}
if (!$form['linkchecker']['linkchecker_scan_node']['#default_value'] && $form_state->getValue('linkchecker_scan_node')) {
// We need to scan this node-type now.
module_load_include('inc', 'linkchecker', 'linkchecker.batch');
- batch_set(_linkchecker_batch_import_nodes(array($node_type)));
+ batch_set(_linkchecker_batch_import_nodes([$node_type]));
}
// Default to TRUE if comment module isn't enabled, we don't care.
if (!$original_linkchecker_comment_state && !empty($form_state->getValue('linkchecker_scan_comment'))) {
// We need to scan comments for this node-type now.
module_load_include('inc', 'linkchecker', 'linkchecker.batch');
- batch_set(_linkchecker_batch_import_comments(array($node_type)));
+ batch_set(_linkchecker_batch_import_comments([$node_type]));
}
}
function linkchecker_form_comment_form_alter(&$form, &$form_state, $form_id) {
// When displaying the form as 'view' or 'preview', show the broken links
// warning.
- if ((empty($form_state['input']) || (isset($form_state['input']['op']) && $form_state['input']['op'] == t('Preview'))) && arg(0) == 'comment' && is_numeric(arg(1)) && arg(2) == 'edit') {
+ $current_path = \Drupal::service('path.current')->getPath();
+ $path_args = explode('/', $current_path);
+ if ((empty($form_state->getUserInput()) || (isset($form_state->getUserInput()['op']) && $form_state->getUserInput()['op'] == t('Preview'))) && $path_args[1] == 'comment' && is_numeric($path_args[1]) && $path_args[2] == 'edit') {
// Show a message on comment edit page if a link check failed once or
// more often.
- $ignore_response_codes = preg_split('/(\r\n?|\n)/', variable_get('linkchecker_ignore_response_codes', "200\n206\n302\n304\n401\n403"));
- $links = db_query('SELECT ll.* FROM {linkchecker_comment} lc INNER JOIN {linkchecker_link} ll ON lc.lid = ll.lid WHERE lc.cid = :cid AND ll.fail_count > :fail_count AND ll.status = :status AND ll.code NOT IN (:codes)', array(':cid' => arg(1), ':fail_count' => 0, ':status' => 1, ':codes' => $ignore_response_codes));
+ $ignore_response_codes = preg_split('/(\r\n?|\n)/', \Drupal::config('linkchecker.settings')->get('error.ignore_response_codes'));
+ $connection = \Drupal::database();
+ $links = $connection->query('SELECT ll.* FROM {linkchecker_comment} lc INNER JOIN {linkchecker_link} ll ON lc.lid = ll.lid WHERE lc.cid = :cid AND ll.fail_count > :fail_count AND ll.status = :status AND ll.code NOT IN (:codes[])', [':cid' => arg(1), ':fail_count' => 0, ':status' => 1, ':codes[]' => $ignore_response_codes]);
foreach ($links as $link) {
if (_linkchecker_link_access($link)) {
- drupal_set_message(format_plural($link->fail_count, 'Link check of <a href="@url">@url</a> failed once (status code: @code).', 'Link check of <a href="@url">@url</a> failed @count times (status code: @code).', array('@url' => $link->url, '@code' => $link->code)), 'warning', FALSE);
+ drupal_set_message(\Drupal::translation()->formatPlural($link->fail_count, 'Link check of <a href="@url">@url</a> failed once (status code: @code).', 'Link check of <a href="@url">@url</a> failed @count times (status code: @code).', ['@url' => $link->url, '@code' => $link->code]), 'warning', FALSE);
}
}
}
* Custom submit handler for block add page.
*/
function linkchecker_block_custom_add_form_submit($form, &$form_state) {
- if (variable_get('linkchecker_scan_blocks', 0)) {
- $bid = db_query('SELECT MAX(bid) FROM {block_custom}')->fetchField();
+ if (\Drupal::config('linkchecker.settings')->get('scan_blocks')) {
+ $connection = \Drupal::database();
+ $bid = $connection->query('SELECT MAX(bid) FROM {block_custom}')->fetchField();
_linkchecker_add_block_custom_links($form_state['values'], $bid);
}
}
* Custom submit handler for block configure page.
*/
function linkchecker_block_custom_configure_form_submit($form, &$form_state) {
- if (variable_get('linkchecker_scan_blocks', 0)) {
+ if (\Drupal::config('linkchecker.settings')->get('scan_blocks')) {
_linkchecker_add_block_custom_links($form_state['values'], $form_state['values']['delta']);
}
}
$block->module = 'block';
$block->delta = $block_custom['bid'];
$block->info = $block_custom['info'];
- $block->body = array();
+ $block->body = [];
$block->body['value'] = $block_custom['body'];
$block->body['format'] = $block_custom['format'];
}
* structured array (see above) if $return_field_names is TRUE.
*/
function _linkchecker_extract_node_links($node, $return_field_names = FALSE) {
-
$filter = new stdClass();
$filter->settings['filter_url_length'] = 72;
// Create array of node fields to scan.
- $text_items = array();
- $text_items_by_field = array();
+ $text_items = [];
+ $text_items_by_field = [];
// Add fields typically not used for urls to the bottom. This way a link may
// found earlier while looping over $text_items_by_field below.
- $text_items_by_field = array_merge($text_items_by_field, _linkchecker_parse_fields('node', $node->type, $node, TRUE));
- $text_items_by_field['title'][] = _filter_url($node->title, $filter);
+ $link_check = _linkchecker_parse_fields('node', $node->bundle(), $node, TRUE);
+ $text_items_by_field = array_merge($text_items_by_field, $link_check);
$text_items = _linkchecker_array_values_recursive($text_items_by_field);
// Get the absolute node path for extraction of relative links.
- $languages = language_list();
+// @FIXME: Review again. What happens with languages in D8?
+// $languages = language_list();
// Note: An "undefined language" (value: 'und') isn't listed in the available
// languages variable $languages.
- $url_options = (empty($node->language) || empty($languages[$node->language])) ? array('absolute' => TRUE) : array('language' => $languages[$node->language], 'absolute' => TRUE);
- $path = url('node/' . $node->nid, $url_options);
+// $url_options = (empty($node->language) || empty($languages[$node->language])) ? array('absolute' => TRUE) : array('language' => $languages[$node->language], 'absolute' => TRUE);
+// $path = url('node/' . $node->nid, $url_options);
+ $path = Url::fromUri('base:' . 'node/' . $node->id())->toString();
// Extract all links in a node.
$links = _linkchecker_extract_links(implode(' ', $text_items), $path);
return $links;
}
else {
- $field_names = array();
+ $field_names = [];
foreach ($text_items_by_field as $field_name => $items) {
foreach ($items as $item) {
foreach ($links as $uri => $link) {
if (!empty($links)) {
// Remove all links from the links array already in the database and only
// add missing links to database.
- $missing_links = _linkchecker_node_links_missing($node->nid, $links);
+ $missing_links = _linkchecker_node_links_missing($node->id(), $links);
// Only add links to database that do not exists.
$i = 0;
foreach ($missing_links as $url) {
- $urlhash = drupal_hash_base64($url);
- $link = db_query('SELECT lid FROM {linkchecker_link} WHERE urlhash = :urlhash', array(':urlhash' => $urlhash))->fetchObject();
+ $urlhash = Crypt::hashBase64($url);
+ $connection = \Drupal::database();
+ $link = $connection->query('SELECT lid FROM {linkchecker_link} WHERE urlhash = :urlhash', [':urlhash' => $urlhash])->fetchObject();
if (!$link) {
$link = new stdClass();
$link->urlhash = $urlhash;
drupal_write_record('linkchecker_link', $link);
}
db_insert('linkchecker_node')
- ->fields(array(
+ ->fields([
'nid' => $node->nid,
'lid' => $link->lid,
- ))
+ ])
->execute();
// Break processing if max links limit per run has been reached.
$missing_links_count = count($missing_links) - LINKCHECKER_SCAN_MAX_LINKS_PER_RUN;
if (!$skip_missing_links_detection && $missing_links_count > 0) {
module_load_include('inc', 'linkchecker', 'linkchecker.batch');
- batch_set(_linkchecker_batch_import_single_node($node->nid, $missing_links_count));
+ batch_set(_linkchecker_batch_import_single_node($node->id(), $missing_links_count));
// If batches were set in the submit handlers, we process them now,
// possibly ending execution. We make sure we do not react to the batch
// that is already being processed (if a batch operation performs a
// drupal_execute).
if ($batch = &batch_get() && !isset($batch['current_set'])) {
- batch_process('node/' . $node->nid);
+ batch_process('node/' . $node->id());
}
}
}
// Remove dead link references for cleanup reasons as very last step.
- _linkchecker_cleanup_node_references($node->nid, $links);
+ _linkchecker_cleanup_node_references($node->id(), $links);
}
/**
* the need for content re-scans is detected by the number of missing links.
*/
function _linkchecker_add_comment_links($comment, $skip_missing_links_detection = FALSE) {
-
$filter = new stdClass();
$filter->settings['filter_url_length'] = 72;
// Create array of comment fields to scan.
- $text_items = array();
+ $text_items = [];
$text_items[] = _filter_url($comment->subject, $filter);
$text_items = array_merge($text_items, _linkchecker_parse_fields('comment', $comment->node_type, $comment));
// Get the absolute node path for extraction of relative links.
- $languages = language_list();
- $node = node_load($comment->nid);
- $url_options = (empty($node->language) || empty($languages[$node->language])) ? array('absolute' => TRUE) : array('language' => $languages[$node->language], 'absolute' => TRUE);
- $path = url('node/' . $comment->nid, $url_options);
+ $languages = \Drupal::languageManager()->getLanguages();
+ $node = Node::load($comment->getCommentedEntityId());
+ $url_options = (empty($node->language()->getId()) || empty($languages[$node->language()->getId()])) ? array('absolute' => TRUE) : ['language' => $languages[$node->language()->getId()], 'absolute' => TRUE];
+ $path = url('node/' . $comment->getCommentedEntityId(), $url_options);
// Extract all links in a comment.
$links = array_keys(_linkchecker_extract_links(implode(' ', $text_items), $path));
// Only add unique links to database that do not exist.
$i = 0;
foreach ($missing_links as $url) {
- $urlhash = drupal_hash_base64($url);
- $link = db_query('SELECT lid FROM {linkchecker_link} WHERE urlhash = :urlhash', array(':urlhash' => $urlhash))->fetchObject();
+ $urlhash = Crypt::hashBase64($url);
+ $connection = \Drupal::database();
+ $link = $connection->query('SELECT lid FROM {linkchecker_link} WHERE urlhash = :urlhash', [':urlhash' => $urlhash])->fetchObject();
if (!$link) {
$link = new stdClass();
$link->urlhash = $urlhash;
drupal_write_record('linkchecker_link', $link);
}
db_insert('linkchecker_comment')
- ->fields(array(
+ ->fields([
'cid' => $comment->cid,
'lid' => $link->lid,
- ))
+ ])
->execute();
// Break processing if max links limit per run has been reached.
// that is already being processed (if a batch operation performs a
// drupal_execute).
if ($batch = &batch_get() && !isset($batch['current_set'])) {
- batch_process('node/' . $comment->nid);
+ batch_process('node/' . $comment->getCommentedEntityId());
}
}
}
$filter->settings['filter_url_length'] = 72;
// Create array of custom block fields to scan. All fields cannot exists.
- $text_items = array();
+ $text_items = [];
if (!empty($block_custom->info)) {
$text_items[] = _filter_url($block_custom->info, $filter);
}
// Only add unique links to database that do not exist.
$i = 0;
foreach ($missing_links as $url) {
- $urlhash = drupal_hash_base64($url);
- $link = db_query('SELECT lid FROM {linkchecker_link} WHERE urlhash = :urlhash', array(':urlhash' => $urlhash))->fetchObject();
+ $urlhash = Crypt::hashBase64($url);
+ $connection = \Drupal::database();
+ $link = $connection->query('SELECT lid FROM {linkchecker_link} WHERE urlhash = :urlhash', [':urlhash' => $urlhash])->fetchObject();
if (!$link) {
$link = new stdClass();
$link->urlhash = $urlhash;
* The node ID.
*/
function _linkchecker_delete_node_links($nid) {
- db_delete('linkchecker_node')
+ \Drupal::database()->delete('linkchecker_node')
->condition('nid', $nid)
->execute();
}
* The comment ID.
*/
function _linkchecker_delete_comment_links($cid) {
- db_delete('linkchecker_comment')
+ \Drupal::database()->delete('linkchecker_comment')
->condition('cid', $cid)
->execute();
}
*
* @param int $bid
* The block ID.
- *
*/
function _linkchecker_delete_block_custom_links($bid) {
- db_delete('linkchecker_block_custom')
+ \Drupal::database()->delete('linkchecker_block_custom')
->condition('bid', $bid)
->execute();
}
* @param int $nid
* The node ID.
* @param array $links
+ * The links.
*/
-function _linkchecker_cleanup_node_references($nid = 0, $links = array()) {
+function _linkchecker_cleanup_node_references($nid = 0, $links = []) {
if (empty($links)) {
// Node do not have links. Delete all references if exists.
- db_delete('linkchecker_node')
+ \Drupal::database()->delete('linkchecker_node')
->condition('nid', $nid)
->execute();
}
// The node still have more than one link, but other links may have been
// removed and links no longer in the content need to be deleted from the
// linkchecker_node reference table.
- $subquery = db_select('linkchecker_link')
- ->fields('linkchecker_link', array('lid'))
- ->condition('urlhash', array_map('drupal_hash_base64', $links), 'IN');
+ $subquery = \Drupal::database()->select('linkchecker_link')
+ ->fields('linkchecker_link', ['lid'])
+ ->condition('urlhash', array_map('\Drupal\Component\Utility\Crypt::hashBase64', $links), 'IN');
- db_delete('linkchecker_node')
+ \Drupal::database()->delete('linkchecker_node')
->condition('nid', $nid)
->condition('lid', $subquery, 'NOT IN')
->execute();
* The comment ID.
* @param array $links
*/
-function _linkchecker_cleanup_comment_references($cid = 0, $links = array()) {
+function _linkchecker_cleanup_comment_references($cid = 0, $links = []) {
if (empty($links)) {
// Comment do not have links. Delete all references if exists.
- db_delete('linkchecker_comment')
+ \Drupal::database()->delete('linkchecker_comment')
->condition('cid', $cid)
->execute();
}
// The comment still have more than one link, but other links may have been
// removed and links no longer in the content need to be deleted from the
// linkchecker_comment reference table.
- $subquery = db_select('linkchecker_link', 'll')
- ->fields('ll', array('lid'))
- ->condition('ll.urlhash', array_map('drupal_hash_base64', $links), 'IN');
+ $subquery = \Drupal::database()->select('linkchecker_link', 'll')
+ ->fields('ll', ['lid'])
+ ->condition('ll.urlhash', array_map('\Drupal\Component\Utility\Crypt::hashBase64', $links), 'IN');
- db_delete('linkchecker_comment')
+ \Drupal::database()->delete('linkchecker_comment')
->condition('cid', $cid)
->condition('lid', $subquery, 'NOT IN')
->execute();
* The block ID.
* @param array $links
*/
-function _linkchecker_cleanup_block_custom_references($bid = 0, $links = array()) {
+function _linkchecker_cleanup_block_custom_references($bid = 0, $links = []) {
if (empty($links)) {
// Block do not have links. Delete all references if exists.
- db_delete('linkchecker_block_custom')
+ \Drupal::database()->delete('linkchecker_block_custom')
->condition('bid', $bid)
->execute();
}
// The block still have more than one link, but other links may have been
// removed and links no longer in the content need to be deleted from the
// linkchecker_block_custom reference table.
- $subquery = db_select('linkchecker_link')
- ->fields('linkchecker_link', array('lid'))
- ->condition('urlhash', array_map('drupal_hash_base64', $links), 'IN');
+ $subquery = \Drupal::database()->select('linkchecker_link')
+ ->fields('linkchecker_link', ['lid'])
+ ->condition('urlhash', array_map('\Drupal\Component\Utility\Crypt::hashBase64', $links), 'IN');
- db_delete('linkchecker_block_custom')
+ \Drupal::database()->delete('linkchecker_block_custom')
->condition('bid', $bid)
->condition('lid', $subquery, 'NOT IN')
->execute();
* An array of node references missing in the linkchecker_node table.
*/
function _linkchecker_node_links_missing($nid, $links) {
- $result = db_query('SELECT ll.url FROM {linkchecker_link} ll INNER JOIN {linkchecker_node} ln ON ln.lid = ll.lid WHERE ln.nid = :nid AND ll.urlhash IN (:urlhashes)', array(':nid' => $nid, ':urlhashes' => array_map('drupal_hash_base64', $links)));
- $links_in_database = array();
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT ll.url FROM {linkchecker_link} ll INNER JOIN {linkchecker_node} ln ON ln.lid = ll.lid WHERE ln.nid = :nid AND ll.urlhash IN (:urlhashes[])', [':nid' => $nid, ':urlhashes[]' => array_map('\Drupal\Component\Utility\Crypt::hashBase64', $links)]);
+ $links_in_database = [];
foreach ($result as $row) {
$links_in_database[] = $row->url;
}
* An array of comment references missing in the linkchecker_comment table.
*/
function _linkchecker_comment_links_missing($cid, $links) {
- $result = db_query('SELECT ll.url FROM {linkchecker_link} ll INNER JOIN {linkchecker_comment} lc ON lc.lid = ll.lid WHERE lc.cid = :cid AND ll.urlhash IN (:urlhashes)', array(':cid' => $cid, ':urlhashes' => array_map('drupal_hash_base64', $links)));
- $links_in_database = array();
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT ll.url FROM {linkchecker_link} ll INNER JOIN {linkchecker_comment} lc ON lc.lid = ll.lid WHERE lc.cid = :cid AND ll.urlhash IN (:urlhashes[])', array(':cid' => $cid, ':urlhashes[]' => array_map('\Drupal\Component\Utility\Crypt::hashBase64', $links)));
+ $links_in_database = [];
foreach ($result as $row) {
$links_in_database[] = $row->url;
}
* table.
*/
function _linkchecker_block_custom_links_missing($bid, $links) {
- $result = db_query('SELECT ll.url FROM {linkchecker_link} ll INNER JOIN {linkchecker_block_custom} lb ON lb.lid = ll.lid WHERE lb.bid = :bid AND ll.urlhash IN (:urlhashes)', array(':bid' => $bid, ':urlhashes' => array_map('drupal_hash_base64', $links)));
- $links_in_database = array();
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT ll.url FROM {linkchecker_link} ll INNER JOIN {linkchecker_block_custom} lb ON lb.lid = ll.lid WHERE lb.bid = :bid AND ll.urlhash IN (:urlhashes[])', array(':bid' => $bid, ':urlhashes[]' => array_map('\Drupal\Component\Utility\Crypt::hashBase64', $links)));
+ $links_in_database = [];
foreach ($result as $row) {
$links_in_database[] = $row->url;
}
* Array of field items with filters applied.
*/
function _linkchecker_parse_fields($entity_type, $bundle_name, $entity, $return_field_names = FALSE) {
- $text_items = array();
- $text_items_by_field = array();
+ $text_items = [];
+ $text_items_by_field = [];
// Create settings for _filter_url() function.
$filter = new stdClass();
$filter->settings['filter_url_length'] = 72;
// Collect the fields from this entity_type and bundle.
- foreach (field_info_instances($entity_type, $bundle_name) as $field_name => $instance) {
- $field = field_info_field($field_name);
- // #1923328: field_name array may be missing in $entity.
- $entity_field = isset($entity->{$field['field_name']}) ? $entity->{$field['field_name']} : array();
-
- switch ($field['type']) {
- // Core fields.
- case 'text_with_summary':
- foreach ($entity_field as $language) {
- foreach ($language as $item) {
- $item += array(
+ $entityManager = \Drupal::service('entity_field.manager');
+ $fields = $entityManager->getFieldDefinitions($entity_type, $bundle_name);
+
+ foreach ($fields as $field_name => $instance) {
+ if ($instance instanceof FieldConfigInterface ) {
+ $field = FieldStorageConfig::loadByName($entity_type, $field_name);
+ // #1923328: field_name array may be missing in $entity.
+ $entity_field = isset($entity->{$field->getName()}) ? $entity->{$field->getName()} : [];
+
+ switch ($field->getType()) {
+ // Core fields.
+ case 'text_with_summary':
+
+ $field_value = $entity_field->getValue();
+ foreach ($field_value as $item) {
+ $item += [
'format' => NULL,
'summary' => '',
'value' => '',
- );
- $text_items[] = $text_items_by_field[$field['field_name']][] = _linkchecker_check_markup($item['value'], $item['format'], linkchecker_entity_language($entity_type, $entity), TRUE);
- $text_items[] = $text_items_by_field[$field['field_name']][] = _linkchecker_check_markup($item['summary'], $item['format'], linkchecker_entity_language($entity_type, $entity), TRUE);
+ ];
+
+ $text_items[] = $text_items_by_field[$field_name][] = _linkchecker_check_markup($item['value'], $item['format'], linkchecker_entity_language($entity_type, $entity), TRUE);
+ $text_items[] = $text_items_by_field[$field_name][] = _linkchecker_check_markup($item['summary'], $item['format'], linkchecker_entity_language($entity_type, $entity), TRUE);
}
- }
- break;
+ break;
- // Core fields.
- case 'text_long':
- case 'text':
- foreach ($entity_field as $language) {
- foreach ($language as $item) {
- $item += array(
+ // Core fields.
+ case 'text_long':
+ case 'text':
+ case 'string':
+ case 'string_long':
+ $field_value = $entity_field->getValue();
+
+ foreach ($field_value as $item) {
+ $item += [
'format' => NULL,
'value' => '',
- );
- $text_items[] = $text_items_by_field[$field['field_name']][] = _linkchecker_check_markup($item['value'], $item['format'], linkchecker_entity_language($entity_type, $entity), TRUE);
+ ];
+ $text_items[] = $text_items_by_field[$field->getName()][] = _linkchecker_check_markup($item['value'], $item['format'], linkchecker_entity_language($entity_type, $entity), TRUE);
}
- }
- break;
+ break;
- // Link module field, http://drupal.org/project/link.
- case 'link_field':
- foreach ($entity_field as $language) {
- foreach ($language as $item) {
- $item += array(
- 'title' => '',
- );
- $options = drupal_parse_url(link_cleanup_url($item['url']));
- $text_items[] = $text_items_by_field[$field['field_name']][] = l($item['title'], $options['path'], $options);
- $text_items[] = $text_items_by_field[$field['field_name']][] = _linkchecker_check_markup($item['title'], NULL, linkchecker_entity_language($entity_type, $entity), TRUE);
+ // Link module field, http://drupal.org/project/link.
+ case 'link':
+ foreach ($entity_field->getValue() as $item) {
+ $item += [
+ 'title' => '',
+ ];
+ $options = [];
+ $text_items[] = $text_items_by_field[$field_name][] = \Drupal::l($item['title'], Url::fromUri($item['uri']), $options);
+ $text_items[] = $text_items_by_field[$field_name][] = _linkchecker_check_markup($item['title'], NULL, linkchecker_entity_language($entity_type, $entity), TRUE);
}
- }
- break;
+ break;
+ }
}
+
}
return ($return_field_names) ? $text_items_by_field : $text_items;
}
break;
+ // @todo: Module is now in D8 core, review if all works the same way and fix the comment.
// Link module field, http://drupal.org/project/link.
case 'link_field':
- foreach ($entity_field as $language_name => $language_value) {
- foreach ($language_value as $item_name => $item_value) {
- _linkchecker_link_replace($entity_field[$language_name][$item_name]['url'], $old_url, $new_url);
- _linkchecker_link_replace($entity_field[$language_name][$item_name]['title'], $old_url, $new_url);
- }
+// @todo: What happend to the language? It it really not needed anymore?
+// foreach ($entity_field as $language_name => $language_value) {
+// foreach ($language_value as $item_name => $item_value) {
+// _linkchecker_link_replace($entity_field[$language_name][$item_name]['url'], $old_url, $new_url);
+// _linkchecker_link_replace($entity_field[$language_name][$item_name]['title'], $old_url, $new_url);
+// }
+ foreach ($entity_field->getValue() as $item) {
+ _linkchecker_link_replace($entity_field[$field_name]['url'], $old_url, $new_url);
+ _linkchecker_link_replace($entity_field[$field_name]['title'], $old_url, $new_url);
}
break;
}
// Remove disabled node types no longer in use.
$node_types = linkchecker_scan_node_types();
if (!empty($node_types)) {
- $subquery1 = db_select('node', 'n')
- ->fields('n', array('nid'))
+ $subquery1 = \Drupal::database()->select('node', 'n')
+ ->fields('n', ['nid'])
->condition('n.type', $node_types, 'NOT IN');
- db_delete('linkchecker_node')
+ \Drupal::database()->delete('linkchecker_node')
->condition('nid', $subquery1, 'IN')
->execute();
}
else {
// No active node_type. Remove all items from table.
- db_truncate('linkchecker_node')->execute();
+ \Drupal::database()->truncate('linkchecker_node')->execute();
// @todo Remove comments link references from table.
}
// @todo Remove comments of unpublished nodes.
$comment_types = linkchecker_scan_comment_types();
if (empty($comment_types)) {
- db_truncate('linkchecker_comment')->execute();
+ \Drupal::database()->truncate('linkchecker_comment')->execute();
}
// Remove block link references if block scanning is disabled.
- if (variable_get('linkchecker_scan_blocks', 0) == 0) {
- db_truncate('linkchecker_block_custom')->execute();
+ if (\Drupal::config('linkchecker.settings')->get('scan_blocks') == FALSE) {
+ \Drupal::database()->truncate('linkchecker_block_custom')->execute();
}
// Remove dead links without references.
- $linkchecker_node = db_select('linkchecker_node', 'ln')
+ $linkchecker_node = \Drupal::database()->select('linkchecker_node', 'ln')
->distinct()
- ->fields('ln', array('lid'));
- $linkchecker_comment = db_select('linkchecker_comment', 'lc')
+ ->fields('ln', ['lid']);
+
+ $linkchecker_comment = \Drupal::database()->select('linkchecker_comment', 'lc')
->distinct()
- ->fields('lc', array('lid'));
- $linkchecker_block_custom = db_select('linkchecker_block_custom', 'lb')
+ ->fields('lc', ['lid']);
+
+ $linkchecker_block_custom = \Drupal::database()->select('linkchecker_block_custom', 'lb')
->distinct()
- ->fields('lb', array('lid'));
+ ->fields('lb', ['lid']);
// UNION all linkchecker type tables.
- $subquery2 = db_select($linkchecker_block_custom->union($linkchecker_comment)->union($linkchecker_node), 'q1')
+ $subquery2 = \Drupal::database()->select($linkchecker_block_custom->union($linkchecker_comment)->union($linkchecker_node), 'q1')
->distinct()
- ->fields('q1', array('lid'));
+ ->fields('q1', ['lid']);
- db_delete('linkchecker_link')
+ \Drupal::database()->delete('linkchecker_link')
->condition('lid', $subquery2, 'NOT IN')
->execute();
-
}
/**
function _linkchecker_extract_links($text = '', $content_path = NULL) {
global $base_root, $is_https;
- $html_dom = filter_dom_load($text);
- $urls = array();
+ $html_dom = Html::load($text);
+ $urls = [];
// Finds all hyperlinks in the content.
- if (variable_get('linkchecker_extract_from_a', 1) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_a') == TRUE) {
$links = $html_dom->getElementsByTagName('a');
foreach ($links as $link) {
$urls[] = $link->getAttribute('href');
}
// Finds all audio links in the content.
- if (variable_get('linkchecker_extract_from_audio', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_audio') == TRUE) {
$audios = $html_dom->getElementsByTagName('audio');
foreach ($audios as $audio) {
$urls[] = $audio->getAttribute('src');
}
// Finds embed tags with links in the content.
- if (variable_get('linkchecker_extract_from_embed', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_embed') == TRUE) {
$embeds = $html_dom->getElementsByTagName('embed');
foreach ($embeds as $embed) {
$urls[] = $embed->getAttribute('src');
}
// Finds iframe tags with links in the content.
- if (variable_get('linkchecker_extract_from_iframe', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_iframe') == TRUE) {
$iframes = $html_dom->getElementsByTagName('iframe');
foreach ($iframes as $iframe) {
$urls[] = $iframe->getAttribute('src');
}
// Finds img tags with links in the content.
- if (variable_get('linkchecker_extract_from_img', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_img') == TRUE) {
$imgs = $html_dom->getElementsByTagName('img');
foreach ($imgs as $img) {
$urls[] = $img->getAttribute('src');
}
// Finds object/param tags with links in the content.
- if (variable_get('linkchecker_extract_from_object', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_object') == TRUE) {
$objects = $html_dom->getElementsByTagName('object');
foreach ($objects as $object) {
$urls[] = $object->getAttribute('data');
// @todo
// - Try to extract links in unkown "flashvars" values
// (e.g., file=http://, data=http://).
- $names = array('archive', 'filename', 'href', 'movie', 'src', 'url');
+ $names = ['archive', 'filename', 'href', 'movie', 'src', 'url'];
if ($param->hasAttribute('name') && in_array($param->getAttribute('name'), $names)) {
$urls[] = $param->getAttribute('value');
}
- $srcs = array('movie');
+ $srcs = ['movie'];
if ($param->hasAttribute('src') && in_array($param->getAttribute('src'), $srcs)) {
$urls[] = $param->getAttribute('value');
}
}
// Finds video tags with links in the content.
- if (variable_get('linkchecker_extract_from_video', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_video') == TRUE) {
$videos = $html_dom->getElementsByTagName('video');
foreach ($videos as $video) {
$urls[] = $video->getAttribute('poster');
$urls = array_filter($urls);
// Remove duplicate urls.
$urls = array_unique($urls);
-
// What type of links should be checked?
- $linkchecker_check_links_types = variable_get('linkchecker_check_links_types', 1);
+ $linkchecker_check_links_types = \Drupal::config('linkchecker.settings')->get('check_links_types');
- $links = array();
+ $links = [];
foreach ($urls as $url) {
// Decode HTML links into plain text links.
// DOMDocument->loadHTML does not provide the RAW url from code. All html
$url_encoded = str_replace(' ', '%20', $url_decoded);
// Full qualified URLs.
- if ($linkchecker_check_links_types != 2 && valid_url($url_encoded, TRUE)) {
+ if ($linkchecker_check_links_types != 2 && UrlHelper::isValid($url_encoded, TRUE)) {
// Add to Array and change HTML links into plain text links.
$links[$url_decoded][] = $url;
}
continue;
}
// Local URLs. $linkchecker_check_links_types = 0 or 2
- elseif ($linkchecker_check_links_types != 1 && valid_url($url_encoded, FALSE)) {
+ elseif ($linkchecker_check_links_types != 1 && UrlHelper::isValid($url_encoded, FALSE)) {
// Get full qualified url with base path of content.
$absolute_content_path = _linkchecker_absolute_content_path($content_path);
// Don't do any string replacement if one of the values is empty.
if (!empty($text) && !empty($old_link_fqdn) && !empty($new_link_fqdn)) {
// Remove protocols and hostname from local URLs.
- $base_roots = array(
- drupal_strtolower('http://' . $_SERVER['HTTP_HOST']),
- drupal_strtolower('https://' . $_SERVER['HTTP_HOST']),
- );
+ $base_roots = [
+ Unicode::strtolower('http://' . $_SERVER['HTTP_HOST']),
+ Unicode::strtolower('https://' . $_SERVER['HTTP_HOST']),
+ ];
$old_link = str_replace($base_roots, '', $old_link_fqdn);
$new_link = str_replace($base_roots, '', $new_link_fqdn);
// Build variables with all URLs and run check_url() only once.
- $old_html_link_fqdn = check_url($old_link_fqdn);
- $new_html_link_fqdn = check_url($new_link_fqdn);
- $old_html_link = check_url($old_link);
- $new_html_link = check_url($new_link);
+ $old_html_link_fqdn = UrlHelper::filterBadProtocol($old_link_fqdn);
+ $new_html_link_fqdn = UrlHelper::filterBadProtocol($new_link_fqdn);
+ $old_html_link = UrlHelper::filterBadProtocol($old_link);
+ $new_html_link = UrlHelper::filterBadProtocol($new_link);
// Replace links in link fields and text and Links weblink fields.
- if (in_array($text, array($old_html_link_fqdn, $old_html_link, $old_link_fqdn, $old_link))) {
+ if (in_array($text, [$old_html_link_fqdn, $old_html_link, $old_link_fqdn, $old_link])) {
// Keep old and new links in the same encoding and format and short or
// fully qualified.
$text = str_replace($old_html_link_fqdn, $new_html_link_fqdn, $text);
}
else {
// Create an array of links with HTML decoded and encoded URLs.
- $old_links = array(
+ $old_links = [
$old_html_link_fqdn,
$old_html_link,
$old_link,
- );
+ ];
// Remove duplicate URLs from array if URLs do not have URL parameters.
// If more than one URL parameter exists - one URL in the array will have
$old_links = array_unique($old_links);
// Load HTML code into DOM.
- $html_dom = filter_dom_load($text);
+ $html_dom = Html::load($text);
// Finds all hyperlinks in the content.
- if (variable_get('linkchecker_extract_from_a', 1) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_a') == TRUE) {
$links = $html_dom->getElementsByTagName('a');
foreach ($links as $link) {
if (in_array($link->getAttribute('href'), $old_links)) {
}
// Finds all audio links in the content.
- if (variable_get('linkchecker_extract_from_audio', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_a') == TRUE) {
$audios = $html_dom->getElementsByTagName('audio');
foreach ($audios as $audio) {
if (in_array($audio->getAttribute('src'), $old_links)) {
}
// Finds embed tags with links in the content.
- if (variable_get('linkchecker_extract_from_embed', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_embed') == TRUE) {
$embeds = $html_dom->getElementsByTagName('embed');
foreach ($embeds as $embed) {
if (in_array($embed->getAttribute('src'), $old_links)) {
}
// Finds iframe tags with links in the content.
- if (variable_get('linkchecker_extract_from_iframe', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_iframe') == TRUE) {
$iframes = $html_dom->getElementsByTagName('iframe');
foreach ($iframes as $iframe) {
if (in_array($iframe->getAttribute('src'), $old_links)) {
}
// Finds img tags with links in the content.
- if (variable_get('linkchecker_extract_from_img', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_img') == TRUE) {
$imgs = $html_dom->getElementsByTagName('img');
foreach ($imgs as $img) {
if (in_array($img->getAttribute('src'), $old_links)) {
}
// Finds object/param tags with links in the content.
- if (variable_get('linkchecker_extract_from_object', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_object') == TRUE) {
$objects = $html_dom->getElementsByTagName('object');
foreach ($objects as $object) {
if (in_array($object->getAttribute('data'), $old_links)) {
// @todo
// - Try to replace links in unkown "flashvars" values
// (e.g., file=http://, data=http://).
- $names = array('archive', 'filename', 'href', 'movie', 'src', 'url');
+ $names = ['archive', 'filename', 'href', 'movie', 'src', 'url'];
if ($param->hasAttribute('name') && in_array($param->getAttribute('name'), $names)) {
if (in_array($param->getAttribute('value'), $old_links)) {
$param->setAttribute('value', $new_html_link);
}
}
- $srcs = array('movie');
+ $srcs = ['movie'];
if ($param->hasAttribute('src') && in_array($param->getAttribute('src'), $srcs)) {
if (in_array($param->getAttribute('value'), $old_links)) {
$param->setAttribute('value', $new_html_link);
}
// Finds video tags with links in the content.
- if (variable_get('linkchecker_extract_from_video', 0) == 1) {
+ if (\Drupal::config('linkchecker.settings')->get('extract.from_video') == TRUE) {
$videos = $html_dom->getElementsByTagName('video');
foreach ($videos as $video) {
if (in_array($video->getAttribute('poster'), $old_links)) {
$format_id = filter_fallback_format();
}
// If the requested text format does not exist, the text cannot be filtered.
- if (!$format = filter_format_load($format_id)) {
- linkchecker_watchdog_log('filter', 'Missing text format: %format.', array('%format' => $format_id), WATCHDOG_ALERT);
+ /** @var \Drupal\filter\Entity\FilterFormat $format **/
+ $format = FilterFormat::load($format_id);
+ if (!$format) {
+ linkchecker_watchdog_log('filter', 'Missing text format: %format.', ['%format' => $format_id], RfcLogLevel::ALERT);
return '';
}
$cache = $cache && !empty($format->cache);
$cache_id = '';
if ($cache) {
- $cache_id = 'linkchecker:' . $format->format . ':' . $langcode . ':' . hash('sha256', $text);
- if ($cached = cache_get($cache_id, 'cache_filter')) {
+ $cache_id = 'linkchecker:' . $format->id() . ':' . $langcode . ':' . hash('sha256', $text);
+ if ($cached = \Drupal::cache()->get($cache_id)) {
return $cached->data;
}
}
$text = str_replace(array("\r\n", "\r"), "\n", $text);
// Get a complete list of filters, ordered properly.
- $filters = filter_list_format($format->format);
- $filter_info = filter_get_filters();
+ /** @var \Drupal\filter\Plugin\FilterInterface[] $filters **/
+ $filters = $format->filters();
+ $filter_info = filter_formats();
// Do not run placeholder or special tag filters used as references to nodes
// like 'weblink' or 'weblinks' node types. If the original link node is
// notify about the broken link on all nodes having a link reference in
// content. This would only confuse the authors as they may also not be able
// to fix the source node of the reference.
- $filters_blacklist = array_keys(array_filter(variable_get('linkchecker_filter_blacklist', explode('|', LINKCHECKER_DEFAULT_FILTER_BLACKLIST))));
+ $filters_blacklist = array_keys(array_filter(\Drupal::config('linkchecker.settings')->get('extract.filter_blacklist')));
// Give filters the chance to escape HTML-like data such as code or formulas.
- foreach ($filters as $name => $filter) {
+ foreach ($filters->getAll() as $filter) {
+ $name = $filter->getType();
+ $status = $filter->status;
+
if (!in_array($name, $filters_blacklist)) {
- if ($filter->status && isset($filter_info[$name]['prepare callback']) && function_exists($filter_info[$name]['prepare callback'])) {
+ if ($status && isset($filter_info[$name]['prepare callback']) && function_exists($filter_info[$name]['prepare callback'])) {
$function = $filter_info[$name]['prepare callback'];
- $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
+ $text = $function($text, $filters, $format, $langcode, $cache, $cache_id);
}
}
}
// Perform filtering.
- foreach ($filters as $name => $filter) {
+ foreach ($filters->getAll() as $name => $filter) {
if (!in_array($name, $filters_blacklist)) {
if ($filter->status && isset($filter_info[$name]['process callback']) && function_exists($filter_info[$name]['process callback'])) {
$function = $filter_info[$name]['process callback'];
// Store in cache with a minimum expiration time of 1 day.
if ($cache) {
- cache_set($cache_id, $text, 'cache_filter', REQUEST_TIME + (60 * 60 * 24));
+ \Drupal::cache()->set($cache_id, $text, REQUEST_TIME + (60 * 60 * 24));
}
-
return $text;
}
}
// Break if the schema is not supported.
- if (!in_array($uri['scheme'], array('http', 'https'))) {
+ if (!in_array($uri['scheme'], ['http', 'https'])) {
return NULL;
}
$status = TRUE;
// Is url in domain blacklist?
- $urls = variable_get('linkchecker_disable_link_check_for_urls', LINKCHECKER_RESERVED_DOCUMENTATION_DOMAINS);
- if (!empty($urls) && preg_match('/' . implode('|', array_map(create_function('$links', 'return preg_quote($links, \'/\');'), preg_split('/(\r\n?|\n)/', $urls))) . '/', $url)) {
+ $urls = \Drupal::config('linkchecker.settings')->get('check.disable_link_check_for_urls');
+ if (!empty($urls) && preg_match('/' . implode('|', array_map(function ($links) { return preg_quote($links, '/'); }, preg_split('/(\r\n?|\n)/', $urls))) . '/', $url)) {
$status = FALSE;
}
*/
function _linkchecker_isvalid_response_code($code) {
- $responses = array(
+ $responses = [
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
- );
+ ];
return array_key_exists($code, $responses);
}
* An array of node type names, keyed by the type.
*/
function linkchecker_scan_node_types() {
- $types = array();
+ $types = [];
foreach (node_type_get_names() as $type => $name) {
- if (variable_get('linkchecker_scan_node_' . $type, FALSE)) {
+ $node_type = NodeType::load($type);
+ if ($node_type->getThirdPartySetting('linkchecker', 'scan_node', FALSE)) {
$types[$type] = $type;
}
}
* An array of node type names, keyed by the type.
*/
function linkchecker_scan_comment_types() {
- $types = array();
+ $types = [];
foreach (node_type_get_names() as $type => $name) {
- if (variable_get('linkchecker_scan_comment_' . $type, FALSE)) {
+ $node_type = NodeType::load($type);
+ if ($node_type->getThirdPartySetting('linkchecker', 'scan_comment', FALSE)) {
$types[$type] = $type;
}
}
* A link ID that have reached a defined failcount.
*/
function _linkchecker_unpublish_nodes($lid) {
- $result = db_query('SELECT nid FROM {linkchecker_node} WHERE lid = :lid', array(':lid' => $lid));
+ $connection = \Drupal::database();
+ $result = $connection->query('SELECT nid FROM {linkchecker_node} WHERE lid = :lid', [':lid' => $lid]);
foreach ($result as $row) {
- // Explicitly don't use node_load_multiple() or the module may run
+ // Explicitly don't use Node::load_multiple() or the module may run
// into issues like http://drupal.org/node/1210606. With this logic
// nodes can be updated until an out of memory occurs and further
// updates will be made on the remaining nodes only.
- $node = node_load($row->nid);
- $node->status = NODE_NOT_PUBLISHED;
- node_save($node);
- linkchecker_watchdog_log('linkchecker', 'Set @type %title to unpublished.', array('@type' => $node->type, '%title' => $node->title));
+ $node = Node::load($row->nid);
+ $node->setPublished(FALSE);
+ $node->save();
+ linkchecker_watchdog_log('linkchecker', 'Set @type %title to unpublished.', ['@type' => $node->bundle(), '%title' => $node->get('title')->value]);
}
}
* Load link as object.
*
* @param int $lid
- * The link id.
+ * The link id.
*
* @return object
*/
function linkchecker_link_load($lid) {
- return db_query('SELECT * FROM {linkchecker_link} WHERE lid = :lid', array(':lid' => $lid))->fetchObject();
+ $connection = \Drupal::database();
+ return $connection->query('SELECT * FROM {linkchecker_link} WHERE lid = :lid', [':lid' => $lid])->fetchObject();
}
/**
// - http://drupal.org/node/1522154
//
// Every moderation module saving a forward revision needs to return FALSE.
- // @todo: Refactor this workaround under D8.
-
+ // @FIXME: Refactor this workaround under D8.
// Workbench Moderation module.
- if (module_exists('workbench_moderation') && workbench_moderation_node_type_moderated($entity->type) === TRUE && empty($entity->workbench_moderation['updating_live_revision'])) {
- return FALSE;
- }
+ // if (\Drupal::moduleHandler()->moduleExists('workbench_moderation') && workbench_moderation_node_type_moderated($entity->type) === TRUE && empty($entity->workbench_moderation['updating_live_revision'])) {
+ // if (\Drupal::moduleHandler()->moduleExists('workbench_moderation') && ($entity->hasHandlerClass('moderation')) && empty($entity->workbench_moderation['updating_live_revision'])) {
+ // return FALSE;
+ // }
- return TRUE;
+ //return TRUE;
}
/**
* Returns all the values from the input array and indexes the array numerically.
*/
function _linkchecker_array_values_recursive(array $array) {
- $array_values = array();
+ $array_values = [];
foreach ($array as $value) {
if (is_array($value)) {