First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>AAA Update test</title>
<short_name>aaa_update_test</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>1</recommended_major>
<supported_majors>1</supported_majors>
<default_major>1</default_major>
<project_status>published</project_status>
<link>http://example.com/project/aaa_update_test</link>
<terms>
<term><name>Projects</name><value>Modules</value></term>
</terms>
<releases>
<release>
<name>aaa_update_test 7.x-1.0</name>
<version>7.x-1.0</version>
<tag>DRUPAL-7--1-0</tag>
<version_major>1</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/aaa_update_test-7-x-1-0-release</release_link>
<download_link>http://example.com/aaa_update_test-7.x-1.0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,11 @@
name = AAA Update test
description = Support module for update module testing.
package = Testing
core = 7.x
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,6 @@
<?php
/**
* @file
* Dummy module for testing Update status.
*/

View file

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<error>No release history was found for the requested project (aaa_update_test).</error>

Binary file not shown.

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>BBB Update test</title>
<short_name>bbb_update_test</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>1</recommended_major>
<supported_majors>1</supported_majors>
<default_major>1</default_major>
<project_status>published</project_status>
<link>http://example.com/project/bbb_update_test</link>
<terms>
<term><name>Projects</name><value>Modules</value></term>
</terms>
<releases>
<release>
<name>bbb_update_test 7.x-1.0</name>
<version>7.x-1.0</version>
<tag>DRUPAL-7--1-0</tag>
<version_major>1</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/bbb_update_test-7-x-1-0-release</release_link>
<download_link>http://example.com/bbb_update_test-7.x-1.0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,11 @@
name = BBB Update test
description = Support module for update module testing.
package = Testing
core = 7.x
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,6 @@
<?php
/**
* @file
* Dummy module for testing Update status.
*/

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>CCC Update test</title>
<short_name>ccc_update_test</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>1</recommended_major>
<supported_majors>1</supported_majors>
<default_major>1</default_major>
<project_status>published</project_status>
<link>http://example.com/project/ccc_update_test</link>
<terms>
<term><name>Projects</name><value>Modules</value></term>
</terms>
<releases>
<release>
<name>ccc_update_test 7.x-1.0</name>
<version>7.x-1.0</version>
<tag>DRUPAL-7--1-0</tag>
<version_major>1</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/ccc_update_test-7-x-1-0-release</release_link>
<download_link>http://example.com/ccc_update_test-7.x-1.0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,11 @@
name = CCC Update test
description = Support module for update module testing.
package = Testing
core = 7.x
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,6 @@
<?php
/**
* @file
* Dummy module for testing Update status.
*/

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Drupal</title>
<short_name>drupal</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>7</recommended_major>
<supported_majors>7</supported_majors>
<default_major>7</default_major>
<project_status>published</project_status>
<link>http://example.com/project/drupal</link>
<terms>
<term><name>Projects</name><value>Drupal project</value></term>
</terms>
<releases>
<release>
<name>Drupal 7.0</name>
<version>7.0</version>
<tag>DRUPAL-7-0</tag>
<version_major>7</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-0-release</release_link>
<download_link>http://example.com/drupal-7-0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Drupal</title>
<short_name>drupal</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>7</recommended_major>
<supported_majors>7</supported_majors>
<default_major>7</default_major>
<project_status>published</project_status>
<link>http://example.com/project/drupal</link>
<terms>
<term><name>Projects</name><value>Drupal project</value></term>
</terms>
<releases>
<release>
<name>Drupal 7.1</name>
<version>7.1</version>
<tag>DRUPAL-7-1</tag>
<version_major>7</version_major>
<version_patch>1</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-1-release</release_link>
<download_link>http://example.com/drupal-7-1.tar.gz</download_link>
<date>1250424581</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>2147483648</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
<release>
<name>Drupal 7.0</name>
<version>7.0</version>
<tag>DRUPAL-7-0</tag>
<version_major>7</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-0-release</release_link>
<download_link>http://example.com/drupal-7-0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Drupal</title>
<short_name>drupal</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>7</recommended_major>
<supported_majors>7</supported_majors>
<default_major>7</default_major>
<project_status>published</project_status>
<link>http://example.com/project/drupal</link>
<terms>
<term><name>Projects</name><value>Drupal project</value></term>
</terms>
<releases>
<release>
<name>Drupal 7.2</name>
<version>7.2</version>
<tag>DRUPAL-7-2</tag>
<version_major>7</version_major>
<version_patch>2</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-2-release</release_link>
<download_link>http://example.com/drupal-7-2.tar.gz</download_link>
<date>1250424641</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>4294967296</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
<term><name>Release type</name><value>Security update</value></term>
</terms>
</release>
<release>
<name>Drupal 7.1</name>
<version>7.1</version>
<tag>DRUPAL-7-1</tag>
<version_major>7</version_major>
<version_patch>1</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-1-release</release_link>
<download_link>http://example.com/drupal-7-1.tar.gz</download_link>
<date>1250424581</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>2147483648</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
<release>
<name>Drupal 7.0</name>
<version>7.0</version>
<tag>DRUPAL-7-0</tag>
<version_major>7</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-0-release</release_link>
<download_link>http://example.com/drupal-7-0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Drupal</title>
<short_name>drupal</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>7</recommended_major>
<supported_majors>7</supported_majors>
<default_major>7</default_major>
<project_status>published</project_status>
<link>http://example.com/project/drupal</link>
<terms>
<term><name>Projects</name><value>Drupal project</value></term>
</terms>
<releases>
<release>
<name>Drupal 7.0</name>
<version>7.0</version>
<tag>DRUPAL-7-0</tag>
<version_major>7</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/drupal-7-0-release</release_link>
<download_link>http://example.com/drupal-7-0.tar.gz</download_link>
<date>1250424521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
<release>
<name>Drupal 7.x-dev</name>
<version>7.x-dev</version>
<tag>DRUPAL-7</tag>
<version_major>7</version_major>
<version_extra>dev</version_extra>
<status>published</status>
<release_link>http://example.com/drupal-7-x-dev-release</release_link>
<download_link>http://example.com/drupal-7.x-dev.tar.gz</download_link>
<date>1250424581</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>2147483648</filesize>
<terms>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,10 @@
name = Update test admin theme
description = Test theme which is used as admin theme.
core = 7.x
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,10 @@
name = Update test base theme
description = Test theme which acts as a base theme for other test subthemes.
core = 7.x
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,11 @@
name = Update test subtheme
description = Test theme which uses update_test_basetheme as the base theme.
core = 7.x
base theme = update_test_basetheme
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,12 @@
name = Update test
description = Support module for update module testing.
package = Testing
version = VERSION
core = 7.x
hidden = TRUE
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,192 @@
<?php
/**
* @file
* Module for testing Update Manager functionality.
*/
/**
* Implements hook_system_theme_info().
*/
function update_test_system_theme_info() {
$themes['update_test_basetheme'] = drupal_get_path('module', 'update_test') . '/themes/update_test_basetheme/update_test_basetheme.info';
$themes['update_test_subtheme'] = drupal_get_path('module', 'update_test') . '/themes/update_test_subtheme/update_test_subtheme.info';
$themes['update_test_admintheme'] = drupal_get_path('module', 'update_test') . '/themes/update_test_admintheme/update_test_admintheme.info';
return $themes;
}
/**
* Implements hook_menu().
*/
function update_test_menu() {
$items = array();
$items['update-test'] = array(
'title' => t('Update test'),
'page callback' => 'update_test_mock_page',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['503-error'] = array(
'title' => t('503 Service unavailable'),
'page callback' => 'update_callback_service_unavailable',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_system_info_alter().
*
* Checks the 'update_test_system_info' variable and sees if we need to alter
* the system info for the given $file based on the setting. The setting is
* expected to be a nested associative array. If the key '#all' is defined, its
* subarray will include .info keys and values for all modules and themes on the
* system. Otherwise, the settings array is keyed by the module or theme short
* name ($file->name) and the subarrays contain settings just for that module or
* theme.
*/
function update_test_system_info_alter(&$info, $file) {
$setting = variable_get('update_test_system_info', array());
foreach (array('#all', $file->name) as $id) {
if (!empty($setting[$id])) {
foreach ($setting[$id] as $key => $value) {
$info[$key] = $value;
}
}
}
}
/**
* Implements hook_update_status_alter().
*
* Checks the 'update_test_update_status' variable and sees if we need to alter
* the update status for the given project based on the setting. The setting is
* expected to be a nested associative array. If the key '#all' is defined, its
* subarray will include .info keys and values for all modules and themes on the
* system. Otherwise, the settings array is keyed by the module or theme short
* name and the subarrays contain settings just for that module or theme.
*/
function update_test_update_status_alter(&$projects) {
$setting = variable_get('update_test_update_status', array());
if (!empty($setting)) {
foreach ($projects as $project_name => &$project) {
foreach (array('#all', $project_name) as $id) {
if (!empty($setting[$id])) {
foreach ($setting[$id] as $key => $value) {
$project[$key] = $value;
}
}
}
}
}
}
/**
* Page callback: Prints mock XML for the Update Manager module.
*
* The specific XML file to print depends on two things: the project we're
* trying to fetch data for, and the desired "availability scenario" for that
* project which we're trying to test. Before attempting to fetch this data (by
* checking for updates on the available updates report), callers need to define
* the 'update_test_xml_map' variable as an array, keyed by project name,
* indicating which availability scenario to use for that project.
*
* @param $project_name
* The project short name the update manager is trying to fetch data for (the
* fetch URLs are of the form: [base_url]/[project_name]/[core_version]).
*
* @see update_test_menu()
*/
function update_test_mock_page($project_name) {
$xml_map = variable_get('update_test_xml_map', FALSE);
if (isset($xml_map[$project_name])) {
$availability_scenario = $xml_map[$project_name];
}
elseif (isset($xml_map['#all'])) {
$availability_scenario = $xml_map['#all'];
}
else {
// The test didn't specify (for example, the webroot has other modules and
// themes installed but they're disabled by the version of the site
// running the test. So, we default to a file we know won't exist, so at
// least we'll get an empty page from readfile instead of a bunch of
// Drupal page output.
$availability_scenario = '#broken#';
}
$path = drupal_get_path('module', 'update_test');
readfile("$path/$project_name.$availability_scenario.xml");
}
/**
* Implements hook_archiver_info().
*/
function update_test_archiver_info() {
return array(
'update_test_archiver' => array(
// This is bogus, we only care about the extensions for now.
'class' => 'ArchiverUpdateTest',
'extensions' => array('update-test-extension'),
),
);
}
/**
* Implements hook_filetransfer_info().
*/
function update_test_filetransfer_info() {
// Define a mock file transfer method, to ensure that there will always be
// at least one method available in the user interface (regardless of the
// environment in which the update manager tests are run).
return array(
'system_test' => array(
'title' => t('Update Test FileTransfer'),
// This should be in an .inc file, but for testing purposes, it is OK to
// leave it in the main module file.
'file' => 'update_test.module',
'class' => 'UpdateTestFileTransfer',
'weight' => -20,
),
);
}
/**
* Mocks a FileTransfer object to test the settings form functionality.
*/
class UpdateTestFileTransfer {
/**
* Returns an UpdateTestFileTransfer object.
*
* @return
* A new UpdateTestFileTransfer object.
*/
public static function factory() {
return new UpdateTestFileTransfer;
}
/**
* Returns a settings form with a text field to input a username.
*/
public function getSettingsForm() {
$form = array();
$form['udpate_test_username'] = array(
'#type' => 'textfield',
'#title' => t('Update Test Username'),
);
return $form;
}
}
/**
* Page callback: Displays an Error 503 (Service unavailable) page.
*
* @see update_test_menu()
*/
function update_callback_service_unavailable() {
drupal_add_http_header('Status', '503 Service unavailable');
print "503 Service Temporarily Unavailable";
}

View file

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Update test base theme</title>
<short_name>update_test_basetheme</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>1</recommended_major>
<supported_majors>1</supported_majors>
<default_major>1</default_major>
<project_status>published</project_status>
<link>http://example.com/project/update_test_basetheme</link>
<terms>
<term><name>Projects</name><value>Themes</value></term>
</terms>
<releases>
<release>
<name>update_test_basetheme 7.x-1.1</name>
<version>7.x-1.1</version>
<tag>DRUPAL-7--1-1</tag>
<version_major>1</version_major>
<version_patch>1</version_patch>
<status>published</status>
<release_link>http://example.com/update_test_basetheme-7-x-1-1-release</release_link>
<download_link>http://example.com/update_test_basetheme-7.x-1.1.tar.gz</download_link>
<date>1250624521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073763241</filesize>
<terms>
<term><name>Release type</name><value>Security update</value></term>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
<release>
<name>update_test_basetheme 7.x-1.0</name>
<version>7.x-1.0</version>
<tag>DRUPAL-7--1-0</tag>
<version_major>1</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/update_test_basetheme-7-x-1-0-release</release_link>
<download_link>http://example.com/update_test_basetheme-7.x-1.0.tar.gz</download_link>
<date>1250524521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>Update test subtheme</title>
<short_name>update_test_subtheme</short_name>
<dc:creator>Drupal</dc:creator>
<api_version>7.x</api_version>
<recommended_major>1</recommended_major>
<supported_majors>1</supported_majors>
<default_major>1</default_major>
<project_status>published</project_status>
<link>http://example.com/project/update_test_subtheme</link>
<terms>
<term><name>Projects</name><value>Themes</value></term>
</terms>
<releases>
<release>
<name>update_test_subtheme 7.x-1.0</name>
<version>7.x-1.0</version>
<tag>DRUPAL-7--1-0</tag>
<version_major>1</version_major>
<version_patch>0</version_patch>
<status>published</status>
<release_link>http://example.com/update_test_subtheme-7-x-1-0-release</release_link>
<download_link>http://example.com/update_test_subtheme-7.x-1.0.tar.gz</download_link>
<date>1250524521</date>
<mdhash>b966255555d9c9b86d480ca08cfaa98e</mdhash>
<filesize>1073741824</filesize>
<terms>
<term><name>Release type</name><value>New features</value></term>
<term><name>Release type</name><value>Bug fixes</value></term>
</terms>
</release>
</releases>
</project>

View file

@ -0,0 +1,35 @@
/**
* @file
* RTL styles used by the Update Manager module.
*/
.update .project {
padding-right: .25em;
}
.update .version-status {
float: left;
padding-left: 10px;
}
.update .version-status .icon {
padding-right: .5em;
}
.update table.version .version-title {
padding-left: 1em;
}
.update table.version .version-details {
padding-left: .5em;
direction: ltr;
}
.update table.version .version-links {
text-align: left;
padding-left: 1em;
}
.update .check-manually {
padding-right: 1em;
}

View file

@ -0,0 +1,133 @@
<?php
/**
* @file
* Hooks provided by the Update Manager module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Alter the list of projects before fetching data and comparing versions.
*
* Most modules will never need to implement this hook. It is for advanced
* interaction with the Update Manager module. The primary use-case for this
* hook is to add projects to the list; for example, to provide update status
* data on disabled modules and themes. A contributed module might want to hide
* projects from the list; for example, if there is a site-specific module that
* doesn't have any official releases, that module could remove itself from this
* list to avoid "No available releases found" warnings on the available updates
* report. In rare cases, a module might want to alter the data associated with
* a project already in the list.
*
* @param $projects
* Reference to an array of the projects installed on the system. This
* includes all the metadata documented in the comments below for each project
* (either module or theme) that is currently enabled. The array is initially
* populated inside update_get_projects() with the help of
* _update_process_info_list(), so look there for examples of how to populate
* the array with real values.
*
* @see update_get_projects()
* @see _update_process_info_list()
*/
function hook_update_projects_alter(&$projects) {
// Hide a site-specific module from the list.
unset($projects['site_specific_module']);
// Add a disabled module to the list.
// The key for the array should be the machine-readable project "short name".
$projects['disabled_project_name'] = array(
// Machine-readable project short name (same as the array key above).
'name' => 'disabled_project_name',
// Array of values from the main .info file for this project.
'info' => array(
'name' => 'Some disabled module',
'description' => 'A module not enabled on the site that you want to see in the available updates report.',
'version' => '7.x-1.0',
'core' => '7.x',
// The maximum file change time (the "ctime" returned by the filectime()
// PHP method) for all of the .info files included in this project.
'_info_file_ctime' => 1243888165,
),
// The date stamp when the project was released, if known. If the disabled
// project was an officially packaged release from drupal.org, this will
// be included in the .info file as the 'datestamp' field. This only
// really matters for development snapshot releases that are regenerated,
// so it can be left undefined or set to 0 in most cases.
'datestamp' => 1243888185,
// Any modules (or themes) included in this project. Keyed by machine-
// readable "short name", value is the human-readable project name printed
// in the UI.
'includes' => array(
'disabled_project' => 'Disabled module',
'disabled_project_helper' => 'Disabled module helper module',
'disabled_project_foo' => 'Disabled module foo add-on module',
),
// Does this project contain a 'module', 'theme', 'disabled-module', or
// 'disabled-theme'?
'project_type' => 'disabled-module',
);
}
/**
* Alter the information about available updates for projects.
*
* @param $projects
* Reference to an array of information about available updates to each
* project installed on the system.
*
* @see update_calculate_project_data()
*/
function hook_update_status_alter(&$projects) {
$settings = variable_get('update_advanced_project_settings', array());
foreach ($projects as $project => $project_info) {
if (isset($settings[$project]) && isset($settings[$project]['check']) &&
($settings[$project]['check'] == 'never' ||
(isset($project_info['recommended']) &&
$settings[$project]['check'] === $project_info['recommended']))) {
$projects[$project]['status'] = UPDATE_NOT_CHECKED;
$projects[$project]['reason'] = t('Ignored from settings');
if (!empty($settings[$project]['notes'])) {
$projects[$project]['extra'][] = array(
'class' => array('admin-note'),
'label' => t('Administrator note'),
'data' => $settings[$project]['notes'],
);
}
}
}
}
/**
* Verify an archive after it has been downloaded and extracted.
*
* @param string $project
* The short name of the project that has been downloaded.
* @param string $archive_file
* The filename of the unextracted archive.
* @param string $directory
* The directory that the archive was extracted into.
*
* @return
* If there are any problems, return an array of error messages. If there are
* no problems, return an empty array.
*
* @see update_manager_archive_verify()
* @ingroup update_manager_file
*/
function hook_verify_update_archive($project, $archive_file, $directory) {
$errors = array();
if (!file_exists($directory)) {
$errors[] = t('The %directory does not exist.', array('%directory' => $directory));
}
// Add other checks on the archive integrity here.
return $errors;
}
/**
* @} End of "addtogroup hooks".
*/

View file

@ -0,0 +1,339 @@
<?php
/**
* @file
* Callbacks and related functions invoked by authorize.php to update projects.
*
* We use the Batch API to actually update each individual project on the site.
* All of the code in this file is run at a low bootstrap level (modules are not
* loaded), so these functions cannot assume access to the rest of the code of
* the Update Manager module.
*/
/**
* Updates existing projects when invoked by authorize.php.
*
* Callback for system_authorized_init() in
* update_manager_update_ready_form_submit().
*
* @param $filetransfer
* The FileTransfer object created by authorize.php for use during this
* operation.
* @param $projects
* A nested array of projects to install into the live webroot, keyed by
* project name. Each subarray contains the following keys:
* - project: The canonical project short name.
* - updater_name: The name of the Updater class to use for this project.
* - local_url: The locally installed location of new code to update with.
*/
function update_authorize_run_update($filetransfer, $projects) {
$operations = array();
foreach ($projects as $project => $project_info) {
$operations[] = array(
'update_authorize_batch_copy_project',
array(
$project_info['project'],
$project_info['updater_name'],
$project_info['local_url'],
$filetransfer,
),
);
}
$batch = array(
'title' => t('Installing updates'),
'init_message' => t('Preparing to update your site'),
'operations' => $operations,
'finished' => 'update_authorize_update_batch_finished',
'file' => drupal_get_path('module', 'update') . '/update.authorize.inc',
);
batch_set($batch);
// Invoke the batch via authorize.php.
system_authorized_batch_process();
}
/**
* Installs a new project when invoked by authorize.php.
*
* Callback for system_authorized_init() in
* update_manager_install_form_submit().
*
* @param FileTransfer $filetransfer
* The FileTransfer object created by authorize.php for use during this
* operation.
* @param string $project
* The canonical project short name (e.g., {system}.name).
* @param string $updater_name
* The name of the Updater class to use for installing this project.
* @param string $local_url
* The URL to the locally installed temp directory where the project has
* already been downloaded and extracted into.
*/
function update_authorize_run_install($filetransfer, $project, $updater_name, $local_url) {
$operations[] = array(
'update_authorize_batch_copy_project',
array(
$project,
$updater_name,
$local_url,
$filetransfer,
),
);
// @todo Instantiate our Updater to set the human-readable title?
$batch = array(
'title' => t('Installing %project', array('%project' => $project)),
'init_message' => t('Preparing to install'),
'operations' => $operations,
// @todo Use a different finished callback for different messages?
'finished' => 'update_authorize_install_batch_finished',
'file' => drupal_get_path('module', 'update') . '/update.authorize.inc',
);
batch_set($batch);
// Invoke the batch via authorize.php.
system_authorized_batch_process();
}
/**
* Implements callback_batch_operation().
*
* Copies project to its proper place when authorized to do so.
*
* @param string $project
* The canonical short name of the project being installed.
* @param string $updater_name
* The name of the Updater class to use for installing this project.
* @param string $local_url
* The URL to the locally installed temp directory where the project has
* already been downloaded and extracted into.
* @param FileTransfer $filetransfer
* The FileTransfer object to use for performing this operation.
* @param array $context
* Reference to an array used for Batch API storage.
*/
function update_authorize_batch_copy_project($project, $updater_name, $local_url, $filetransfer, &$context) {
// Initialize some variables in the Batch API $context array.
if (!isset($context['results']['log'])) {
$context['results']['log'] = array();
}
if (!isset($context['results']['log'][$project])) {
$context['results']['log'][$project] = array();
}
if (!isset($context['results']['tasks'])) {
$context['results']['tasks'] = array();
}
// The batch API uses a session, and since all the arguments are serialized
// and unserialized between requests, although the FileTransfer object itself
// will be reconstructed, the connection pointer itself will be lost. However,
// the FileTransfer object will still have the connection variable, even
// though the connection itself is now gone. So, although it's ugly, we have
// to unset the connection variable at this point so that the FileTransfer
// object will re-initiate the actual connection.
unset($filetransfer->connection);
if (!empty($context['results']['log'][$project]['#abort'])) {
$context['finished'] = 1;
return;
}
$updater = new $updater_name($local_url);
try {
if ($updater->isInstalled()) {
// This is an update.
$tasks = $updater->update($filetransfer);
}
else {
$tasks = $updater->install($filetransfer);
}
}
catch (UpdaterException $e) {
_update_batch_create_message($context['results']['log'][$project], t('Error installing / updating'), FALSE);
_update_batch_create_message($context['results']['log'][$project], $e->getMessage(), FALSE);
$context['results']['log'][$project]['#abort'] = TRUE;
return;
}
_update_batch_create_message($context['results']['log'][$project], t('Installed %project_name successfully', array('%project_name' => $project)));
if (!empty($tasks)) {
$context['results']['tasks'] += $tasks;
}
// This particular operation is now complete, even though the batch might
// have other operations to perform.
$context['finished'] = 1;
}
/**
* Implements callback_batch_finished().
*
* Performs actions when the authorized update batch is done.
*
* This processes the results and stashes them into SESSION such that
* authorize.php will render a report. Also responsible for putting the site
* back online and clearing the update status cache after a successful update.
*
* @param $success
* TRUE if the batch operation was successful; FALSE if there were errors.
* @param $results
* An associative array of results from the batch operation.
*/
function update_authorize_update_batch_finished($success, $results) {
foreach ($results['log'] as $project => $messages) {
if (!empty($messages['#abort'])) {
$success = FALSE;
}
}
$offline = variable_get('maintenance_mode', FALSE);
if ($success) {
// Now that the update completed, we need to clear the cache of available
// update data and recompute our status, so prevent show bogus results.
_update_authorize_clear_update_status();
// Take the site out of maintenance mode if it was previously that way.
if ($offline && isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) {
variable_set('maintenance_mode', FALSE);
$page_message = array(
'message' => t('Update was completed successfully. Your site has been taken out of maintenance mode.'),
'type' => 'status',
);
}
else {
$page_message = array(
'message' => t('Update was completed successfully.'),
'type' => 'status',
);
}
}
elseif (!$offline) {
$page_message = array(
'message' => t('Update failed! See the log below for more information.'),
'type' => 'error',
);
}
else {
$page_message = array(
'message' => t('Update failed! See the log below for more information. Your site is still in maintenance mode.'),
'type' => 'error',
);
}
// Since we're doing an update of existing code, always add a task for
// running update.php.
$results['tasks'][] = t('Your modules have been downloaded and updated.');
$results['tasks'][] = t('<a href="@update">Run database updates</a>', array('@update' => base_path() . 'update.php'));
// Unset the variable since it is no longer needed.
unset($_SESSION['maintenance_mode']);
// Set all these values into the SESSION so authorize.php can display them.
$_SESSION['authorize_results']['success'] = $success;
$_SESSION['authorize_results']['page_message'] = $page_message;
$_SESSION['authorize_results']['messages'] = $results['log'];
$_SESSION['authorize_results']['tasks'] = $results['tasks'];
$_SESSION['authorize_operation']['page_title'] = t('Update manager');
}
/**
* Implements callback_batch_finished().
*
* Performs actions when the authorized install batch is done.
*
* This processes the results and stashes them into SESSION such that
* authorize.php will render a report. Also responsible for putting the site
* back online after a successful install if necessary.
*
* @param $success
* TRUE if the batch operation was a success; FALSE if there were errors.
* @param $results
* An associative array of results from the batch operation.
*/
function update_authorize_install_batch_finished($success, $results) {
foreach ($results['log'] as $project => $messages) {
if (!empty($messages['#abort'])) {
$success = FALSE;
}
}
$offline = variable_get('maintenance_mode', FALSE);
if ($success) {
// Take the site out of maintenance mode if it was previously that way.
if ($offline && isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) {
variable_set('maintenance_mode', FALSE);
$page_message = array(
'message' => t('Installation was completed successfully. Your site has been taken out of maintenance mode.'),
'type' => 'status',
);
}
else {
$page_message = array(
'message' => t('Installation was completed successfully.'),
'type' => 'status',
);
}
}
elseif (!$success && !$offline) {
$page_message = array(
'message' => t('Installation failed! See the log below for more information.'),
'type' => 'error',
);
}
else {
$page_message = array(
'message' => t('Installation failed! See the log below for more information. Your site is still in maintenance mode.'),
'type' => 'error',
);
}
// Unset the variable since it is no longer needed.
unset($_SESSION['maintenance_mode']);
// Set all these values into the SESSION so authorize.php can display them.
$_SESSION['authorize_results']['success'] = $success;
$_SESSION['authorize_results']['page_message'] = $page_message;
$_SESSION['authorize_results']['messages'] = $results['log'];
$_SESSION['authorize_results']['tasks'] = $results['tasks'];
$_SESSION['authorize_operation']['page_title'] = t('Update manager');
}
/**
* Creates a structure of log messages.
*
* @param array $project_results
* An associative array of results from the batch operation.
* @param string $message
* A string containing a log message.
* @param bool $success
* (optional) TRUE if the operation the message is about was a success, FALSE
* if there were errors. Defaults to TRUE.
*/
function _update_batch_create_message(&$project_results, $message, $success = TRUE) {
$project_results[] = array('message' => $message, 'success' => $success);
}
/**
* Clears cached available update status data.
*
* Since this function is run at such a low bootstrap level, the Update Manager
* module is not loaded. So, we can't just call _update_cache_clear(). However,
* the database is bootstrapped, so we can do a query ourselves to clear out
* what we want to clear.
*
* Note that we do not want to just truncate the table, since that would remove
* items related to currently pending fetch attempts.
*
* @see update_authorize_update_batch_finished()
* @see _update_cache_clear()
*/
function _update_authorize_clear_update_status() {
$query = db_delete('cache_update');
$query->condition(
db_or()
->condition('cid', 'update_project_%', 'LIKE')
->condition('cid', 'available_releases::%', 'LIKE')
);
$query->execute();
}

View file

@ -0,0 +1,838 @@
<?php
/**
* @file
* Code required only when comparing available updates to existing data.
*/
/**
* Fetches an array of installed and enabled projects.
*
* This is only responsible for generating an array of projects (taking into
* account projects that include more than one module or theme). Other
* information like the specific version and install type (official release,
* dev snapshot, etc) is handled later in update_process_project_info() since
* that logic is only required when preparing the status report, not for
* fetching the available release data.
*
* This array is fairly expensive to construct, since it involves a lot of disk
* I/O, so we cache the results into the {cache_update} table using the
* 'update_project_projects' cache ID. However, since this is not the data about
* available updates fetched from the network, it is acceptable to invalidate it
* somewhat quickly. If we keep this data for very long, site administrators are
* more likely to see incorrect results if they upgrade to a newer version of a
* module or theme but do not visit certain pages that automatically clear this
* cache.
*
* @return
* An associative array of currently enabled projects keyed by the
* machine-readable project short name. Each project contains:
* - name: The machine-readable project short name.
* - info: An array with values from the main .info file for this project.
* - name: The human-readable name of the project.
* - package: The package that the project is grouped under.
* - version: The version of the project.
* - project: The Drupal.org project name.
* - datestamp: The date stamp of the project's main .info file.
* - _info_file_ctime: The maximum file change time for all of the .info
* files included in this project.
* - datestamp: The date stamp when the project was released, if known.
* - includes: An associative array containing all projects included with this
* project, keyed by the machine-readable short name with the human-readable
* name as value.
* - project_type: The type of project. Allowed values are 'module' and
* 'theme'.
* - project_status: This indicates if the project is enabled and will always
* be TRUE, as the function only returns enabled projects.
* - sub_themes: If the project is a theme it contains an associative array of
* all sub-themes.
* - base_themes: If the project is a theme it contains an associative array
* of all base-themes.
*
* @see update_process_project_info()
* @see update_calculate_project_data()
* @see update_project_cache()
*/
function update_get_projects() {
$projects = &drupal_static(__FUNCTION__, array());
if (empty($projects)) {
// Retrieve the projects from cache, if present.
$projects = update_project_cache('update_project_projects');
if (empty($projects)) {
// Still empty, so we have to rebuild the cache.
$module_data = system_rebuild_module_data();
$theme_data = system_rebuild_theme_data();
_update_process_info_list($projects, $module_data, 'module', TRUE);
_update_process_info_list($projects, $theme_data, 'theme', TRUE);
if (variable_get('update_check_disabled', FALSE)) {
_update_process_info_list($projects, $module_data, 'module', FALSE);
_update_process_info_list($projects, $theme_data, 'theme', FALSE);
}
// Allow other modules to alter projects before fetching and comparing.
drupal_alter('update_projects', $projects);
// Cache the site's project data for at most 1 hour.
_update_cache_set('update_project_projects', $projects, REQUEST_TIME + 3600);
}
}
return $projects;
}
/**
* Populates an array of project data.
*
* This iterates over a list of the installed modules or themes and groups them
* by project and status. A few parts of this function assume that enabled
* modules and themes are always processed first, and if disabled modules or
* themes are being processed (there is a setting to control if disabled code
* should be included or not in the 'Available updates' report), those are only
* processed after $projects has been populated with information about the
* enabled code. Modules and themes set as hidden are always ignored. This
* function also records the latest change time on the .info files for each
* module or theme, which is important data which is used when deciding if the
* cached available update data should be invalidated.
*
* @param $projects
* Reference to the array of project data of what's installed on this site.
* @param $list
* Array of data to process to add the relevant info to the $projects array.
* @param $project_type
* The kind of data in the list. Can be 'module' or 'theme'.
* @param $status
* Boolean that controls what status (enabled or disabled) to process out of
* the $list and add to the $projects array.
*
* @see update_get_projects()
*/
function _update_process_info_list(&$projects, $list, $project_type, $status) {
$admin_theme = variable_get('admin_theme', 'seven');
foreach ($list as $file) {
// The admin theme is a special case. It should always be considered enabled
// for the purposes of update checking.
if ($file->name === $admin_theme) {
$file->status = TRUE;
}
// A disabled base theme of an enabled sub-theme still has all of its code
// run by the sub-theme, so we include it in our "enabled" projects list.
if ($status && !$file->status && !empty($file->sub_themes)) {
foreach ($file->sub_themes as $key => $name) {
// Build a list of enabled sub-themes.
if ($list[$key]->status) {
$file->enabled_sub_themes[$key] = $name;
}
}
// If there are no enabled subthemes, we should ignore this base theme
// for the enabled case. If the site is trying to display disabled
// themes, we'll catch it then.
if (empty($file->enabled_sub_themes)) {
continue;
}
}
// Otherwise, just add projects of the proper status to our list.
elseif ($file->status != $status) {
continue;
}
// Skip if the .info file is broken.
if (empty($file->info)) {
continue;
}
// Skip if it's a hidden module or theme.
if (!empty($file->info['hidden'])) {
continue;
}
// If the .info doesn't define the 'project', try to figure it out.
if (!isset($file->info['project'])) {
$file->info['project'] = update_get_project_name($file);
}
// If we still don't know the 'project', give up.
if (empty($file->info['project'])) {
continue;
}
// If we don't already know it, grab the change time on the .info file
// itself. Note: we need to use the ctime, not the mtime (modification
// time) since many (all?) tar implementations will go out of their way to
// set the mtime on the files it creates to the timestamps recorded in the
// tarball. We want to see the last time the file was changed on disk,
// which is left alone by tar and correctly set to the time the .info file
// was unpacked.
if (!isset($file->info['_info_file_ctime'])) {
$info_filename = dirname($file->uri) . '/' . $file->name . '.info';
$file->info['_info_file_ctime'] = filectime($info_filename);
}
if (!isset($file->info['datestamp'])) {
$file->info['datestamp'] = 0;
}
$project_name = $file->info['project'];
// Figure out what project type we're going to use to display this module
// or theme. If the project name is 'drupal', we don't want it to show up
// under the usual "Modules" section, we put it at a special "Drupal Core"
// section at the top of the report.
if ($project_name == 'drupal') {
$project_display_type = 'core';
}
else {
$project_display_type = $project_type;
}
if (empty($status) && empty($file->enabled_sub_themes)) {
// If we're processing disabled modules or themes, append a suffix.
// However, we don't do this to a a base theme with enabled
// subthemes, since we treat that case as if it is enabled.
$project_display_type .= '-disabled';
}
// Add a list of sub-themes that "depend on" the project and a list of base
// themes that are "required by" the project.
if ($project_name == 'drupal') {
// Drupal core is always required, so this extra info would be noise.
$sub_themes = array();
$base_themes = array();
}
else {
// Add list of enabled sub-themes.
$sub_themes = !empty($file->enabled_sub_themes) ? $file->enabled_sub_themes : array();
// Add list of base themes.
$base_themes = !empty($file->base_themes) ? $file->base_themes : array();
}
if (!isset($projects[$project_name])) {
// Only process this if we haven't done this project, since a single
// project can have multiple modules or themes.
$projects[$project_name] = array(
'name' => $project_name,
// Only save attributes from the .info file we care about so we do not
// bloat our RAM usage needlessly.
'info' => update_filter_project_info($file->info),
'datestamp' => $file->info['datestamp'],
'includes' => array($file->name => $file->info['name']),
'project_type' => $project_display_type,
'project_status' => $status,
'sub_themes' => $sub_themes,
'base_themes' => $base_themes,
);
}
elseif ($projects[$project_name]['project_type'] == $project_display_type) {
// Only add the file we're processing to the 'includes' array for this
// project if it is of the same type and status (which is encoded in the
// $project_display_type). This prevents listing all the disabled
// modules included with an enabled project if we happen to be checking
// for disabled modules, too.
$projects[$project_name]['includes'][$file->name] = $file->info['name'];
$projects[$project_name]['info']['_info_file_ctime'] = max($projects[$project_name]['info']['_info_file_ctime'], $file->info['_info_file_ctime']);
$projects[$project_name]['datestamp'] = max($projects[$project_name]['datestamp'], $file->info['datestamp']);
if (!empty($sub_themes)) {
$projects[$project_name]['sub_themes'] += $sub_themes;
}
if (!empty($base_themes)) {
$projects[$project_name]['base_themes'] += $base_themes;
}
}
elseif (empty($status)) {
// If we have a project_name that matches, but the project_display_type
// does not, it means we're processing a disabled module or theme that
// belongs to a project that has some enabled code. In this case, we add
// the disabled thing into a separate array for separate display.
$projects[$project_name]['disabled'][$file->name] = $file->info['name'];
}
}
}
/**
* Determines what project a given file object belongs to.
*
* @param $file
* A file object as returned by system_get_files_database().
*
* @return
* The canonical project short name.
*
* @see system_get_files_database()
*/
function update_get_project_name($file) {
$project_name = '';
if (isset($file->info['project'])) {
$project_name = $file->info['project'];
}
elseif (isset($file->info['package']) && (strpos($file->info['package'], 'Core') === 0)) {
$project_name = 'drupal';
}
return $project_name;
}
/**
* Determines version and type information for currently installed projects.
*
* Processes the list of projects on the system to figure out the currently
* installed versions, and other information that is required before we can
* compare against the available releases to produce the status report.
*
* @param $projects
* Array of project information from update_get_projects().
*/
function update_process_project_info(&$projects) {
foreach ($projects as $key => $project) {
// Assume an official release until we see otherwise.
$install_type = 'official';
$info = $project['info'];
if (isset($info['version'])) {
// Check for development snapshots
if (preg_match('@(dev|HEAD)@', $info['version'])) {
$install_type = 'dev';
}
// Figure out what the currently installed major version is. We need
// to handle both contribution (e.g. "5.x-1.3", major = 1) and core
// (e.g. "5.1", major = 5) version strings.
$matches = array();
if (preg_match('/^(\d+\.x-)?(\d+)\..*$/', $info['version'], $matches)) {
$info['major'] = $matches[2];
}
elseif (!isset($info['major'])) {
// This would only happen for version strings that don't follow the
// drupal.org convention. We let contribs define "major" in their
// .info in this case, and only if that's missing would we hit this.
$info['major'] = -1;
}
}
else {
// No version info available at all.
$install_type = 'unknown';
$info['version'] = t('Unknown');
$info['major'] = -1;
}
// Finally, save the results we care about into the $projects array.
$projects[$key]['existing_version'] = $info['version'];
$projects[$key]['existing_major'] = $info['major'];
$projects[$key]['install_type'] = $install_type;
}
}
/**
* Calculates the current update status of all projects on the site.
*
* The results of this function are expensive to compute, especially on sites
* with lots of modules or themes, since it involves a lot of comparisons and
* other operations. Therefore, we cache the results into the {cache_update}
* table using the 'update_project_data' cache ID. However, since this is not
* the data about available updates fetched from the network, it is ok to
* invalidate it somewhat quickly. If we keep this data for very long, site
* administrators are more likely to see incorrect results if they upgrade to a
* newer version of a module or theme but do not visit certain pages that
* automatically clear this cache.
*
* @param array $available
* Data about available project releases.
*
* @return
* An array of installed projects with current update status information.
*
* @see update_get_available()
* @see update_get_projects()
* @see update_process_project_info()
* @see update_project_cache()
*/
function update_calculate_project_data($available) {
// Retrieve the projects from cache, if present.
$projects = update_project_cache('update_project_data');
// If $projects is empty, then the cache must be rebuilt.
// Otherwise, return the cached data and skip the rest of the function.
if (!empty($projects)) {
return $projects;
}
$projects = update_get_projects();
update_process_project_info($projects);
foreach ($projects as $project => $project_info) {
if (isset($available[$project])) {
update_calculate_project_update_status($project, $projects[$project], $available[$project]);
}
else {
$projects[$project]['status'] = UPDATE_UNKNOWN;
$projects[$project]['reason'] = t('No available releases found');
}
}
// Give other modules a chance to alter the status (for example, to allow a
// contrib module to provide fine-grained settings to ignore specific
// projects or releases).
drupal_alter('update_status', $projects);
// Cache the site's update status for at most 1 hour.
_update_cache_set('update_project_data', $projects, REQUEST_TIME + 3600);
return $projects;
}
/**
* Calculates the current update status of a specific project.
*
* This function is the heart of the update status feature. For each project it
* is invoked with, it first checks if the project has been flagged with a
* special status like "unsupported" or "insecure", or if the project node
* itself has been unpublished. In any of those cases, the project is marked
* with an error and the next project is considered.
*
* If the project itself is valid, the function decides what major release
* series to consider. The project defines what the currently supported major
* versions are for each version of core, so the first step is to make sure the
* current version is still supported. If so, that's the target version. If the
* current version is unsupported, the project maintainer's recommended major
* version is used. There's also a check to make sure that this function never
* recommends an earlier release than the currently installed major version.
*
* Given a target major version, the available releases are scanned looking for
* the specific release to recommend (avoiding beta releases and development
* snapshots if possible). For the target major version, the highest patch level
* is found. If there is a release at that patch level with no extra ("beta",
* etc.), then the release at that patch level with the most recent release date
* is recommended. If every release at that patch level has extra (only betas),
* then the latest release from the previous patch level is recommended. For
* example:
*
* - 1.6-bugfix <-- recommended version because 1.6 already exists.
* - 1.6
*
* or
*
* - 1.6-beta
* - 1.5 <-- recommended version because no 1.6 exists.
* - 1.4
*
* Also, the latest release from the same major version is looked for, even beta
* releases, to display to the user as the "Latest version" option.
* Additionally, the latest official release from any higher major versions that
* have been released is searched for to provide a set of "Also available"
* options.
*
* Finally, and most importantly, the release history continues to be scanned
* until the currently installed release is reached, searching for anything
* marked as a security update. If any security updates have been found between
* the recommended release and the installed version, all of the releases that
* included a security fix are recorded so that the site administrator can be
* warned their site is insecure, and links pointing to the release notes for
* each security update can be included (which, in turn, will link to the
* official security announcements for each vulnerability).
*
* This function relies on the fact that the .xml release history data comes
* sorted based on major version and patch level, then finally by release date
* if there are multiple releases such as betas from the same major.patch
* version (e.g., 5.x-1.5-beta1, 5.x-1.5-beta2, and 5.x-1.5). Development
* snapshots for a given major version are always listed last.
*
* @param $unused
* Input is not being used, but remains in function for API compatibility
* reasons.
* @param $project_data
* An array containing information about a specific project.
* @param $available
* Data about available project releases of a specific project.
*/
function update_calculate_project_update_status($unused, &$project_data, $available) {
foreach (array('title', 'link') as $attribute) {
if (!isset($project_data[$attribute]) && isset($available[$attribute])) {
$project_data[$attribute] = $available[$attribute];
}
}
// If the project status is marked as something bad, there's nothing else
// to consider.
if (isset($available['project_status'])) {
switch ($available['project_status']) {
case 'insecure':
$project_data['status'] = UPDATE_NOT_SECURE;
if (empty($project_data['extra'])) {
$project_data['extra'] = array();
}
$project_data['extra'][] = array(
'class' => array('project-not-secure'),
'label' => t('Project not secure'),
'data' => t('This project has been labeled insecure by the Drupal security team, and is no longer available for download. Immediately disabling everything included by this project is strongly recommended!'),
);
break;
case 'unpublished':
case 'revoked':
$project_data['status'] = UPDATE_REVOKED;
if (empty($project_data['extra'])) {
$project_data['extra'] = array();
}
$project_data['extra'][] = array(
'class' => array('project-revoked'),
'label' => t('Project revoked'),
'data' => t('This project has been revoked, and is no longer available for download. Disabling everything included by this project is strongly recommended!'),
);
break;
case 'unsupported':
$project_data['status'] = UPDATE_NOT_SUPPORTED;
if (empty($project_data['extra'])) {
$project_data['extra'] = array();
}
$project_data['extra'][] = array(
'class' => array('project-not-supported'),
'label' => t('Project not supported'),
'data' => t('This project is no longer supported, and is no longer available for download. Disabling everything included by this project is strongly recommended!'),
);
break;
case 'not-fetched':
$project_data['status'] = UPDATE_NOT_FETCHED;
$project_data['reason'] = t('Failed to get available update data.');
break;
default:
// Assume anything else (e.g. 'published') is valid and we should
// perform the rest of the logic in this function.
break;
}
}
if (!empty($project_data['status'])) {
// We already know the status for this project, so there's nothing else to
// compute. Record the project status into $project_data and we're done.
$project_data['project_status'] = $available['project_status'];
return;
}
// Figure out the target major version.
$existing_major = $project_data['existing_major'];
$supported_majors = array();
if (isset($available['supported_majors'])) {
$supported_majors = explode(',', $available['supported_majors']);
}
elseif (isset($available['default_major'])) {
// Older release history XML file without supported or recommended.
$supported_majors[] = $available['default_major'];
}
if (in_array($existing_major, $supported_majors)) {
// Still supported, stay at the current major version.
$target_major = $existing_major;
}
elseif (isset($available['recommended_major'])) {
// Since 'recommended_major' is defined, we know this is the new XML
// format. Therefore, we know the current release is unsupported since
// its major version was not in the 'supported_majors' list. We should
// find the best release from the recommended major version.
$target_major = $available['recommended_major'];
$project_data['status'] = UPDATE_NOT_SUPPORTED;
}
elseif (isset($available['default_major'])) {
// Older release history XML file without recommended, so recommend
// the currently defined "default_major" version.
$target_major = $available['default_major'];
}
else {
// Malformed XML file? Stick with the current version.
$target_major = $existing_major;
}
// Make sure we never tell the admin to downgrade. If we recommended an
// earlier version than the one they're running, they'd face an
// impossible data migration problem, since Drupal never supports a DB
// downgrade path. In the unfortunate case that what they're running is
// unsupported, and there's nothing newer for them to upgrade to, we
// can't print out a "Recommended version", but just have to tell them
// what they have is unsupported and let them figure it out.
$target_major = max($existing_major, $target_major);
$release_patch_changed = '';
$patch = '';
// If the project is marked as UPDATE_FETCH_PENDING, it means that the
// data we currently have (if any) is stale, and we've got a task queued
// up to (re)fetch the data. In that case, we mark it as such, merge in
// whatever data we have (e.g. project title and link), and move on.
if (!empty($available['fetch_status']) && $available['fetch_status'] == UPDATE_FETCH_PENDING) {
$project_data['status'] = UPDATE_FETCH_PENDING;
$project_data['reason'] = t('No available update data');
$project_data['fetch_status'] = $available['fetch_status'];
return;
}
// Defend ourselves from XML history files that contain no releases.
if (empty($available['releases'])) {
$project_data['status'] = UPDATE_UNKNOWN;
$project_data['reason'] = t('No available releases found');
return;
}
foreach ($available['releases'] as $version => $release) {
// First, if this is the existing release, check a few conditions.
if ($project_data['existing_version'] === $version) {
if (isset($release['terms']['Release type']) &&
in_array('Insecure', $release['terms']['Release type'])) {
$project_data['status'] = UPDATE_NOT_SECURE;
}
elseif ($release['status'] == 'unpublished') {
$project_data['status'] = UPDATE_REVOKED;
if (empty($project_data['extra'])) {
$project_data['extra'] = array();
}
$project_data['extra'][] = array(
'class' => array('release-revoked'),
'label' => t('Release revoked'),
'data' => t('Your currently installed release has been revoked, and is no longer available for download. Disabling everything included in this release or upgrading is strongly recommended!'),
);
}
elseif (isset($release['terms']['Release type']) &&
in_array('Unsupported', $release['terms']['Release type'])) {
$project_data['status'] = UPDATE_NOT_SUPPORTED;
if (empty($project_data['extra'])) {
$project_data['extra'] = array();
}
$project_data['extra'][] = array(
'class' => array('release-not-supported'),
'label' => t('Release not supported'),
'data' => t('Your currently installed release is now unsupported, and is no longer available for download. Disabling everything included in this release or upgrading is strongly recommended!'),
);
}
}
// Otherwise, ignore unpublished, insecure, or unsupported releases.
if ($release['status'] == 'unpublished' ||
(isset($release['terms']['Release type']) &&
(in_array('Insecure', $release['terms']['Release type']) ||
in_array('Unsupported', $release['terms']['Release type'])))) {
continue;
}
// See if this is a higher major version than our target and yet still
// supported. If so, record it as an "Also available" release.
// Note: some projects have a HEAD release from CVS days, which could
// be one of those being compared. They would not have version_major
// set, so we must call isset first.
if (isset($release['version_major']) && $release['version_major'] > $target_major) {
if (in_array($release['version_major'], $supported_majors)) {
if (!isset($project_data['also'])) {
$project_data['also'] = array();
}
if (!isset($project_data['also'][$release['version_major']])) {
$project_data['also'][$release['version_major']] = $version;
$project_data['releases'][$version] = $release;
}
}
// Otherwise, this release can't matter to us, since it's neither
// from the release series we're currently using nor the recommended
// release. We don't even care about security updates for this
// branch, since if a project maintainer puts out a security release
// at a higher major version and not at the lower major version,
// they must remove the lower version from the supported major
// versions at the same time, in which case we won't hit this code.
continue;
}
// Look for the 'latest version' if we haven't found it yet. Latest is
// defined as the most recent version for the target major version.
if (!isset($project_data['latest_version'])
&& $release['version_major'] == $target_major) {
$project_data['latest_version'] = $version;
$project_data['releases'][$version] = $release;
}
// Look for the development snapshot release for this branch.
if (!isset($project_data['dev_version'])
&& $release['version_major'] == $target_major
&& isset($release['version_extra'])
&& $release['version_extra'] == 'dev') {
$project_data['dev_version'] = $version;
$project_data['releases'][$version] = $release;
}
// Look for the 'recommended' version if we haven't found it yet (see
// phpdoc at the top of this function for the definition).
if (!isset($project_data['recommended'])
&& $release['version_major'] == $target_major
&& isset($release['version_patch'])) {
if ($patch != $release['version_patch']) {
$patch = $release['version_patch'];
$release_patch_changed = $release;
}
if (empty($release['version_extra']) && $patch == $release['version_patch']) {
$project_data['recommended'] = $release_patch_changed['version'];
$project_data['releases'][$release_patch_changed['version']] = $release_patch_changed;
}
}
// Stop searching once we hit the currently installed version.
if ($project_data['existing_version'] === $version) {
break;
}
// If we're running a dev snapshot and have a timestamp, stop
// searching for security updates once we hit an official release
// older than what we've got. Allow 100 seconds of leeway to handle
// differences between the datestamp in the .info file and the
// timestamp of the tarball itself (which are usually off by 1 or 2
// seconds) so that we don't flag that as a new release.
if ($project_data['install_type'] == 'dev') {
if (empty($project_data['datestamp'])) {
// We don't have current timestamp info, so we can't know.
continue;
}
elseif (isset($release['date']) && ($project_data['datestamp'] + 100 > $release['date'])) {
// We're newer than this, so we can skip it.
continue;
}
}
// See if this release is a security update.
if (isset($release['terms']['Release type'])
&& in_array('Security update', $release['terms']['Release type'])) {
$project_data['security updates'][] = $release;
}
}
// If we were unable to find a recommended version, then make the latest
// version the recommended version if possible.
if (!isset($project_data['recommended']) && isset($project_data['latest_version'])) {
$project_data['recommended'] = $project_data['latest_version'];
}
//
// Check to see if we need an update or not.
//
if (!empty($project_data['security updates'])) {
// If we found security updates, that always trumps any other status.
$project_data['status'] = UPDATE_NOT_SECURE;
}
if (isset($project_data['status'])) {
// If we already know the status, we're done.
return;
}
// If we don't know what to recommend, there's nothing we can report.
// Bail out early.
if (!isset($project_data['recommended'])) {
$project_data['status'] = UPDATE_UNKNOWN;
$project_data['reason'] = t('No available releases found');
return;
}
// If we're running a dev snapshot, compare the date of the dev snapshot
// with the latest official version, and record the absolute latest in
// 'latest_dev' so we can correctly decide if there's a newer release
// than our current snapshot.
if ($project_data['install_type'] == 'dev') {
if (isset($project_data['dev_version']) && $available['releases'][$project_data['dev_version']]['date'] > $available['releases'][$project_data['latest_version']]['date']) {
$project_data['latest_dev'] = $project_data['dev_version'];
}
else {
$project_data['latest_dev'] = $project_data['latest_version'];
}
}
// Figure out the status, based on what we've seen and the install type.
switch ($project_data['install_type']) {
case 'official':
if ($project_data['existing_version'] === $project_data['recommended'] || $project_data['existing_version'] === $project_data['latest_version']) {
$project_data['status'] = UPDATE_CURRENT;
}
else {
$project_data['status'] = UPDATE_NOT_CURRENT;
}
break;
case 'dev':
$latest = $available['releases'][$project_data['latest_dev']];
if (empty($project_data['datestamp'])) {
$project_data['status'] = UPDATE_NOT_CHECKED;
$project_data['reason'] = t('Unknown release date');
}
elseif (($project_data['datestamp'] + 100 > $latest['date'])) {
$project_data['status'] = UPDATE_CURRENT;
}
else {
$project_data['status'] = UPDATE_NOT_CURRENT;
}
break;
default:
$project_data['status'] = UPDATE_UNKNOWN;
$project_data['reason'] = t('Invalid info');
}
}
/**
* Retrieves data from {cache_update} or empties the cache when necessary.
*
* Two very expensive arrays computed by this module are the list of all
* installed modules and themes (and .info data, project associations, etc), and
* the current status of the site relative to the currently available releases.
* These two arrays are cached in the {cache_update} table and used whenever
* possible. The cache is cleared whenever the administrator visits the status
* report, available updates report, or the module or theme administration
* pages, since we should always recompute the most current values on any of
* those pages.
*
* Note: while both of these arrays are expensive to compute (in terms of disk
* I/O and some fairly heavy CPU processing), neither of these is the actual
* data about available updates that we have to fetch over the network from
* updates.drupal.org. That information is stored with the
* 'update_available_releases' cache ID -- it needs to persist longer than 1
* hour and never get invalidated just by visiting a page on the site.
*
* @param $cid
* The cache ID of data to return from the cache. Valid options are
* 'update_project_data' and 'update_project_projects'.
*
* @return
* The cached value of the $projects array generated by
* update_calculate_project_data() or update_get_projects(), or an empty array
* when the cache is cleared.
*/
function update_project_cache($cid) {
$projects = array();
// On certain paths, we should clear the cache and recompute the projects for
// update status of the site to avoid presenting stale information.
$q = $_GET['q'];
$paths = array(
'admin/modules',
'admin/modules/update',
'admin/appearance',
'admin/appearance/update',
'admin/reports',
'admin/reports/updates',
'admin/reports/updates/update',
'admin/reports/status',
'admin/reports/updates/check',
);
if (in_array($q, $paths)) {
_update_cache_clear($cid);
}
else {
$cache = _update_cache_get($cid);
if (!empty($cache->data) && $cache->expire > REQUEST_TIME) {
$projects = $cache->data;
}
}
return $projects;
}
/**
* Filters the project .info data to only save attributes we need.
*
* @param array $info
* Array of .info file data as returned by drupal_parse_info_file().
*
* @return
* Array of .info file data we need for the update manager.
*
* @see _update_process_info_list()
*/
function update_filter_project_info($info) {
$whitelist = array(
'_info_file_ctime',
'datestamp',
'major',
'name',
'package',
'project',
'project status url',
'version',
);
return array_intersect_key($info, drupal_map_assoc($whitelist));
}

135
modules/update/update.css Normal file
View file

@ -0,0 +1,135 @@
/**
* @file
* Styles used by the Update Manager module.
*/
.update .project {
font-weight: bold;
font-size: 110%;
padding-left: .25em; /* LTR */
height: 22px;
}
.update .version-status {
float: right; /* LTR */
padding-right: 10px; /* LTR */
font-size: 110%;
height: 20px;
}
.update .version-status .icon {
padding-left: .5em; /* LTR */
}
.update .version-date {
white-space: nowrap;
}
.update .info {
margin: 0;
padding: 1em 1em .25em 1em;
}
.update tr.even,
.update tr.odd {
border: none;
}
.update tr td {
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
.update tr.error {
background: #fcc;
}
.update tr.error .version-recommended {
background: #fdd;
}
.update tr.ok {
background: #dfd;
}
.update tr.warning {
background: #ffd;
}
.update tr.warning .version-recommended {
background: #ffe;
}
.current-version,
.new-version {
direction: ltr; /* Note: version numbers should always be LTR. */
}
.update tr.unknown {
background: #ddd;
}
table.update,
.update table.version {
width: 100%;
margin-top: .5em;
border: none;
}
.update table.version tbody {
border: none;
}
.update table.version tr,
.update table.version td {
line-height: .9em;
padding: 0;
margin: 0;
border: none;
background: none;
}
.update table.version .version-title {
padding-left: 1em; /* LTR */
width: 14em;
}
.update table.version .version-details {
padding-right: .5em; /* LTR */
}
.update table.version .version-links {
text-align: right; /* LTR */
padding-right: 1em; /* LTR */
}
.update table.version-security .version-title {
color: #970F00;
}
.update table.version-recommended-strong .version-title {
font-weight: bold;
}
.update .security-error {
font-weight: bold;
color: #970F00;
}
.update .check-manually {
padding-left: 1em; /* LTR */
}
.update-major-version-warning {
color: #ff0000;
}
table tbody tr.update-security,
table tbody tr.update-unsupported {
background: #fcc;
}
th.update-project-name {
width: 50%;
}

View file

@ -0,0 +1,427 @@
<?php
/**
* @file
* Code required only when fetching information about available updates.
*/
/**
* Page callback: Checks for updates and displays the update status report.
*
* Manually checks the update status without the use of cron.
*
* @see update_menu()
*/
function update_manual_status() {
_update_refresh();
$batch = array(
'operations' => array(
array('update_fetch_data_batch', array()),
),
'finished' => 'update_fetch_data_finished',
'title' => t('Checking available update data'),
'progress_message' => t('Trying to check available update data ...'),
'error_message' => t('Error checking available update data.'),
'file' => drupal_get_path('module', 'update') . '/update.fetch.inc',
);
batch_set($batch);
batch_process('admin/reports/updates');
}
/**
* Implements callback_batch_operation().
*
* Processes a step in batch for fetching available update data.
*
* @param $context
* Reference to an array used for Batch API storage.
*/
function update_fetch_data_batch(&$context) {
$queue = DrupalQueue::get('update_fetch_tasks');
if (empty($context['sandbox']['max'])) {
$context['finished'] = 0;
$context['sandbox']['max'] = $queue->numberOfItems();
$context['sandbox']['progress'] = 0;
$context['message'] = t('Checking available update data ...');
$context['results']['updated'] = 0;
$context['results']['failures'] = 0;
$context['results']['processed'] = 0;
}
// Grab another item from the fetch queue.
for ($i = 0; $i < 5; $i++) {
if ($item = $queue->claimItem()) {
if (_update_process_fetch_task($item->data)) {
$context['results']['updated']++;
$context['message'] = t('Checked available update data for %title.', array('%title' => $item->data['info']['name']));
}
else {
$context['message'] = t('Failed to check available update data for %title.', array('%title' => $item->data['info']['name']));
$context['results']['failures']++;
}
$context['sandbox']['progress']++;
$context['results']['processed']++;
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
$queue->deleteItem($item);
}
else {
// If the queue is currently empty, we're done. It's possible that
// another thread might have added new fetch tasks while we were
// processing this batch. In that case, the usual 'finished' math could
// get confused, since we'd end up processing more tasks that we thought
// we had when we started and initialized 'max' with numberOfItems(). By
// forcing 'finished' to be exactly 1 here, we ensure that batch
// processing is terminated.
$context['finished'] = 1;
return;
}
}
}
/**
* Implements callback_batch_finished().
*
* Performs actions when all fetch tasks have been completed.
*
* @param $success
* TRUE if the batch operation was successful; FALSE if there were errors.
* @param $results
* An associative array of results from the batch operation, including the key
* 'updated' which holds the total number of projects we fetched available
* update data for.
*/
function update_fetch_data_finished($success, $results) {
if ($success) {
if (!empty($results)) {
if (!empty($results['updated'])) {
drupal_set_message(format_plural($results['updated'], 'Checked available update data for one project.', 'Checked available update data for @count projects.'));
}
if (!empty($results['failures'])) {
drupal_set_message(format_plural($results['failures'], 'Failed to get available update data for one project.', 'Failed to get available update data for @count projects.'), 'error');
}
}
}
else {
drupal_set_message(t('An error occurred trying to get available update data.'), 'error');
}
}
/**
* Attempts to drain the queue of tasks for release history data to fetch.
*/
function _update_fetch_data() {
$queue = DrupalQueue::get('update_fetch_tasks');
$end = time() + variable_get('update_max_fetch_time', UPDATE_MAX_FETCH_TIME);
while (time() < $end && ($item = $queue->claimItem())) {
_update_process_fetch_task($item->data);
$queue->deleteItem($item);
}
}
/**
* Processes a task to fetch available update data for a single project.
*
* Once the release history XML data is downloaded, it is parsed and saved into
* the {cache_update} table in an entry just for that project.
*
* @param $project
* Associative array of information about the project to fetch data for.
*
* @return
* TRUE if we fetched parsable XML, otherwise FALSE.
*/
function _update_process_fetch_task($project) {
global $base_url;
$fail = &drupal_static(__FUNCTION__, array());
// This can be in the middle of a long-running batch, so REQUEST_TIME won't
// necessarily be valid.
$now = time();
if (empty($fail)) {
// If we have valid data about release history XML servers that we have
// failed to fetch from on previous attempts, load that from the cache.
if (($cache = _update_cache_get('fetch_failures')) && ($cache->expire > $now)) {
$fail = $cache->data;
}
}
$max_fetch_attempts = variable_get('update_max_fetch_attempts', UPDATE_MAX_FETCH_ATTEMPTS);
$success = FALSE;
$available = array();
$site_key = drupal_hmac_base64($base_url, drupal_get_private_key());
$url = _update_build_fetch_url($project, $site_key);
$fetch_url_base = _update_get_fetch_url_base($project);
$project_name = $project['name'];
if (empty($fail[$fetch_url_base]) || $fail[$fetch_url_base] < $max_fetch_attempts) {
$xml = drupal_http_request($url);
if (!isset($xml->error) && isset($xml->data)) {
$data = $xml->data;
}
}
if (!empty($data)) {
$available = update_parse_xml($data);
// @todo: Purge release data we don't need (http://drupal.org/node/238950).
if (!empty($available)) {
// Only if we fetched and parsed something sane do we return success.
$success = TRUE;
}
}
else {
$available['project_status'] = 'not-fetched';
if (empty($fail[$fetch_url_base])) {
$fail[$fetch_url_base] = 1;
}
else {
$fail[$fetch_url_base]++;
}
}
$frequency = variable_get('update_check_frequency', 1);
$cid = 'available_releases::' . $project_name;
_update_cache_set($cid, $available, $now + (60 * 60 * 24 * $frequency));
// Stash the $fail data back in the DB for the next 5 minutes.
_update_cache_set('fetch_failures', $fail, $now + (60 * 5));
// Whether this worked or not, we did just (try to) check for updates.
variable_set('update_last_check', $now);
// Now that we processed the fetch task for this project, clear out the
// record in {cache_update} for this task so we're willing to fetch again.
_update_cache_clear('fetch_task::' . $project_name);
return $success;
}
/**
* Clears out all the cached available update data and initiates re-fetching.
*/
function _update_refresh() {
module_load_include('inc', 'update', 'update.compare');
// Since we're fetching new available update data, we want to clear
// our cache of both the projects we care about, and the current update
// status of the site. We do *not* want to clear the cache of available
// releases just yet, since that data (even if it's stale) can be useful
// during update_get_projects(); for example, to modules that implement
// hook_system_info_alter() such as cvs_deploy.
_update_cache_clear('update_project_projects');
_update_cache_clear('update_project_data');
$projects = update_get_projects();
// Now that we have the list of projects, we should also clear our cache of
// available release data, since even if we fail to fetch new data, we need
// to clear out the stale data at this point.
_update_cache_clear('available_releases::', TRUE);
foreach ($projects as $key => $project) {
update_create_fetch_task($project);
}
}
/**
* Adds a task to the queue for fetching release history data for a project.
*
* We only create a new fetch task if there's no task already in the queue for
* this particular project (based on 'fetch_task::' entries in the
* {cache_update} table).
*
* @param $project
* Associative array of information about a project as created by
* update_get_projects(), including keys such as 'name' (short name), and the
* 'info' array with data from a .info file for the project.
*
* @see update_get_projects()
* @see update_get_available()
* @see update_refresh()
* @see update_fetch_data()
* @see _update_process_fetch_task()
*/
function _update_create_fetch_task($project) {
$fetch_tasks = &drupal_static(__FUNCTION__, array());
if (empty($fetch_tasks)) {
$fetch_tasks = _update_get_cache_multiple('fetch_task');
}
$cid = 'fetch_task::' . $project['name'];
if (empty($fetch_tasks[$cid])) {
$queue = DrupalQueue::get('update_fetch_tasks');
$queue->createItem($project);
// Due to race conditions, it is possible that another process already
// inserted a row into the {cache_update} table and the following query will
// throw an exception.
// @todo: Remove the need for the manual check by relying on a queue that
// enforces unique items.
try {
db_insert('cache_update')
->fields(array(
'cid' => $cid,
'created' => REQUEST_TIME,
))
->execute();
}
catch (Exception $e) {
// The exception can be ignored safely.
}
$fetch_tasks[$cid] = REQUEST_TIME;
}
}
/**
* Generates the URL to fetch information about project updates.
*
* This figures out the right URL to use, based on the project's .info file and
* the global defaults. Appends optional query arguments when the site is
* configured to report usage stats.
*
* @param $project
* The array of project information from update_get_projects().
* @param $site_key
* (optional) The anonymous site key hash. Defaults to an empty string.
*
* @return
* The URL for fetching information about updates to the specified project.
*
* @see update_fetch_data()
* @see _update_process_fetch_task()
* @see update_get_projects()
*/
function _update_build_fetch_url($project, $site_key = '') {
$name = $project['name'];
$url = _update_get_fetch_url_base($project);
$url .= '/' . $name . '/' . DRUPAL_CORE_COMPATIBILITY;
// Only append usage information if we have a site key and the project is
// enabled. We do not want to record usage statistics for disabled projects.
if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
// Append the site key.
$url .= (strpos($url, '?') !== FALSE) ? '&' : '?';
$url .= 'site_key=';
$url .= rawurlencode($site_key);
// Append the version.
if (!empty($project['info']['version'])) {
$url .= '&version=';
$url .= rawurlencode($project['info']['version']);
}
// Append the list of modules or themes enabled.
$list = array_keys($project['includes']);
$url .= '&list=';
$url .= rawurlencode(implode(',', $list));
}
return $url;
}
/**
* Returns the base of the URL to fetch available update data for a project.
*
* @param $project
* The array of project information from update_get_projects().
*
* @return
* The base of the URL used for fetching available update data. This does
* not include the path elements to specify a particular project, version,
* site_key, etc.
*
* @see _update_build_fetch_url()
*/
function _update_get_fetch_url_base($project) {
return isset($project['info']['project status url']) ? $project['info']['project status url'] : variable_get('update_fetch_url', UPDATE_DEFAULT_URL);
}
/**
* Performs any notifications that should be done once cron fetches new data.
*
* This method checks the status of the site using the new data and, depending
* on the configuration of the site, notifies administrators via e-mail if there
* are new releases or missing security updates.
*
* @see update_requirements()
*/
function _update_cron_notify() {
module_load_install('update');
$status = update_requirements('runtime');
$params = array();
$notify_all = (variable_get('update_notification_threshold', 'all') == 'all');
foreach (array('core', 'contrib') as $report_type) {
$type = 'update_' . $report_type;
if (isset($status[$type]['severity'])
&& ($status[$type]['severity'] == REQUIREMENT_ERROR || ($notify_all && $status[$type]['reason'] == UPDATE_NOT_CURRENT))) {
$params[$report_type] = $status[$type]['reason'];
}
}
if (!empty($params)) {
$notify_list = variable_get('update_notify_emails', '');
if (!empty($notify_list)) {
$default_language = language_default();
foreach ($notify_list as $target) {
if ($target_user = user_load_by_mail($target)) {
$target_language = user_preferred_language($target_user);
}
else {
$target_language = $default_language;
}
$message = drupal_mail('update', 'status_notify', $target, $target_language, $params);
// Track when the last mail was successfully sent to avoid sending
// too many e-mails.
if ($message['result']) {
variable_set('update_last_email_notification', REQUEST_TIME);
}
}
}
}
}
/**
* Parses the XML of the Drupal release history info files.
*
* @param $raw_xml
* A raw XML string of available release data for a given project.
*
* @return
* Array of parsed data about releases for a given project, or NULL if there
* was an error parsing the string.
*/
function update_parse_xml($raw_xml) {
try {
$xml = new SimpleXMLElement($raw_xml);
}
catch (Exception $e) {
// SimpleXMLElement::__construct produces an E_WARNING error message for
// each error found in the XML data and throws an exception if errors
// were detected. Catch any exception and return failure (NULL).
return;
}
// If there is no valid project data, the XML is invalid, so return failure.
if (!isset($xml->short_name)) {
return;
}
$short_name = (string) $xml->short_name;
$data = array();
foreach ($xml as $k => $v) {
$data[$k] = (string) $v;
}
$data['releases'] = array();
if (isset($xml->releases)) {
foreach ($xml->releases->children() as $release) {
$version = (string) $release->version;
$data['releases'][$version] = array();
foreach ($release->children() as $k => $v) {
$data['releases'][$version][$k] = (string) $v;
}
$data['releases'][$version]['terms'] = array();
if ($release->terms) {
foreach ($release->terms->children() as $term) {
if (!isset($data['releases'][$version]['terms'][(string) $term->name])) {
$data['releases'][$version]['terms'][(string) $term->name] = array();
}
$data['releases'][$version]['terms'][(string) $term->name][] = (string) $term->value;
}
}
}
}
return $data;
}

View file

@ -0,0 +1,13 @@
name = Update manager
description = Checks for available updates, and can securely install or update modules and themes via a web interface.
version = VERSION
package = Core
core = 7.x
files[] = update.test
configure = admin/reports/updates/settings
; Information added by Drupal.org packaging script on 2017-06-21
version = "7.56"
project = "drupal"
datestamp = "1498069849"

View file

@ -0,0 +1,190 @@
<?php
/**
* @file
* Install, update, and uninstall functions for the Update Manager module.
*/
/**
* Implements hook_requirements().
*
* @return
* An array describing the status of the site regarding available updates. If
* there is no update data, only one record will be returned, indicating that
* the status of core can't be determined. If data is available, there will be
* two records: one for core, and another for all of contrib (assuming there
* are any contributed modules or themes enabled on the site). In addition to
* the fields expected by hook_requirements ('value', 'severity', and
* optionally 'description'), this array will contain a 'reason' attribute,
* which is an integer constant to indicate why the given status is being
* returned (UPDATE_NOT_SECURE, UPDATE_NOT_CURRENT, or UPDATE_UNKNOWN). This
* is used for generating the appropriate e-mail notification messages during
* update_cron(), and might be useful for other modules that invoke
* update_requirements() to find out if the site is up to date or not.
*
* @see _update_message_text()
* @see _update_cron_notify()
*/
function update_requirements($phase) {
$requirements = array();
if ($phase == 'runtime') {
if ($available = update_get_available(FALSE)) {
module_load_include('inc', 'update', 'update.compare');
$data = update_calculate_project_data($available);
// First, populate the requirements for core:
$requirements['update_core'] = _update_requirement_check($data['drupal'], 'core');
// We don't want to check drupal a second time.
unset($data['drupal']);
if (!empty($data)) {
// Now, sort our $data array based on each project's status. The
// status constants are numbered in the right order of precedence, so
// we just need to make sure the projects are sorted in ascending
// order of status, and we can look at the first project we find.
uasort($data, '_update_project_status_sort');
$first_project = reset($data);
$requirements['update_contrib'] = _update_requirement_check($first_project, 'contrib');
}
}
else {
$requirements['update_core']['title'] = t('Drupal core update status');
$requirements['update_core']['value'] = t('No update data available');
$requirements['update_core']['severity'] = REQUIREMENT_WARNING;
$requirements['update_core']['reason'] = UPDATE_UNKNOWN;
$requirements['update_core']['description'] = _update_no_data();
}
}
return $requirements;
}
/**
* Implements hook_schema().
*/
function update_schema() {
$schema['cache_update'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_update']['description'] = 'Cache table for the Update module to store information about available releases, fetched from central server.';
return $schema;
}
/**
* Implements hook_install().
*/
function update_install() {
$queue = DrupalQueue::get('update_fetch_tasks', TRUE);
$queue->createQueue();
}
/**
* Implements hook_uninstall().
*/
function update_uninstall() {
// Clear any variables that might be in use
$variables = array(
'update_check_frequency',
'update_fetch_url',
'update_last_check',
'update_last_email_notification',
'update_notification_threshold',
'update_notify_emails',
'update_max_fetch_attempts',
'update_max_fetch_time',
);
foreach ($variables as $variable) {
variable_del($variable);
}
$queue = DrupalQueue::get('update_fetch_tasks');
$queue->deleteQueue();
}
/**
* Fills in the requirements array.
*
* This is shared for both core and contrib to generate the right elements in
* the array for hook_requirements().
*
* @param $project
* Array of information about the project we're testing as returned by
* update_calculate_project_data().
* @param $type
* What kind of project this is ('core' or 'contrib').
*
* @return
* An array to be included in the nested $requirements array.
*
* @see hook_requirements()
* @see update_requirements()
* @see update_calculate_project_data()
*/
function _update_requirement_check($project, $type) {
$requirement = array();
if ($type == 'core') {
$requirement['title'] = t('Drupal core update status');
}
else {
$requirement['title'] = t('Module and theme update status');
}
$status = $project['status'];
if ($status != UPDATE_CURRENT) {
$requirement['reason'] = $status;
$requirement['description'] = _update_message_text($type, $status, TRUE);
$requirement['severity'] = REQUIREMENT_ERROR;
}
switch ($status) {
case UPDATE_NOT_SECURE:
$requirement_label = t('Not secure!');
break;
case UPDATE_REVOKED:
$requirement_label = t('Revoked!');
break;
case UPDATE_NOT_SUPPORTED:
$requirement_label = t('Unsupported release');
break;
case UPDATE_NOT_CURRENT:
$requirement_label = t('Out of date');
$requirement['severity'] = REQUIREMENT_WARNING;
break;
case UPDATE_UNKNOWN:
case UPDATE_NOT_CHECKED:
case UPDATE_NOT_FETCHED:
$requirement_label = isset($project['reason']) ? $project['reason'] : t('Can not determine status');
$requirement['severity'] = REQUIREMENT_WARNING;
break;
default:
$requirement_label = t('Up to date');
}
if ($status != UPDATE_CURRENT && $type == 'core' && isset($project['recommended'])) {
$requirement_label .= ' ' . t('(version @version available)', array('@version' => $project['recommended']));
}
$requirement['value'] = l($requirement_label, update_manager_access() ? 'admin/reports/updates/update' : 'admin/reports/updates');
return $requirement;
}
/**
* @addtogroup updates-6.x-to-7.x
* @{
*/
/**
* Create a queue to store tasks for requests to fetch available update data.
*/
function update_update_7000() {
module_load_include('inc', 'system', 'system.queue');
$queue = DrupalQueue::get('update_fetch_tasks');
$queue->createQueue();
}
/**
* Recreates cache_update table.
*
* Converts fields that hold serialized variables from text to blob.
* Removes 'headers' column.
*/
function update_update_7001() {
$schema = system_schema_cache_7054();
db_drop_table('cache_update');
db_create_table('cache_update', $schema);
}
/**
* @} End of "addtogroup updates-6.x-to-7.x".
*/

View file

@ -0,0 +1,947 @@
<?php
/**
* @file
* Administrative screens and processing functions of the Update Manager module.
*
* This allows site administrators with the 'administer software updates'
* permission to either upgrade existing projects, or download and install new
* ones, so long as the killswitch setting ('allow_authorize_operations') is
* still TRUE.
*
* To install new code, the administrator is prompted for either the URL of an
* archive file, or to directly upload the archive file. The archive is loaded
* into a temporary location, extracted, and verified. If everything is
* successful, the user is redirected to authorize.php to type in file transfer
* credentials and authorize the installation to proceed with elevated
* privileges, such that the extracted files can be copied out of the temporary
* location and into the live web root.
*
* Updating existing code is a more elaborate process. The first step is a
* selection form where the user is presented with a table of installed projects
* that are missing newer releases. The user selects which projects they wish to
* update, and presses the "Download updates" button to continue. This sets up a
* batch to fetch all the selected releases, and redirects to
* admin/update/download to display the batch progress bar as it runs. Each
* batch operation is responsible for downloading a single file, extracting the
* archive, and verifying the contents. If there are any errors, the user is
* redirected back to the first page with the error messages. If all downloads
* were extacted and verified, the user is instead redirected to
* admin/update/ready, a landing page which reminds them to backup their
* database and asks if they want to put the site offline during the update.
* Once the user presses the "Install updates" button, they are redirected to
* authorize.php to supply their web root file access credentials. The
* authorized operation (which lives in update.authorize.inc) sets up a batch to
* copy each extracted update from the temporary location into the live web
* root.
*/
/**
* @defgroup update_manager_update Update Manager module: update
* @{
* Update Manager module functionality for updating existing code.
*
* Provides a user interface to update existing code.
*/
/**
* Form constructor for the update form of the Update Manager module.
*
* This presents a table with all projects that have available updates with
* checkboxes to select which ones to upgrade.
*
* @param $context
* String representing the context from which we're trying to update.
* Allowed values are 'module', 'theme', and 'report'.
*
* @see update_manager_update_form_validate()
* @see update_manager_update_form_submit()
* @see update_menu()
* @ingroup forms
*/
function update_manager_update_form($form, $form_state, $context) {
if (!_update_manager_check_backends($form, 'update')) {
return $form;
}
$form['#theme'] = 'update_manager_update_form';
$available = update_get_available(TRUE);
if (empty($available)) {
$form['message'] = array(
'#markup' => t('There was a problem getting update information. Try again later.'),
);
return $form;
}
$form['#attached']['css'][] = drupal_get_path('module', 'update') . '/update.css';
// This will be a nested array. The first key is the kind of project, which
// can be either 'enabled', 'disabled', 'manual' (projects which require
// manual updates, such as core). Then, each subarray is an array of
// projects of that type, indexed by project short name, and containing an
// array of data for cells in that project's row in the appropriate table.
$projects = array();
// This stores the actual download link we're going to update from for each
// project in the form, regardless of if it's enabled or disabled.
$form['project_downloads'] = array('#tree' => TRUE);
module_load_include('inc', 'update', 'update.compare');
$project_data = update_calculate_project_data($available);
foreach ($project_data as $name => $project) {
// Filter out projects which are up to date already.
if ($project['status'] == UPDATE_CURRENT) {
continue;
}
// The project name to display can vary based on the info we have.
if (!empty($project['title'])) {
if (!empty($project['link'])) {
$project_name = l($project['title'], $project['link']);
}
else {
$project_name = check_plain($project['title']);
}
}
elseif (!empty($project['info']['name'])) {
$project_name = check_plain($project['info']['name']);
}
else {
$project_name = check_plain($name);
}
if ($project['project_type'] == 'theme' || $project['project_type'] == 'theme-disabled') {
$project_name .= ' ' . t('(Theme)');
}
if (empty($project['recommended'])) {
// If we don't know what to recommend they upgrade to, we should skip
// the project entirely.
continue;
}
$recommended_release = $project['releases'][$project['recommended']];
$recommended_version = $recommended_release['version'] . ' ' . l(t('(Release notes)'), $recommended_release['release_link'], array('attributes' => array('title' => t('Release notes for @project_title', array('@project_title' => $project['title'])))));
if ($recommended_release['version_major'] != $project['existing_major']) {
$recommended_version .= '<div title="Major upgrade warning" class="update-major-version-warning">' . t('This update is a major version update which means that it may not be backwards compatible with your currently running version. It is recommended that you read the release notes and proceed at your own risk.') . '</div>';
}
// Create an entry for this project.
$entry = array(
'title' => $project_name,
'installed_version' => $project['existing_version'],
'recommended_version' => $recommended_version,
);
switch ($project['status']) {
case UPDATE_NOT_SECURE:
case UPDATE_REVOKED:
$entry['title'] .= ' ' . t('(Security update)');
$entry['#weight'] = -2;
$type = 'security';
break;
case UPDATE_NOT_SUPPORTED:
$type = 'unsupported';
$entry['title'] .= ' ' . t('(Unsupported)');
$entry['#weight'] = -1;
break;
case UPDATE_UNKNOWN:
case UPDATE_NOT_FETCHED:
case UPDATE_NOT_CHECKED:
case UPDATE_NOT_CURRENT:
$type = 'recommended';
break;
default:
// Jump out of the switch and onto the next project in foreach.
continue 2;
}
$entry['#attributes'] = array('class' => array('update-' . $type));
// Drupal core needs to be upgraded manually.
$needs_manual = $project['project_type'] == 'core';
if ($needs_manual) {
// There are no checkboxes in the 'Manual updates' table so it will be
// rendered by theme('table'), not theme('tableselect'). Since the data
// formats are incompatible, we convert now to the format expected by
// theme('table').
unset($entry['#weight']);
$attributes = $entry['#attributes'];
unset($entry['#attributes']);
$entry = array(
'data' => $entry,
) + $attributes;
}
else {
$form['project_downloads'][$name] = array(
'#type' => 'value',
'#value' => $recommended_release['download_link'],
);
}
// Based on what kind of project this is, save the entry into the
// appropriate subarray.
switch ($project['project_type']) {
case 'core':
// Core needs manual updates at this time.
$projects['manual'][$name] = $entry;
break;
case 'module':
case 'theme':
$projects['enabled'][$name] = $entry;
break;
case 'module-disabled':
case 'theme-disabled':
$projects['disabled'][$name] = $entry;
break;
}
}
if (empty($projects)) {
$form['message'] = array(
'#markup' => t('All of your projects are up to date.'),
);
return $form;
}
$headers = array(
'title' => array(
'data' => t('Name'),
'class' => array('update-project-name'),
),
'installed_version' => t('Installed version'),
'recommended_version' => t('Recommended version'),
);
if (!empty($projects['enabled'])) {
$form['projects'] = array(
'#type' => 'tableselect',
'#header' => $headers,
'#options' => $projects['enabled'],
);
if (!empty($projects['disabled'])) {
$form['projects']['#prefix'] = '<h2>' . t('Enabled') . '</h2>';
}
}
if (!empty($projects['disabled'])) {
$form['disabled_projects'] = array(
'#type' => 'tableselect',
'#header' => $headers,
'#options' => $projects['disabled'],
'#weight' => 1,
'#prefix' => '<h2>' . t('Disabled') . '</h2>',
);
}
// If either table has been printed yet, we need a submit button and to
// validate the checkboxes.
if (!empty($projects['enabled']) || !empty($projects['disabled'])) {
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Download these updates'),
);
$form['#validate'][] = 'update_manager_update_form_validate';
}
if (!empty($projects['manual'])) {
$prefix = '<h2>' . t('Manual updates required') . '</h2>';
$prefix .= '<p>' . t('Updates of Drupal core are not supported at this time.') . '</p>';
$form['manual_updates'] = array(
'#type' => 'markup',
'#markup' => theme('table', array('header' => $headers, 'rows' => $projects['manual'])),
'#prefix' => $prefix,
'#weight' => 120,
);
}
return $form;
}
/**
* Returns HTML for the first page in the process of updating projects.
*
* @param $variables
* An associative array containing:
* - form: A render element representing the form.
*
* @ingroup themeable
*/
function theme_update_manager_update_form($variables) {
$form = $variables['form'];
$last = variable_get('update_last_check', 0);
$output = theme('update_last_check', array('last' => $last));
$output .= drupal_render_children($form);
return $output;
}
/**
* Form validation handler for update_manager_update_form().
*
* Ensures that at least one project is selected.
*
* @see update_manager_update_form_submit()
*/
function update_manager_update_form_validate($form, &$form_state) {
if (!empty($form_state['values']['projects'])) {
$enabled = array_filter($form_state['values']['projects']);
}
if (!empty($form_state['values']['disabled_projects'])) {
$disabled = array_filter($form_state['values']['disabled_projects']);
}
if (empty($enabled) && empty($disabled)) {
form_set_error('projects', t('You must select at least one project to update.'));
}
}
/**
* Form submission handler for update_manager_update_form().
*
* Sets up a batch that downloads, extracts, and verifies the selected releases.
*
* @see update_manager_update_form_validate()
*/
function update_manager_update_form_submit($form, &$form_state) {
$projects = array();
foreach (array('projects', 'disabled_projects') as $type) {
if (!empty($form_state['values'][$type])) {
$projects = array_merge($projects, array_keys(array_filter($form_state['values'][$type])));
}
}
$operations = array();
foreach ($projects as $project) {
$operations[] = array(
'update_manager_batch_project_get',
array(
$project,
$form_state['values']['project_downloads'][$project],
),
);
}
$batch = array(
'title' => t('Downloading updates'),
'init_message' => t('Preparing to download selected updates'),
'operations' => $operations,
'finished' => 'update_manager_download_batch_finished',
'file' => drupal_get_path('module', 'update') . '/update.manager.inc',
);
batch_set($batch);
}
/**
* Implements callback_batch_finished().
*
* Batch callback: Performs actions when the download batch is completed.
*
* @param $success
* TRUE if the batch operation was successful, FALSE if there were errors.
* @param $results
* An associative array of results from the batch operation.
*/
function update_manager_download_batch_finished($success, $results) {
if (!empty($results['errors'])) {
$error_list = array(
'title' => t('Downloading updates failed:'),
'items' => $results['errors'],
);
drupal_set_message(theme('item_list', $error_list), 'error');
}
elseif ($success) {
drupal_set_message(t('Updates downloaded successfully.'));
$_SESSION['update_manager_update_projects'] = $results['projects'];
drupal_goto('admin/update/ready');
}
else {
// Ideally we're catching all Exceptions, so they should never see this,
// but just in case, we have to tell them something.
drupal_set_message(t('Fatal error trying to download.'), 'error');
}
}
/**
* Form constructor for the update ready form.
*
* Build the form when the site is ready to update (after downloading).
*
* This form is an intermediary step in the automated update workflow. It is
* presented to the site administrator after all the required updates have been
* downloaded and verified. The point of this page is to encourage the user to
* backup their site, give them the opportunity to put the site offline, and
* then ask them to confirm that the update should continue. After this step,
* the user is redirected to authorize.php to enter their file transfer
* credentials and attempt to complete the update.
*
* @see update_manager_update_ready_form_submit()
* @see update_menu()
* @ingroup forms
*/
function update_manager_update_ready_form($form, &$form_state) {
if (!_update_manager_check_backends($form, 'update')) {
return $form;
}
$form['backup'] = array(
'#prefix' => '<strong>',
'#markup' => t('Back up your database and site before you continue. <a href="@backup_url">Learn how</a>.', array('@backup_url' => url('http://drupal.org/node/22281'))),
'#suffix' => '</strong>',
);
$form['maintenance_mode'] = array(
'#title' => t('Perform updates with site in maintenance mode (strongly recommended)'),
'#type' => 'checkbox',
'#default_value' => TRUE,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Continue'),
);
return $form;
}
/**
* Form submission handler for update_manager_update_ready_form().
*
* If the site administrator requested that the site is put offline during the
* update, do so now. Otherwise, pull information about all the required updates
* out of the SESSION, figure out what Drupal\Core\Updater\Updater class is
* needed for each one, generate an array of update operations to perform, and
* hand it all off to system_authorized_init(), then redirect to authorize.php.
*
* @see update_authorize_run_update()
* @see system_authorized_init()
* @see system_authorized_get_url()
*/
function update_manager_update_ready_form_submit($form, &$form_state) {
// Store maintenance_mode setting so we can restore it when done.
$_SESSION['maintenance_mode'] = variable_get('maintenance_mode', FALSE);
if ($form_state['values']['maintenance_mode'] == TRUE) {
variable_set('maintenance_mode', TRUE);
}
if (!empty($_SESSION['update_manager_update_projects'])) {
// Make sure the Updater registry is loaded.
drupal_get_updaters();
$updates = array();
$directory = _update_manager_extract_directory();
$projects = $_SESSION['update_manager_update_projects'];
unset($_SESSION['update_manager_update_projects']);
foreach ($projects as $project => $url) {
$project_location = $directory . '/' . $project;
$updater = Updater::factory($project_location);
$project_real_location = drupal_realpath($project_location);
$updates[] = array(
'project' => $project,
'updater_name' => get_class($updater),
'local_url' => $project_real_location,
);
}
// If the owner of the last directory we extracted is the same as the
// owner of our configuration directory (e.g. sites/default) where we're
// trying to install the code, there's no need to prompt for FTP/SSH
// credentials. Instead, we instantiate a FileTransferLocal and invoke
// update_authorize_run_update() directly.
if (fileowner($project_real_location) == fileowner(conf_path())) {
module_load_include('inc', 'update', 'update.authorize');
$filetransfer = new FileTransferLocal(DRUPAL_ROOT);
update_authorize_run_update($filetransfer, $updates);
}
// Otherwise, go through the regular workflow to prompt for FTP/SSH
// credentials and invoke update_authorize_run_update() indirectly with
// whatever FileTransfer object authorize.php creates for us.
else {
system_authorized_init('update_authorize_run_update', drupal_get_path('module', 'update') . '/update.authorize.inc', array($updates), t('Update manager'));
$form_state['redirect'] = system_authorized_get_url();
}
}
}
/**
* @} End of "defgroup update_manager_update".
*/
/**
* @defgroup update_manager_install Update Manager module: install
* @{
* Update Manager module functionality for installing new code.
*
* Provides a user interface to install new code.
*/
/**
* Form constructor for the install form of the Update Manager module.
*
* This presents a place to enter a URL or upload an archive file to use to
* install a new module or theme.
*
* @param $context
* String representing the context from which we're trying to install.
* Allowed values are 'module', 'theme', and 'report'.
*
* @see update_manager_install_form_validate()
* @see update_manager_install_form_submit()
* @see update_menu()
* @ingroup forms
*/
function update_manager_install_form($form, &$form_state, $context) {
if (!_update_manager_check_backends($form, 'install')) {
return $form;
}
$form['help_text'] = array(
'#prefix' => '<p>',
'#markup' => t('You can find <a href="@module_url">modules</a> and <a href="@theme_url">themes</a> on <a href="@drupal_org_url">drupal.org</a>. The following file extensions are supported: %extensions.', array(
'@module_url' => 'http://drupal.org/project/modules',
'@theme_url' => 'http://drupal.org/project/themes',
'@drupal_org_url' => 'http://drupal.org',
'%extensions' => archiver_get_extensions(),
)),
'#suffix' => '</p>',
);
$form['project_url'] = array(
'#type' => 'textfield',
'#title' => t('Install from a URL'),
'#description' => t('For example: %url', array('%url' => 'http://ftp.drupal.org/files/projects/name.tar.gz')),
);
$form['information'] = array(
'#prefix' => '<strong>',
'#markup' => t('Or'),
'#suffix' => '</strong>',
);
$form['project_upload'] = array(
'#type' => 'file',
'#title' => t('Upload a module or theme archive to install'),
'#description' => t('For example: %filename from your local computer', array('%filename' => 'name.tar.gz')),
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Install'),
);
return $form;
}
/**
* Checks for file transfer backends and prepares a form fragment about them.
*
* @param array $form
* Reference to the form array we're building.
* @param string $operation
* The update manager operation we're in the middle of. Can be either 'update'
* or 'install'. Use to provide operation-specific interface text.
*
* @return
* TRUE if the update manager should continue to the next step in the
* workflow, or FALSE if we've hit a fatal configuration and must halt the
* workflow.
*/
function _update_manager_check_backends(&$form, $operation) {
// If file transfers will be performed locally, we do not need to display any
// warnings or notices to the user and should automatically continue the
// workflow, since we won't be using a FileTransfer backend that requires
// user input or a specific server configuration.
if (update_manager_local_transfers_allowed()) {
return TRUE;
}
// Otherwise, show the available backends.
$form['available_backends'] = array(
'#prefix' => '<p>',
'#suffix' => '</p>',
);
$available_backends = drupal_get_filetransfer_info();
if (empty($available_backends)) {
if ($operation == 'update') {
$form['available_backends']['#markup'] = t('Your server does not support updating modules and themes from this interface. Instead, update modules and themes by uploading the new versions directly to the server, as described in the <a href="@handbook_url">handbook</a>.', array('@handbook_url' => 'http://drupal.org/getting-started/install-contrib'));
}
else {
$form['available_backends']['#markup'] = t('Your server does not support installing modules and themes from this interface. Instead, install modules and themes by uploading them directly to the server, as described in the <a href="@handbook_url">handbook</a>.', array('@handbook_url' => 'http://drupal.org/getting-started/install-contrib'));
}
return FALSE;
}
$backend_names = array();
foreach ($available_backends as $backend) {
$backend_names[] = $backend['title'];
}
if ($operation == 'update') {
$form['available_backends']['#markup'] = format_plural(
count($available_backends),
'Updating modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other update methods.',
'Updating modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See the <a href="@handbook_url">handbook</a> for other update methods.',
array(
'@backends' => implode(', ', $backend_names),
'@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
));
}
else {
$form['available_backends']['#markup'] = format_plural(
count($available_backends),
'Installing modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other installation methods.',
'Installing modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See the <a href="@handbook_url">handbook</a> for other installation methods.',
array(
'@backends' => implode(', ', $backend_names),
'@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
));
}
return TRUE;
}
/**
* Form validation handler for update_manager_install_form().
*
* @see update_manager_install_form_submit()
*/
function update_manager_install_form_validate($form, &$form_state) {
if (!($form_state['values']['project_url'] XOR !empty($_FILES['files']['name']['project_upload']))) {
form_set_error('project_url', t('You must either provide a URL or upload an archive file to install.'));
}
if ($form_state['values']['project_url']) {
if (!valid_url($form_state['values']['project_url'], TRUE)) {
form_set_error('project_url', t('The provided URL is invalid.'));
}
}
}
/**
* Form submission handler for update_manager_install_form().
*
* Either downloads the file specified in the URL to a temporary cache, or
* uploads the file attached to the form, then attempts to extract the archive
* into a temporary location and verify it. Instantiate the appropriate
* Updater class for this project and make sure it is not already installed in
* the live webroot. If everything is successful, setup an operation to run
* via authorize.php which will copy the extracted files from the temporary
* location into the live site.
*
* @see update_manager_install_form_validate()
* @see update_authorize_run_install()
* @see system_authorized_init()
* @see system_authorized_get_url()
*/
function update_manager_install_form_submit($form, &$form_state) {
if ($form_state['values']['project_url']) {
$field = 'project_url';
$local_cache = update_manager_file_get($form_state['values']['project_url']);
if (!$local_cache) {
form_set_error($field, t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state['values']['project_url'])));
return;
}
}
elseif ($_FILES['files']['name']['project_upload']) {
$validators = array('file_validate_extensions' => array(archiver_get_extensions()));
$field = 'project_upload';
if (!($finfo = file_save_upload($field, $validators, NULL, FILE_EXISTS_REPLACE))) {
// Failed to upload the file. file_save_upload() calls form_set_error() on
// failure.
return;
}
$local_cache = $finfo->uri;
}
$directory = _update_manager_extract_directory();
try {
$archive = update_manager_archive_extract($local_cache, $directory);
}
catch (Exception $e) {
form_set_error($field, $e->getMessage());
return;
}
$files = $archive->listContents();
if (!$files) {
form_set_error($field, t('Provided archive contains no files.'));
return;
}
// Unfortunately, we can only use the directory name to determine the project
// name. Some archivers list the first file as the directory (i.e., MODULE/)
// and others list an actual file (i.e., MODULE/README.TXT).
$project = strtok($files[0], '/\\');
$archive_errors = update_manager_archive_verify($project, $local_cache, $directory);
if (!empty($archive_errors)) {
form_set_error($field, array_shift($archive_errors));
// @todo: Fix me in D8: We need a way to set multiple errors on the same
// form element and have all of them appear!
if (!empty($archive_errors)) {
foreach ($archive_errors as $error) {
drupal_set_message($error, 'error');
}
}
return;
}
// Make sure the Updater registry is loaded.
drupal_get_updaters();
$project_location = $directory . '/' . $project;
try {
$updater = Updater::factory($project_location);
}
catch (Exception $e) {
form_set_error($field, $e->getMessage());
return;
}
try {
$project_title = Updater::getProjectTitle($project_location);
}
catch (Exception $e) {
form_set_error($field, $e->getMessage());
return;
}
if (!$project_title) {
form_set_error($field, t('Unable to determine %project name.', array('%project' => $project)));
}
if ($updater->isInstalled()) {
form_set_error($field, t('%project is already installed.', array('%project' => $project_title)));
return;
}
$project_real_location = drupal_realpath($project_location);
$arguments = array(
'project' => $project,
'updater_name' => get_class($updater),
'local_url' => $project_real_location,
);
// If the owner of the directory we extracted is the same as the
// owner of our configuration directory (e.g. sites/default) where we're
// trying to install the code, there's no need to prompt for FTP/SSH
// credentials. Instead, we instantiate a FileTransferLocal and invoke
// update_authorize_run_install() directly.
if (fileowner($project_real_location) == fileowner(conf_path())) {
module_load_include('inc', 'update', 'update.authorize');
$filetransfer = new FileTransferLocal(DRUPAL_ROOT);
call_user_func_array('update_authorize_run_install', array_merge(array($filetransfer), $arguments));
}
// Otherwise, go through the regular workflow to prompt for FTP/SSH
// credentials and invoke update_authorize_run_install() indirectly with
// whatever FileTransfer object authorize.php creates for us.
else {
system_authorized_init('update_authorize_run_install', drupal_get_path('module', 'update') . '/update.authorize.inc', $arguments, t('Update manager'));
$form_state['redirect'] = system_authorized_get_url();
}
}
/**
* @} End of "defgroup update_manager_install".
*/
/**
* @defgroup update_manager_file Update Manager module: file management
* @{
* Update Manager module file management functions.
*
* These functions are used by the update manager to copy, extract, and verify
* archive files.
*/
/**
* Unpacks a downloaded archive file.
*
* @param string $file
* The filename of the archive you wish to extract.
* @param string $directory
* The directory you wish to extract the archive into.
*
* @return Archiver
* The Archiver object used to extract the archive.
*
* @throws Exception
*/
function update_manager_archive_extract($file, $directory) {
$archiver = archiver_get_archiver($file);
if (!$archiver) {
throw new Exception(t('Cannot extract %file, not a valid archive.', array ('%file' => $file)));
}
// Remove the directory if it exists, otherwise it might contain a mixture of
// old files mixed with the new files (e.g. in cases where files were removed
// from a later release).
$files = $archiver->listContents();
// Unfortunately, we can only use the directory name to determine the project
// name. Some archivers list the first file as the directory (i.e., MODULE/)
// and others list an actual file (i.e., MODULE/README.TXT).
$project = strtok($files[0], '/\\');
$extract_location = $directory . '/' . $project;
if (file_exists($extract_location)) {
file_unmanaged_delete_recursive($extract_location);
}
$archiver->extract($directory);
return $archiver;
}
/**
* Verifies an archive after it has been downloaded and extracted.
*
* This function is responsible for invoking hook_verify_update_archive().
*
* @param string $project
* The short name of the project to download.
* @param string $archive_file
* The filename of the unextracted archive.
* @param string $directory
* The directory that the archive was extracted into.
*
* @return array
* An array of error messages to display if the archive was invalid. If there
* are no errors, it will be an empty array.
*/
function update_manager_archive_verify($project, $archive_file, $directory) {
return module_invoke_all('verify_update_archive', $project, $archive_file, $directory);
}
/**
* Copies a file from the specified URL to the temporary directory for updates.
*
* Returns the local path if the file has already been downloaded.
*
* @param $url
* The URL of the file on the server.
*
* @return string
* Path to local file.
*/
function update_manager_file_get($url) {
$parsed_url = parse_url($url);
$remote_schemes = array('http', 'https', 'ftp', 'ftps', 'smb', 'nfs');
if (!in_array($parsed_url['scheme'], $remote_schemes)) {
// This is a local file, just return the path.
return drupal_realpath($url);
}
// Check the cache and download the file if needed.
$cache_directory = _update_manager_cache_directory();
$local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
if (!file_exists($local) || update_delete_file_if_stale($local)) {
return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
}
else {
return $local;
}
}
/**
* Implements callback_batch_operation().
*
* Downloads, unpacks, and verifies a project.
*
* This function assumes that the provided URL points to a file archive of some
* sort. The URL can have any scheme that we have a file stream wrapper to
* support. The file is downloaded to a local cache.
*
* @param string $project
* The short name of the project to download.
* @param string $url
* The URL to download a specific project release archive file.
* @param array $context
* Reference to an array used for Batch API storage.
*
* @see update_manager_download_page()
*/
function update_manager_batch_project_get($project, $url, &$context) {
// This is here to show the user that we are in the process of downloading.
if (!isset($context['sandbox']['started'])) {
$context['sandbox']['started'] = TRUE;
$context['message'] = t('Downloading %project', array('%project' => $project));
$context['finished'] = 0;
return;
}
// Actually try to download the file.
if (!($local_cache = update_manager_file_get($url))) {
$context['results']['errors'][$project] = t('Failed to download %project from %url', array('%project' => $project, '%url' => $url));
return;
}
// Extract it.
$extract_directory = _update_manager_extract_directory();
try {
update_manager_archive_extract($local_cache, $extract_directory);
}
catch (Exception $e) {
$context['results']['errors'][$project] = $e->getMessage();
return;
}
// Verify it.
$archive_errors = update_manager_archive_verify($project, $local_cache, $extract_directory);
if (!empty($archive_errors)) {
// We just need to make sure our array keys don't collide, so use the
// numeric keys from the $archive_errors array.
foreach ($archive_errors as $key => $error) {
$context['results']['errors']["$project-$key"] = $error;
}
return;
}
// Yay, success.
$context['results']['projects'][$project] = $url;
$context['finished'] = 1;
}
/**
* Determines if file transfers will be performed locally.
*
* If the server is configured such that webserver-created files have the same
* owner as the configuration directory (e.g., sites/default) where new code
* will eventually be installed, the update manager can transfer files entirely
* locally, without changing their ownership (in other words, without prompting
* the user for FTP, SSH or other credentials).
*
* This server configuration is an inherent security weakness because it allows
* a malicious webserver process to append arbitrary PHP code and then execute
* it. However, it is supported here because it is a common configuration on
* shared hosting, and there is nothing Drupal can do to prevent it.
*
* @return
* TRUE if local file transfers are allowed on this server, or FALSE if not.
*
* @see update_manager_update_ready_form_submit()
* @see update_manager_install_form_submit()
* @see install_check_requirements()
*/
function update_manager_local_transfers_allowed() {
// Compare the owner of a webserver-created temporary file to the owner of
// the configuration directory to determine if local transfers will be
// allowed.
$temporary_file = drupal_tempnam('temporary://', 'update_');
$local_transfers_allowed = fileowner($temporary_file) === fileowner(conf_path());
// Clean up. If this fails, we can ignore it (since this is just a temporary
// file anyway).
@drupal_unlink($temporary_file);
return $local_transfers_allowed;
}
/**
* @} End of "defgroup update_manager_file".
*/

View file

@ -0,0 +1,996 @@
<?php
/**
* @file
* Handles updates of Drupal core and contributed projects.
*
* The module checks for available updates of Drupal core and any installed
* contributed modules and themes. It warns site administrators if newer
* releases are available via the system status report (admin/reports/status),
* the module and theme pages, and optionally via e-mail. It also provides the
* ability to install contributed modules and themes via an user interface.
*/
/**
* URL to check for updates, if a given project doesn't define its own.
*/
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');
// These are internally used constants for this code, do not modify.
/**
* Project is missing security update(s).
*/
define('UPDATE_NOT_SECURE', 1);
/**
* Current release has been unpublished and is no longer available.
*/
define('UPDATE_REVOKED', 2);
/**
* Current release is no longer supported by the project maintainer.
*/
define('UPDATE_NOT_SUPPORTED', 3);
/**
* Project has a new release available, but it is not a security release.
*/
define('UPDATE_NOT_CURRENT', 4);
/**
* Project is up to date.
*/
define('UPDATE_CURRENT', 5);
/**
* Project's status cannot be checked.
*/
define('UPDATE_NOT_CHECKED', -1);
/**
* No available update data was found for project.
*/
define('UPDATE_UNKNOWN', -2);
/**
* There was a failure fetching available update data for this project.
*/
define('UPDATE_NOT_FETCHED', -3);
/**
* We need to (re)fetch available update data for this project.
*/
define('UPDATE_FETCH_PENDING', -4);
/**
* Maximum number of attempts to fetch available update data from a given host.
*/
define('UPDATE_MAX_FETCH_ATTEMPTS', 2);
/**
* Maximum number of seconds to try fetching available update data at a time.
*/
define('UPDATE_MAX_FETCH_TIME', 30);
/**
* Implements hook_help().
*/
function update_help($path, $arg) {
switch ($path) {
case 'admin/reports/updates':
return '<p>' . t('Here you can find information about available updates for your installed modules and themes. Note that each module or theme is part of a "project", which may or may not have the same name, and might include multiple modules or themes within it.') . '</p>';
case 'admin/help#update':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t("The Update manager module periodically checks for new versions of your site's software (including contributed modules and themes), and alerts administrators to available updates. In order to provide update information, anonymous usage statistics are sent to Drupal.org. If desired, you may disable the Update manager module from the <a href='@modules'>Module administration page</a>. For more information, see the online handbook entry for <a href='@update'>Update manager module</a>.", array('@update' => 'http://drupal.org/documentation/modules/update', '@modules' => url('admin/modules'))) . '</p>';
// Only explain the Update manager if it has not been disabled.
if (update_manager_access()) {
$output .= '<p>' . t('The Update manager also allows administrators to update and install modules and themes through the administration interface.') . '</p>';
}
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Checking for available updates') . '</dt>';
$output .= '<dd>' . t('A report of <a href="@update-report">available updates</a> will alert you when new releases are available for download. You may configure options for the frequency for checking updates (which are performed during <a href="@cron">cron</a> runs) and e-mail notifications at the <a href="@update-settings">Update manager settings</a> page.', array('@update-report' => url('admin/reports/updates'), '@cron' => 'http://drupal.org/cron', '@update-settings' => url('admin/reports/updates/settings'))) . '</dd>';
// Only explain the Update manager if it has not been disabled.
if (update_manager_access()) {
$output .= '<dt>' . t('Performing updates through the user interface') . '</dt>';
$output .= '<dd>' . t('The Update manager module allows administrators to perform updates directly through the administration interface. At the top of the <a href="@modules_page">modules</a> and <a href="@themes_page">themes</a> pages you will see a link to update to new releases. This will direct you to the <a href="@update-page">update page</a> where you see a listing of all the missing updates and confirm which ones you want to upgrade. From there, you are prompted for your FTP/SSH password, which then transfers the files into your Drupal installation, overwriting your old files. More detailed instructions can be found in the <a href="@update">online handbook</a>.', array('@modules_page' => url('admin/modules'), '@themes_page' => url('admin/appearance'), '@update-page' => url('admin/reports/updates/update'), '@update' => 'http://drupal.org/documentation/modules/update')) . '</dd>';
$output .= '<dt>' . t('Installing new modules and themes through the user interface') . '</dt>';
$output .= '<dd>' . t('You can also install new modules and themes in the same fashion, through the <a href="@install">install page</a>, or by clicking the <em>Install new module/theme</em> link at the top of the <a href="@modules_page">modules</a> and <a href="@themes_page">themes</a> pages. In this case, you are prompted to provide either the URL to the download, or to upload a packaged release file from your local computer.', array('@modules_page' => url('admin/modules'), '@themes_page' => url('admin/appearance'), '@install' => url('admin/reports/updates/install'))) . '</dd>';
}
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_init().
*/
function update_init() {
if (arg(0) == 'admin' && user_access('administer site configuration')) {
switch ($_GET['q']) {
// These pages don't need additional nagging.
case 'admin/appearance/update':
case 'admin/appearance/install':
case 'admin/modules/update':
case 'admin/modules/install':
case 'admin/reports/updates':
case 'admin/reports/updates/update':
case 'admin/reports/updates/install':
case 'admin/reports/updates/settings':
case 'admin/reports/status':
case 'admin/update/ready':
return;
// If we are on the appearance or modules list, display a detailed report
// of the update status.
case 'admin/appearance':
case 'admin/modules':
$verbose = TRUE;
break;
}
module_load_install('update');
$status = update_requirements('runtime');
foreach (array('core', 'contrib') as $report_type) {
$type = 'update_' . $report_type;
if (!empty($verbose)) {
if (isset($status[$type]['severity'])) {
if ($status[$type]['severity'] == REQUIREMENT_ERROR) {
drupal_set_message($status[$type]['description'], 'error', FALSE);
}
elseif ($status[$type]['severity'] == REQUIREMENT_WARNING) {
drupal_set_message($status[$type]['description'], 'warning', FALSE);
}
}
}
// Otherwise, if we're on *any* admin page and there's a security
// update missing, print an error message about it.
else {
if (isset($status[$type])
&& isset($status[$type]['reason'])
&& $status[$type]['reason'] === UPDATE_NOT_SECURE) {
drupal_set_message($status[$type]['description'], 'error', FALSE);
}
}
}
}
}
/**
* Implements hook_menu().
*/
function update_menu() {
$items = array();
$items['admin/reports/updates'] = array(
'title' => 'Available updates',
'description' => 'Get a status report about available updates for your installed modules and themes.',
'page callback' => 'update_status',
'access arguments' => array('administer site configuration'),
'weight' => -50,
'file' => 'update.report.inc',
);
$items['admin/reports/updates/list'] = array(
'title' => 'List',
'access arguments' => array('administer site configuration'),
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['admin/reports/updates/settings'] = array(
'title' => 'Settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('update_settings'),
'access arguments' => array('administer site configuration'),
'file' => 'update.settings.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 50,
);
$items['admin/reports/updates/check'] = array(
'title' => 'Manual update check',
'page callback' => 'update_manual_status',
'access arguments' => array('administer site configuration'),
'type' => MENU_CALLBACK,
'file' => 'update.fetch.inc',
);
// We want action links for updating projects at a few different locations:
// both the module and theme administration pages, and on the available
// updates report itself. The menu items will be mostly identical, except the
// paths and titles, so we just define them in a loop. We pass in a string
// indicating what context we're entering the action from, so that can
// customize the appearance as needed.
$paths = array(
'report' => 'admin/reports/updates',
'module' => 'admin/modules',
'theme' => 'admin/appearance',
);
foreach ($paths as $context => $path) {
$items[$path . '/install'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array('update_manager_install_form', $context),
'access callback' => 'update_manager_access',
'access arguments' => array(),
'weight' => 25,
'type' => MENU_LOCAL_ACTION,
'file' => 'update.manager.inc',
);
$items[$path . '/update'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array('update_manager_update_form', $context),
'access callback' => 'update_manager_access',
'access arguments' => array(),
'weight' => 10,
'title' => 'Update',
'type' => MENU_LOCAL_TASK,
'file' => 'update.manager.inc',
);
}
// Customize the titles of the action links depending on where they appear.
// We use += array() to let the translation extractor find these menu titles.
$items['admin/reports/updates/install'] += array('title' => 'Install new module or theme');
$items['admin/modules/install'] += array('title' => 'Install new module');
$items['admin/appearance/install'] += array('title' => 'Install new theme');
// Menu callback used for the confirmation page after all the releases
// have been downloaded, asking you to backup before installing updates.
$items['admin/update/ready'] = array(
'title' => 'Ready to update',
'page callback' => 'drupal_get_form',
'page arguments' => array('update_manager_update_ready_form'),
'access callback' => 'update_manager_access',
'access arguments' => array(),
'type' => MENU_CALLBACK,
'file' => 'update.manager.inc',
);
return $items;
}
/**
* Access callback: Resolves if the current user can access updater menu items.
*
* It both enforces the 'administer software updates' permission and the global
* kill switch for the authorize.php script.
*
* @return
* TRUE if the current user can access the updater menu items; FALSE
* otherwise.
*
* @see update_menu()
*/
function update_manager_access() {
return variable_get('allow_authorize_operations', TRUE) && user_access('administer software updates');
}
/**
* Implements hook_theme().
*/
function update_theme() {
return array(
'update_manager_update_form' => array(
'render element' => 'form',
'file' => 'update.manager.inc',
),
'update_last_check' => array(
'variables' => array('last' => NULL),
),
'update_report' => array(
'variables' => array('data' => NULL),
'file' => 'update.report.inc',
),
'update_version' => array(
'variables' => array('version' => NULL, 'tag' => NULL, 'class' => array()),
'file' => 'update.report.inc',
),
'update_status_label' => array(
'variables' => array('status' => NULL),
'file' => 'update.report.inc',
),
);
}
/**
* Implements hook_cron().
*/
function update_cron() {
$frequency = variable_get('update_check_frequency', 1);
$interval = 60 * 60 * 24 * $frequency;
if ((REQUEST_TIME - variable_get('update_last_check', 0)) > $interval) {
// If the configured update interval has elapsed, we want to invalidate
// the cached data for all projects, attempt to re-fetch, and trigger any
// configured notifications about the new status.
update_refresh();
update_fetch_data();
}
else {
// Otherwise, see if any individual projects are now stale or still
// missing data, and if so, try to fetch the data.
update_get_available(TRUE);
}
if ((REQUEST_TIME - variable_get('update_last_email_notification', 0)) > $interval) {
// If configured time between notifications elapsed, send email about
// updates possibly available.
module_load_include('inc', 'update', 'update.fetch');
_update_cron_notify();
}
// Clear garbage from disk.
update_clear_update_disk_cache();
}
/**
* Implements hook_themes_enabled().
*
* If themes are enabled, we invalidate the cache of available updates.
*/
function update_themes_enabled($themes) {
// Clear all update module caches.
_update_cache_clear();
}
/**
* Implements hook_themes_disabled().
*
* If themes are disabled, we invalidate the cache of available updates.
*/
function update_themes_disabled($themes) {
// Clear all update module caches.
_update_cache_clear();
}
/**
* Implements hook_form_FORM_ID_alter() for system_modules().
*
* Adds a form submission handler to the system modules form, so that if a site
* admin saves the form, we invalidate the cache of available updates.
*
* @see _update_cache_clear()
*/
function update_form_system_modules_alter(&$form, $form_state) {
$form['#submit'][] = 'update_cache_clear_submit';
}
/**
* Form submission handler for system_modules().
*
* @see update_form_system_modules_alter()
*/
function update_cache_clear_submit($form, &$form_state) {
// Clear all update module caches.
_update_cache_clear();
}
/**
* Returns a warning message when there is no data about available updates.
*/
function _update_no_data() {
$destination = drupal_get_destination();
return t('No update information available. <a href="@run_cron">Run cron</a> or <a href="@check_manually">check manually</a>.', array(
'@run_cron' => url('admin/reports/status/run-cron', array('query' => $destination)),
'@check_manually' => url('admin/reports/updates/check', array('query' => $destination)),
));
}
/**
* Tries to get update information from cache and refreshes it when necessary.
*
* In addition to checking the cache lifetime, this function also ensures that
* there are no .info files for enabled modules or themes that have a newer
* modification timestamp than the last time we checked for available update
* data. If any .info file was modified, it almost certainly means a new version
* of something was installed. Without fresh available update data, the logic in
* update_calculate_project_data() will be wrong and produce confusing, bogus
* results.
*
* @param $refresh
* (optional) Boolean to indicate if this method should refresh the cache
* automatically if there's no data. Defaults to FALSE.
*
* @return
* Array of data about available releases, keyed by project shortname.
*
* @see update_refresh()
* @see update_get_projects()
*/
function update_get_available($refresh = FALSE) {
module_load_include('inc', 'update', 'update.compare');
$needs_refresh = FALSE;
// Grab whatever data we currently have cached in the DB.
$available = _update_get_cached_available_releases();
$num_avail = count($available);
$projects = update_get_projects();
foreach ($projects as $key => $project) {
// If there's no data at all, we clearly need to fetch some.
if (empty($available[$key])) {
update_create_fetch_task($project);
$needs_refresh = TRUE;
continue;
}
// See if the .info file is newer than the last time we checked for data,
// and if so, mark this project's data as needing to be re-fetched. Any
// time an admin upgrades their local installation, the .info file will
// be changed, so this is the only way we can be sure we're not showing
// bogus information right after they upgrade.
if ($project['info']['_info_file_ctime'] > $available[$key]['last_fetch']) {
$available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
}
// If we have project data but no release data, we need to fetch. This
// can be triggered when we fail to contact a release history server.
if (empty($available[$key]['releases'])) {
$available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
}
// If we think this project needs to fetch, actually create the task now
// and remember that we think we're missing some data.
if (!empty($available[$key]['fetch_status']) && $available[$key]['fetch_status'] == UPDATE_FETCH_PENDING) {
update_create_fetch_task($project);
$needs_refresh = TRUE;
}
}
if ($needs_refresh && $refresh) {
// Attempt to drain the queue of fetch tasks.
update_fetch_data();
// After processing the queue, we've (hopefully) got better data, so pull
// the latest from the cache again and use that directly.
$available = _update_get_cached_available_releases();
}
return $available;
}
/**
* Creates a new fetch task after loading the necessary include file.
*
* @param $project
* Associative array of information about a project. See update_get_projects()
* for the keys used.
*
* @see _update_create_fetch_task()
*/
function update_create_fetch_task($project) {
module_load_include('inc', 'update', 'update.fetch');
return _update_create_fetch_task($project);
}
/**
* Refreshes the release data after loading the necessary include file.
*
* @see _update_refresh()
*/
function update_refresh() {
module_load_include('inc', 'update', 'update.fetch');
return _update_refresh();
}
/**
* Attempts to fetch update data after loading the necessary include file.
*
* @see _update_fetch_data()
*/
function update_fetch_data() {
module_load_include('inc', 'update', 'update.fetch');
return _update_fetch_data();
}
/**
* Returns all currently cached data about available releases for all projects.
*
* @return
* Array of data about available releases, keyed by project shortname.
*/
function _update_get_cached_available_releases() {
$data = array();
$cache_items = _update_get_cache_multiple('available_releases');
foreach ($cache_items as $cid => $cache) {
$cache->data['last_fetch'] = $cache->created;
if ($cache->expire < REQUEST_TIME) {
$cache->data['fetch_status'] = UPDATE_FETCH_PENDING;
}
// The project shortname is embedded in the cache ID, even if there's no
// data for this project in the DB at all, so use that for the indexes in
// the array.
$parts = explode('::', $cid, 2);
$data[$parts[1]] = $cache->data;
}
return $data;
}
/**
* Implements hook_mail().
*
* Constructs the e-mail notification message when the site is out of date.
*
* @param $key
* Unique key to indicate what message to build, always 'status_notify'.
* @param $message
* Reference to the message array being built.
* @param $params
* Array of parameters to indicate what kind of text to include in the message
* body. This is a keyed array of message type ('core' or 'contrib') as the
* keys, and the status reason constant (UPDATE_NOT_SECURE, etc) for the
* values.
*
* @see drupal_mail()
* @see _update_cron_notify()
* @see _update_message_text()
*/
function update_mail($key, &$message, $params) {
$language = $message['language'];
$langcode = $language->language;
$message['subject'] .= t('New release(s) available for !site_name', array('!site_name' => variable_get('site_name', 'Drupal')), array('langcode' => $langcode));
foreach ($params as $msg_type => $msg_reason) {
$message['body'][] = _update_message_text($msg_type, $msg_reason, FALSE, $language);
}
$message['body'][] = t('See the available updates page for more information:', array(), array('langcode' => $langcode)) . "\n" . url('admin/reports/updates', array('absolute' => TRUE, 'language' => $language));
if (update_manager_access()) {
$message['body'][] = t('You can automatically install your missing updates using the Update manager:', array(), array('langcode' => $langcode)) . "\n" . url('admin/reports/updates/update', array('absolute' => TRUE, 'language' => $language));
}
$settings_url = url('admin/reports/updates/settings', array('absolute' => TRUE));
if (variable_get('update_notification_threshold', 'all') == 'all') {
$message['body'][] = t('Your site is currently configured to send these emails when any updates are available. To get notified only for security updates, !url.', array('!url' => $settings_url));
}
else {
$message['body'][] = t('Your site is currently configured to send these emails only when security updates are available. To get notified for any available updates, !url.', array('!url' => $settings_url));
}
}
/**
* Returns the appropriate message text when site is out of date or not secure.
*
* These error messages are shared by both update_requirements() for the
* site-wide status report at admin/reports/status and in the body of the
* notification e-mail messages generated by update_cron().
*
* @param $msg_type
* String to indicate what kind of message to generate. Can be either 'core'
* or 'contrib'.
* @param $msg_reason
* Integer constant specifying why message is generated.
* @param $report_link
* (optional) Boolean that controls if a link to the updates report should be
* added. Defaults to FALSE.
* @param $language
* (optional) A language object to use. Defaults to NULL.
*
* @return
* The properly translated error message for the given key.
*/
function _update_message_text($msg_type, $msg_reason, $report_link = FALSE, $language = NULL) {
$langcode = isset($language) ? $language->language : NULL;
$text = '';
switch ($msg_reason) {
case UPDATE_NOT_SECURE:
if ($msg_type == 'core') {
$text = t('There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately!', array(), array('langcode' => $langcode));
}
else {
$text = t('There are security updates available for one or more of your modules or themes. To ensure the security of your server, you should update immediately!', array(), array('langcode' => $langcode));
}
break;
case UPDATE_REVOKED:
if ($msg_type == 'core') {
$text = t('Your version of Drupal has been revoked and is no longer available for download. Upgrading is strongly recommended!', array(), array('langcode' => $langcode));
}
else {
$text = t('The installed version of at least one of your modules or themes has been revoked and is no longer available for download. Upgrading or disabling is strongly recommended!', array(), array('langcode' => $langcode));
}
break;
case UPDATE_NOT_SUPPORTED:
if ($msg_type == 'core') {
$text = t('Your version of Drupal is no longer supported. Upgrading is strongly recommended!', array(), array('langcode' => $langcode));
}
else {
$text = t('The installed version of at least one of your modules or themes is no longer supported. Upgrading or disabling is strongly recommended. See the project homepage for more details.', array(), array('langcode' => $langcode));
}
break;
case UPDATE_NOT_CURRENT:
if ($msg_type == 'core') {
$text = t('There are updates available for your version of Drupal. To ensure the proper functioning of your site, you should update as soon as possible.', array(), array('langcode' => $langcode));
}
else {
$text = t('There are updates available for one or more of your modules or themes. To ensure the proper functioning of your site, you should update as soon as possible.', array(), array('langcode' => $langcode));
}
break;
case UPDATE_UNKNOWN:
case UPDATE_NOT_CHECKED:
case UPDATE_NOT_FETCHED:
case UPDATE_FETCH_PENDING:
if ($msg_type == 'core') {
$text = t('There was a problem checking <a href="@update-report">available updates</a> for Drupal.', array('@update-report' => url('admin/reports/updates')), array('langcode' => $langcode));
}
else {
$text = t('There was a problem checking <a href="@update-report">available updates</a> for your modules or themes.', array('@update-report' => url('admin/reports/updates')), array('langcode' => $langcode));
}
break;
}
if ($report_link) {
if (update_manager_access()) {
$text .= ' ' . t('See the <a href="@available_updates">available updates</a> page for more information and to install your missing updates.', array('@available_updates' => url('admin/reports/updates/update', array('language' => $language))), array('langcode' => $langcode));
}
else {
$text .= ' ' . t('See the <a href="@available_updates">available updates</a> page for more information.', array('@available_updates' => url('admin/reports/updates', array('language' => $language))), array('langcode' => $langcode));
}
}
return $text;
}
/**
* Orders projects based on their status.
*
* Callback for uasort() within update_requirements().
*/
function _update_project_status_sort($a, $b) {
// The status constants are numerically in the right order, so we can
// usually subtract the two to compare in the order we want. However,
// negative status values should be treated as if they are huge, since we
// always want them at the bottom of the list.
$a_status = $a['status'] > 0 ? $a['status'] : (-10 * $a['status']);
$b_status = $b['status'] > 0 ? $b['status'] : (-10 * $b['status']);
return $a_status - $b_status;
}
/**
* Returns HTML for the last time we checked for update data.
*
* In addition to properly formatting the given timestamp, this function also
* provides a "Check manually" link that refreshes the available update and
* redirects back to the same page.
*
* @param $variables
* An associative array containing:
* - last: The timestamp when the site last checked for available updates.
*
* @see theme_update_report()
* @see theme_update_available_updates_form()
* @ingroup themeable
*/
function theme_update_last_check($variables) {
$last = $variables['last'];
$output = '<div class="update checked">';
$output .= $last ? t('Last checked: @time ago', array('@time' => format_interval(REQUEST_TIME - $last))) : t('Last checked: never');
$output .= ' <span class="check-manually">(' . l(t('Check manually'), 'admin/reports/updates/check', array('query' => drupal_get_destination())) . ')</span>';
$output .= "</div>\n";
return $output;
}
/**
* Implements hook_verify_update_archive().
*
* First, we ensure that the archive isn't a copy of Drupal core, which the
* update manager does not yet support. See http://drupal.org/node/606592
*
* Then, we make sure that at least one module included in the archive file has
* an .info file which claims that the code is compatible with the current
* version of Drupal core.
*
* @see drupal_system_listing()
* @see _system_rebuild_module_data()
*/
function update_verify_update_archive($project, $archive_file, $directory) {
$errors = array();
// Make sure this isn't a tarball of Drupal core.
if (
file_exists("$directory/$project/index.php")
&& file_exists("$directory/$project/update.php")
&& file_exists("$directory/$project/includes/bootstrap.inc")
&& file_exists("$directory/$project/modules/node/node.module")
&& file_exists("$directory/$project/modules/system/system.module")
) {
return array(
'no-core' => t('Automatic updating of Drupal core is not supported. See the <a href="@upgrade-guide">upgrade guide</a> for information on how to update Drupal core manually.', array('@upgrade-guide' => 'http://drupal.org/upgrade')),
);
}
// Parse all the .info files and make sure at least one is compatible with
// this version of Drupal core. If one is compatible, then the project as a
// whole is considered compatible (since, for example, the project may ship
// with some out-of-date modules that are not necessary for its overall
// functionality).
$compatible_project = FALSE;
$incompatible = array();
$files = file_scan_directory("$directory/$project", '/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', array('key' => 'name', 'min_depth' => 0));
foreach ($files as $key => $file) {
// Get the .info file for the module or theme this file belongs to.
$info = drupal_parse_info_file($file->uri);
// If the module or theme is incompatible with Drupal core, set an error.
if (empty($info['core']) || $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
$incompatible[] = !empty($info['name']) ? $info['name'] : t('Unknown');
}
else {
$compatible_project = TRUE;
break;
}
}
if (empty($files)) {
$errors[] = t('%archive_file does not contain any .info files.', array('%archive_file' => drupal_basename($archive_file)));
}
elseif (!$compatible_project) {
$errors[] = format_plural(
count($incompatible),
'%archive_file contains a version of %names that is not compatible with Drupal !version.',
'%archive_file contains versions of modules or themes that are not compatible with Drupal !version: %names',
array('!version' => DRUPAL_CORE_COMPATIBILITY, '%archive_file' => drupal_basename($archive_file), '%names' => implode(', ', $incompatible))
);
}
return $errors;
}
/**
* @defgroup update_status_cache Private update status cache system
* @{
* Functions to manage the update status cache.
*
* We specifically do NOT use the core cache API for saving the fetched data
* about available updates. It is vitally important that this cache is only
* cleared when we're populating it after successfully fetching new available
* update data. Usage of the core cache API results in all sorts of potential
* problems that would result in attempting to fetch available update data all
* the time, including if a site has a "minimum cache lifetime" (which is both a
* minimum and a maximum) defined, or if a site uses memcache or another
* pluggable cache system that assumes volatile caches.
*
* The Update Manager module still uses the {cache_update} table, but instead of
* using cache_set(), cache_get(), and cache_clear_all(), there are private
* helper functions that implement these same basic tasks but ensure that the
* cache is not prematurely cleared, and that the data is always stored in the
* database, even if memcache or another cache backend is in use.
*/
/**
* Stores data in the private update status cache table.
*
* @param $cid
* The cache ID to save the data with.
* @param $data
* The data to store.
* @param $expire
* One of the following values:
* - CACHE_PERMANENT: Indicates that the item should never be removed except
* by explicitly using _update_cache_clear().
* - A Unix timestamp: Indicates that the item should be kept at least until
* the given time, after which it will be invalidated.
*
* @see _update_cache_get()
*/
function _update_cache_set($cid, $data, $expire) {
$fields = array(
'created' => REQUEST_TIME,
'expire' => $expire,
);
if (!is_string($data)) {
$fields['data'] = serialize($data);
$fields['serialized'] = 1;
}
else {
$fields['data'] = $data;
$fields['serialized'] = 0;
}
db_merge('cache_update')
->key(array('cid' => $cid))
->fields($fields)
->execute();
}
/**
* Retrieves data from the private update status cache table.
*
* @param $cid
* The cache ID to retrieve.
*
* @return
* An array of data for the given cache ID, or NULL if the ID was not found.
*
* @see _update_cache_set()
*/
function _update_cache_get($cid) {
$cache = db_query("SELECT data, created, expire, serialized FROM {cache_update} WHERE cid = :cid", array(':cid' => $cid))->fetchObject();
if (isset($cache->data)) {
if ($cache->serialized) {
$cache->data = unserialize($cache->data);
}
}
return $cache;
}
/**
* Returns an array of cache items with a given cache ID prefix.
*
* @param string $cid_prefix
* The cache ID prefix.
*
* @return
* Associative array of cache items, keyed by cache ID.
*/
function _update_get_cache_multiple($cid_prefix) {
$data = array();
$result = db_select('cache_update')
->fields('cache_update', array('cid', 'data', 'created', 'expire', 'serialized'))
->condition('cache_update.cid', $cid_prefix . '::%', 'LIKE')
->execute();
foreach ($result as $cache) {
if ($cache) {
if ($cache->serialized) {
$cache->data = unserialize($cache->data);
}
$data[$cache->cid] = $cache;
}
}
return $data;
}
/**
* Invalidates cached data relating to update status.
*
* @param $cid
* (optional) Cache ID of the record to clear from the private update module
* cache. If empty, all records will be cleared from the table except fetch
* tasks. Defaults to NULL.
* @param $wildcard
* (optional) If TRUE, cache IDs starting with $cid are deleted in addition to
* the exact cache ID specified by $cid. Defaults to FALSE.
*/
function _update_cache_clear($cid = NULL, $wildcard = FALSE) {
if (empty($cid)) {
db_delete('cache_update')
// Clear everything except fetch task information because these are used
// to ensure that the fetch task queue items are not added multiple times.
->condition('cid', 'fetch_task::%', 'NOT LIKE')
->execute();
}
else {
$query = db_delete('cache_update');
if ($wildcard) {
$query->condition('cid', $cid . '%', 'LIKE');
}
else {
$query->condition('cid', $cid);
}
$query->execute();
}
}
/**
* Implements hook_flush_caches().
*
* Called from update.php (among others) to flush the caches. Since we're
* running update.php, we are likely to install a new version of something, in
* which case, we want to check for available update data again. However,
* because we have our own caching system, we need to directly clear the
* database table ourselves at this point and return nothing, for example, on
* sites that use memcache where cache_clear_all() won't know how to purge this
* data.
*
* However, we only want to do this from update.php, since otherwise, we'd lose
* all the available update data on every cron run. So, we specifically check if
* the site is in MAINTENANCE_MODE == 'update' (which indicates update.php is
* running, not update module... alas for overloaded names).
*/
function update_flush_caches() {
if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
_update_cache_clear();
}
return array();
}
/**
* @} End of "defgroup update_status_cache".
*/
/**
* Returns a short unique identifier for this Drupal installation.
*
* @return
* An eight character string uniquely identifying this Drupal installation.
*/
function _update_manager_unique_identifier() {
$id = &drupal_static(__FUNCTION__, '');
if (empty($id)) {
$id = substr(hash('sha256', drupal_get_hash_salt()), 0, 8);
}
return $id;
}
/**
* Returns the directory where update archive files should be extracted.
*
* @param $create
* (optional) Whether to attempt to create the directory if it does not
* already exist. Defaults to TRUE.
*
* @return
* The full path to the temporary directory where update file archives should
* be extracted.
*/
function _update_manager_extract_directory($create = TRUE) {
$directory = &drupal_static(__FUNCTION__, '');
if (empty($directory)) {
$directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();
if ($create && !file_exists($directory)) {
mkdir($directory);
}
}
return $directory;
}
/**
* Returns the directory where update archive files should be cached.
*
* @param $create
* (optional) Whether to attempt to create the directory if it does not
* already exist. Defaults to TRUE.
*
* @return
* The full path to the temporary directory where update file archives should
* be cached.
*/
function _update_manager_cache_directory($create = TRUE) {
$directory = &drupal_static(__FUNCTION__, '');
if (empty($directory)) {
$directory = 'temporary://update-cache-' . _update_manager_unique_identifier();
if ($create && !file_exists($directory)) {
mkdir($directory);
}
}
return $directory;
}
/**
* Clears the temporary files and directories based on file age from disk.
*/
function update_clear_update_disk_cache() {
// List of update module cache directories. Do not create the directories if
// they do not exist.
$directories = array(
_update_manager_cache_directory(FALSE),
_update_manager_extract_directory(FALSE),
);
// Search for files and directories in base folder only without recursion.
foreach ($directories as $directory) {
file_scan_directory($directory, '/.*/', array('callback' => 'update_delete_file_if_stale', 'recurse' => FALSE));
}
}
/**
* Deletes stale files and directories from the update manager disk cache.
*
* Files and directories older than 6 hours and development snapshots older than
* 5 minutes are considered stale. We only cache development snapshots for 5
* minutes since otherwise updated snapshots might not be downloaded as
* expected.
*
* When checking file ages, we need to use the ctime, not the mtime
* (modification time) since many (all?) tar implementations go out of their way
* to set the mtime on the files they create to the timestamps recorded in the
* tarball. We want to see the last time the file was changed on disk, which is
* left alone by tar and correctly set to the time the archive file was
* unpacked.
*
* @param $path
* A string containing a file path or (streamwrapper) URI.
*/
function update_delete_file_if_stale($path) {
if (file_exists($path)) {
$filectime = filectime($path);
if (REQUEST_TIME - $filectime > DRUPAL_MAXIMUM_TEMP_FILE_AGE || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && REQUEST_TIME - $filectime > 300)) {
file_unmanaged_delete_recursive($path);
}
}
}

View file

@ -0,0 +1,327 @@
<?php
/**
* @file
* Code required only when rendering the available updates report.
*/
/**
* Page callback: Generates a page about the update status of projects.
*
* @see update_menu()
*/
function update_status() {
if ($available = update_get_available(TRUE)) {
module_load_include('inc', 'update', 'update.compare');
$data = update_calculate_project_data($available);
return theme('update_report', array('data' => $data));
}
else {
return theme('update_report', array('data' => _update_no_data()));
}
}
/**
* Returns HTML for the project status report.
*
* @param array $variables
* An associative array containing:
* - data: An array of data about each project's status.
*
* @ingroup themeable
*/
function theme_update_report($variables) {
$data = $variables['data'];
$last = variable_get('update_last_check', 0);
$output = theme('update_last_check', array('last' => $last));
if (!is_array($data)) {
$output .= '<p>' . $data . '</p>';
return $output;
}
$header = array();
$rows = array();
$notification_level = variable_get('update_notification_threshold', 'all');
// Create an array of status values keyed by module or theme name, since
// we'll need this while generating the report if we have to cross reference
// anything (e.g. subthemes which have base themes missing an update).
foreach ($data as $project) {
foreach ($project['includes'] as $key => $name) {
$status[$key] = $project['status'];
}
}
foreach ($data as $project) {
switch ($project['status']) {
case UPDATE_CURRENT:
$class = 'ok';
$icon = theme('image', array('path' => 'misc/watchdog-ok.png', 'width' => 18, 'height' => 18, 'alt' => t('ok'), 'title' => t('ok')));
break;
case UPDATE_UNKNOWN:
case UPDATE_FETCH_PENDING:
case UPDATE_NOT_FETCHED:
$class = 'unknown';
$icon = theme('image', array('path' => 'misc/watchdog-warning.png', 'width' => 18, 'height' => 18, 'alt' => t('warning'), 'title' => t('warning')));
break;
case UPDATE_NOT_SECURE:
case UPDATE_REVOKED:
case UPDATE_NOT_SUPPORTED:
$class = 'error';
$icon = theme('image', array('path' => 'misc/watchdog-error.png', 'width' => 18, 'height' => 18, 'alt' => t('error'), 'title' => t('error')));
break;
case UPDATE_NOT_CHECKED:
case UPDATE_NOT_CURRENT:
default:
$class = 'warning';
$icon = theme('image', array('path' => 'misc/watchdog-warning.png', 'width' => 18, 'height' => 18, 'alt' => t('warning'), 'title' => t('warning')));
break;
}
$row = '<div class="version-status">';
$status_label = theme('update_status_label', array('status' => $project['status']));
$row .= !empty($status_label) ? $status_label : check_plain($project['reason']);
$row .= '<span class="icon">' . $icon . '</span>';
$row .= "</div>\n";
$row .= '<div class="project">';
if (isset($project['title'])) {
if (isset($project['link'])) {
$row .= l($project['title'], $project['link']);
}
else {
$row .= check_plain($project['title']);
}
}
else {
$row .= check_plain($project['name']);
}
$row .= ' ' . check_plain($project['existing_version']);
if ($project['install_type'] == 'dev' && !empty($project['datestamp'])) {
$row .= ' <span class="version-date">(' . format_date($project['datestamp'], 'custom', 'Y-M-d') . ')</span>';
}
$row .= "</div>\n";
$versions_inner = '';
$security_class = array();
$version_class = array();
if (isset($project['recommended'])) {
if ($project['status'] != UPDATE_CURRENT || $project['existing_version'] !== $project['recommended']) {
// First, figure out what to recommend.
// If there's only 1 security update and it has the same version we're
// recommending, give it the same CSS class as if it was recommended,
// but don't print out a separate "Recommended" line for this project.
if (!empty($project['security updates']) && count($project['security updates']) == 1 && $project['security updates'][0]['version'] === $project['recommended']) {
$security_class[] = 'version-recommended';
$security_class[] = 'version-recommended-strong';
}
else {
$version_class[] = 'version-recommended';
// Apply an extra class if we're displaying both a recommended
// version and anything else for an extra visual hint.
if ($project['recommended'] !== $project['latest_version']
|| !empty($project['also'])
|| ($project['install_type'] == 'dev'
&& isset($project['dev_version'])
&& $project['latest_version'] !== $project['dev_version']
&& $project['recommended'] !== $project['dev_version'])
|| (isset($project['security updates'][0])
&& $project['recommended'] !== $project['security updates'][0])
) {
$version_class[] = 'version-recommended-strong';
}
$versions_inner .= theme('update_version', array('version' => $project['releases'][$project['recommended']], 'tag' => t('Recommended version:'), 'class' => $version_class));
}
// Now, print any security updates.
if (!empty($project['security updates'])) {
$security_class[] = 'version-security';
foreach ($project['security updates'] as $security_update) {
$versions_inner .= theme('update_version', array('version' => $security_update, 'tag' => t('Security update:'), 'class' => $security_class));
}
}
}
if ($project['recommended'] !== $project['latest_version']) {
$versions_inner .= theme('update_version', array('version' => $project['releases'][$project['latest_version']], 'tag' => t('Latest version:'), 'class' => array('version-latest')));
}
if ($project['install_type'] == 'dev'
&& $project['status'] != UPDATE_CURRENT
&& isset($project['dev_version'])
&& $project['recommended'] !== $project['dev_version']) {
$versions_inner .= theme('update_version', array('version' => $project['releases'][$project['dev_version']], 'tag' => t('Development version:'), 'class' => array('version-latest')));
}
}
if (isset($project['also'])) {
foreach ($project['also'] as $also) {
$versions_inner .= theme('update_version', array('version' => $project['releases'][$also], 'tag' => t('Also available:'), 'class' => array('version-also-available')));
}
}
if (!empty($versions_inner)) {
$row .= "<div class=\"versions\">\n" . $versions_inner . "</div>\n";
}
$row .= "<div class=\"info\">\n";
if (!empty($project['extra'])) {
$row .= '<div class="extra">' . "\n";
foreach ($project['extra'] as $key => $value) {
$row .= '<div class="' . implode(' ', $value['class']) . '">';
$row .= check_plain($value['label']) . ': ';
$row .= drupal_placeholder($value['data']);
$row .= "</div>\n";
}
$row .= "</div>\n"; // extra div.
}
$row .= '<div class="includes">';
sort($project['includes']);
if (!empty($project['disabled'])) {
sort($project['disabled']);
// Make sure we start with a clean slate for each project in the report.
$includes_items = array();
$row .= t('Includes:');
$includes_items[] = t('Enabled: %includes', array('%includes' => implode(', ', $project['includes'])));
$includes_items[] = t('Disabled: %disabled', array('%disabled' => implode(', ', $project['disabled'])));
$row .= theme('item_list', array('items' => $includes_items));
}
else {
$row .= t('Includes: %includes', array('%includes' => implode(', ', $project['includes'])));
}
$row .= "</div>\n";
if (!empty($project['base_themes'])) {
$row .= '<div class="basethemes">';
asort($project['base_themes']);
$base_themes = array();
foreach ($project['base_themes'] as $base_key => $base_theme) {
switch ($status[$base_key]) {
case UPDATE_NOT_SECURE:
case UPDATE_REVOKED:
case UPDATE_NOT_SUPPORTED:
$base_themes[] = t('%base_theme (!base_label)', array('%base_theme' => $base_theme, '!base_label' => theme('update_status_label', array('status' => $status[$base_key]))));
break;
default:
$base_themes[] = drupal_placeholder($base_theme);
}
}
$row .= t('Depends on: !basethemes', array('!basethemes' => implode(', ', $base_themes)));
$row .= "</div>\n";
}
if (!empty($project['sub_themes'])) {
$row .= '<div class="subthemes">';
sort($project['sub_themes']);
$row .= t('Required by: %subthemes', array('%subthemes' => implode(', ', $project['sub_themes'])));
$row .= "</div>\n";
}
$row .= "</div>\n"; // info div.
if (!isset($rows[$project['project_type']])) {
$rows[$project['project_type']] = array();
}
$row_key = isset($project['title']) ? drupal_strtolower($project['title']) : drupal_strtolower($project['name']);
$rows[$project['project_type']][$row_key] = array(
'class' => array($class),
'data' => array($row),
);
}
$project_types = array(
'core' => t('Drupal core'),
'module' => t('Modules'),
'theme' => t('Themes'),
'module-disabled' => t('Disabled modules'),
'theme-disabled' => t('Disabled themes'),
);
foreach ($project_types as $type_name => $type_label) {
if (!empty($rows[$type_name])) {
ksort($rows[$type_name]);
$output .= "\n<h3>" . $type_label . "</h3>\n";
$output .= theme('table', array('header' => $header, 'rows' => $rows[$type_name], 'attributes' => array('class' => array('update'))));
}
}
drupal_add_css(drupal_get_path('module', 'update') . '/update.css');
return $output;
}
/**
* Returns HTML for a label to display for a project's update status.
*
* @param array $variables
* An associative array containing:
* - status: The integer code for a project's current update status.
*
* @see update_calculate_project_data()
* @ingroup themeable
*/
function theme_update_status_label($variables) {
switch ($variables['status']) {
case UPDATE_NOT_SECURE:
return '<span class="security-error">' . t('Security update required!') . '</span>';
case UPDATE_REVOKED:
return '<span class="revoked">' . t('Revoked!') . '</span>';
case UPDATE_NOT_SUPPORTED:
return '<span class="not-supported">' . t('Not supported!') . '</span>';
case UPDATE_NOT_CURRENT:
return '<span class="not-current">' . t('Update available') . '</span>';
case UPDATE_CURRENT:
return '<span class="current">' . t('Up to date') . '</span>';
}
}
/**
* Returns HTML for the version display of a project.
*
* @param array $variables
* An associative array containing:
* - version: An array of data about the latest released version, containing:
* - version: The version number.
* - release_link: The URL for the release notes.
* - date: The date of the release.
* - download_link: The URL for the downloadable file.
* - tag: The title of the project.
* - class: A string containing extra classes for the wrapping table.
*
* @ingroup themeable
*/
function theme_update_version($variables) {
$version = $variables['version'];
$tag = $variables['tag'];
$class = implode(' ', $variables['class']);
$output = '';
$output .= '<table class="version ' . $class . '">';
$output .= '<tr>';
$output .= '<td class="version-title">' . $tag . "</td>\n";
$output .= '<td class="version-details">';
$output .= l($version['version'], $version['release_link']);
$output .= ' <span class="version-date">(' . format_date($version['date'], 'custom', 'Y-M-d') . ')</span>';
$output .= "</td>\n";
$output .= '<td class="version-links">';
$links = array();
$links['update-download'] = array(
'title' => t('Download'),
'href' => $version['download_link'],
);
$links['update-release-notes'] = array(
'title' => t('Release notes'),
'href' => $version['release_link'],
);
$output .= theme('links__update_version', array('links' => $links));
$output .= '</td>';
$output .= '</tr>';
$output .= "</table>\n";
return $output;
}

View file

@ -0,0 +1,129 @@
<?php
/**
* @file
* Code required only for the update status settings form.
*/
/**
* Form constructor for the update settings form.
*
* @see update_settings_validate()
* @see update_settings_submit()
* @ingroup forms
*/
function update_settings($form) {
$form['update_check_frequency'] = array(
'#type' => 'radios',
'#title' => t('Check for updates'),
'#default_value' => variable_get('update_check_frequency', 1),
'#options' => array(
'1' => t('Daily'),
'7' => t('Weekly'),
),
'#description' => t('Select how frequently you want to automatically check for new releases of your currently installed modules and themes.'),
);
$form['update_check_disabled'] = array(
'#type' => 'checkbox',
'#title' => t('Check for updates of disabled and uninstalled modules and themes'),
'#default_value' => variable_get('update_check_disabled', FALSE),
);
$notify_emails = variable_get('update_notify_emails', array());
$form['update_notify_emails'] = array(
'#type' => 'textarea',
'#title' => t('E-mail addresses to notify when updates are available'),
'#rows' => 4,
'#default_value' => implode("\n", $notify_emails),
'#description' => t('Whenever your site checks for available updates and finds new releases, it can notify a list of users via e-mail. Put each address on a separate line. If blank, no e-mails will be sent.'),
);
$form['update_notification_threshold'] = array(
'#type' => 'radios',
'#title' => t('E-mail notification threshold'),
'#default_value' => variable_get('update_notification_threshold', 'all'),
'#options' => array(
'all' => t('All newer versions'),
'security' => t('Only security updates'),
),
'#description' => t('You can choose to send e-mail only if a security update is available, or to be notified about all newer versions. If there are updates available of Drupal core or any of your installed modules and themes, your site will always print a message on the <a href="@status_report">status report</a> page, and will also display an error message on administration pages if there is a security update.', array('@status_report' => url('admin/reports/status')))
);
$form = system_settings_form($form);
// Custom validation callback for the email notification setting.
$form['#validate'][] = 'update_settings_validate';
// We need to call our own submit callback first, not the one from
// system_settings_form(), so that we can process and save the emails.
unset($form['#submit']);
return $form;
}
/**
* Form validation handler for update_settings().
*
* Validates the e-mail addresses and ensures the field is formatted correctly.
*
* @see update_settings_submit()
*/
function update_settings_validate($form, &$form_state) {
if (!empty($form_state['values']['update_notify_emails'])) {
$valid = array();
$invalid = array();
foreach (explode("\n", trim($form_state['values']['update_notify_emails'])) as $email) {
$email = trim($email);
if (!empty($email)) {
if (valid_email_address($email)) {
$valid[] = $email;
}
else {
$invalid[] = $email;
}
}
}
if (empty($invalid)) {
$form_state['notify_emails'] = $valid;
}
elseif (count($invalid) == 1) {
form_set_error('update_notify_emails', t('%email is not a valid e-mail address.', array('%email' => reset($invalid))));
}
else {
form_set_error('update_notify_emails', t('%emails are not valid e-mail addresses.', array('%emails' => implode(', ', $invalid))));
}
}
}
/**
* Form submission handler for update_settings().
*
* Also invalidates the cache of available updates if the "Check for updates of
* disabled and uninstalled modules and themes" setting is being changed. The
* available updates report needs to refetch available update data after this
* setting changes or it would show misleading things (e.g., listing the
* disabled projects on the site with the "No available releases found"
* warning).
*
* @see update_settings_validate()
*/
function update_settings_submit($form, $form_state) {
$op = $form_state['values']['op'];
if (empty($form_state['notify_emails'])) {
variable_del('update_notify_emails');
}
else {
variable_set('update_notify_emails', $form_state['notify_emails']);
}
unset($form_state['notify_emails']);
unset($form_state['values']['update_notify_emails']);
// See if the update_check_disabled setting is being changed, and if so,
// invalidate all cached update status data.
$check_disabled = variable_get('update_check_disabled', FALSE);
if ($form_state['values']['update_check_disabled'] != $check_disabled) {
_update_cache_clear();
}
system_settings_form_submit($form, $form_state);
}

852
modules/update/update.test Normal file
View file

@ -0,0 +1,852 @@
<?php
/**
* @file
* This file contains tests for the Update Manager module.
*
* The overarching methodology of these tests is we need to compare a given
* state of installed modules and themes (e.g., version, project grouping,
* timestamps, etc) against a current state of what the release history XML
* files we fetch say is available. We have dummy XML files (in the
* modules/update/tests directory) that describe various scenarios of what's
* available for different test projects, and we have dummy .info file data
* (specified via hook_system_info_alter() in the update_test helper module)
* describing what's currently installed. Each test case defines a set of
* projects to install, their current state (via the 'update_test_system_info'
* variable) and the desired available update data (via the
* 'update_test_xml_map' variable), and then performs a series of assertions
* that the report matches our expectations given the specific initial state and
* availability scenario.
*/
/**
* Defines some shared functions used by all update tests.
*/
class UpdateTestHelper extends DrupalWebTestCase {
/**
* Refreshes the update status based on the desired available update scenario.
*
* @param $xml_map
* Array that maps project names to availability scenarios to fetch. The key
* '#all' is used if a project-specific mapping is not defined.
* @param $url
* (optional) A string containing the URL to fetch update data from.
* Defaults to 'update-test'.
*
* @see update_test_mock_page()
*/
protected function refreshUpdateStatus($xml_map, $url = 'update-test') {
// Tell the Update Manager module to fetch from the URL provided by
// update_test module.
variable_set('update_fetch_url', url($url, array('absolute' => TRUE)));
// Save the map for update_test_mock_page() to use.
variable_set('update_test_xml_map', $xml_map);
// Manually check the update status.
$this->drupalGet('admin/reports/updates/check');
}
/**
* Runs a series of assertions that are applicable to all update statuses.
*/
protected function standardTests() {
$this->assertRaw('<h3>' . t('Drupal core') . '</h3>');
$this->assertRaw(l(t('Drupal'), 'http://example.com/project/drupal'), 'Link to the Drupal project appears.');
$this->assertNoText(t('No available releases found'));
}
}
/**
* Tests behavior related to discovering and listing updates to Drupal core.
*/
class UpdateCoreTestCase extends UpdateTestHelper {
public static function getInfo() {
return array(
'name' => 'Update core functionality',
'description' => 'Tests the Update Manager module through a series of functional tests using mock XML data.',
'group' => 'Update',
);
}
function setUp() {
parent::setUp('update_test', 'update');
$admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer modules'));
$this->drupalLogin($admin_user);
}
/**
* Tests the Update Manager module when no updates are available.
*/
function testNoUpdatesAvailable() {
$this->setSystemInfo7_0();
$this->refreshUpdateStatus(array('drupal' => '0'));
$this->standardTests();
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertNoText(t('Security update required!'));
}
/**
* Tests the Update Manager module when one normal update is available.
*/
function testNormalUpdateAvailable() {
$this->setSystemInfo7_0();
$this->refreshUpdateStatus(array('drupal' => '1'));
$this->standardTests();
$this->assertNoText(t('Up to date'));
$this->assertText(t('Update available'));
$this->assertNoText(t('Security update required!'));
$this->assertRaw(l('7.1', 'http://example.com/drupal-7-1-release'), 'Link to release appears.');
$this->assertRaw(l(t('Download'), 'http://example.com/drupal-7-1.tar.gz'), 'Link to download appears.');
$this->assertRaw(l(t('Release notes'), 'http://example.com/drupal-7-1-release'), 'Link to release notes appears.');
}
/**
* Tests the Update Manager module when a security update is available.
*/
function testSecurityUpdateAvailable() {
$this->setSystemInfo7_0();
$this->refreshUpdateStatus(array('drupal' => '2-sec'));
$this->standardTests();
$this->assertNoText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertText(t('Security update required!'));
$this->assertRaw(l('7.2', 'http://example.com/drupal-7-2-release'), 'Link to release appears.');
$this->assertRaw(l(t('Download'), 'http://example.com/drupal-7-2.tar.gz'), 'Link to download appears.');
$this->assertRaw(l(t('Release notes'), 'http://example.com/drupal-7-2-release'), 'Link to release notes appears.');
}
/**
* Ensures proper results where there are date mismatches among modules.
*/
function testDatestampMismatch() {
$system_info = array(
'#all' => array(
// We need to think we're running a -dev snapshot to see dates.
'version' => '7.0-dev',
'datestamp' => time(),
),
'block' => array(
// This is 2001-09-09 01:46:40 GMT, so test for "2001-Sep-".
'datestamp' => '1000000000',
),
);
variable_set('update_test_system_info', $system_info);
$this->refreshUpdateStatus(array('drupal' => 'dev'));
$this->assertNoText(t('2001-Sep-'));
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertNoText(t('Security update required!'));
}
/**
* Checks that running cron updates the list of available updates.
*/
function testModulePageRunCron() {
$this->setSystemInfo7_0();
variable_set('update_fetch_url', url('update-test', array('absolute' => TRUE)));
variable_set('update_test_xml_map', array('drupal' => '0'));
$this->cronRun();
$this->drupalGet('admin/modules');
$this->assertNoText(t('No update information available.'));
}
/**
* Checks the messages at admin/modules when the site is up to date.
*/
function testModulePageUpToDate() {
$this->setSystemInfo7_0();
// Instead of using refreshUpdateStatus(), set these manually.
variable_set('update_fetch_url', url('update-test', array('absolute' => TRUE)));
variable_set('update_test_xml_map', array('drupal' => '0'));
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertText(t('Checked available update data for one project.'));
$this->drupalGet('admin/modules');
$this->assertNoText(t('There are updates available for your version of Drupal.'));
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Checks the messages at admin/modules when an update is missing.
*/
function testModulePageRegularUpdate() {
$this->setSystemInfo7_0();
// Instead of using refreshUpdateStatus(), set these manually.
variable_set('update_fetch_url', url('update-test', array('absolute' => TRUE)));
variable_set('update_test_xml_map', array('drupal' => '1'));
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertText(t('Checked available update data for one project.'));
$this->drupalGet('admin/modules');
$this->assertText(t('There are updates available for your version of Drupal.'));
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Checks the messages at admin/modules when a security update is missing.
*/
function testModulePageSecurityUpdate() {
$this->setSystemInfo7_0();
// Instead of using refreshUpdateStatus(), set these manually.
variable_set('update_fetch_url', url('update-test', array('absolute' => TRUE)));
variable_set('update_test_xml_map', array('drupal' => '2-sec'));
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertText(t('Checked available update data for one project.'));
$this->drupalGet('admin/modules');
$this->assertNoText(t('There are updates available for your version of Drupal.'));
$this->assertText(t('There is a security update available for your version of Drupal.'));
// Make sure admin/appearance warns you you're missing a security update.
$this->drupalGet('admin/appearance');
$this->assertNoText(t('There are updates available for your version of Drupal.'));
$this->assertText(t('There is a security update available for your version of Drupal.'));
// Make sure duplicate messages don't appear on Update status pages.
$this->drupalGet('admin/reports/status');
// We're expecting "There is a security update..." inside the status report
// itself, but the drupal_set_message() appears as an li so we can prefix
// with that and search for the raw HTML.
$this->assertNoRaw('<li>' . t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates/settings');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Tests the Update Manager module when the update server returns 503 errors.
*/
function testServiceUnavailable() {
$this->refreshUpdateStatus(array(), '503-error');
// Ensure that no "Warning: SimpleXMLElement..." parse errors are found.
$this->assertNoText('SimpleXMLElement');
$this->assertUniqueText(t('Failed to get available update data for one project.'));
}
/**
* Tests that exactly one fetch task per project is created and not more.
*/
function testFetchTasks() {
$projecta = array(
'name' => 'aaa_update_test',
);
$projectb = array(
'name' => 'bbb_update_test',
);
$queue = DrupalQueue::get('update_fetch_tasks');
$this->assertEqual($queue->numberOfItems(), 0, 'Queue is empty');
update_create_fetch_task($projecta);
$this->assertEqual($queue->numberOfItems(), 1, 'Queue contains one item');
update_create_fetch_task($projectb);
$this->assertEqual($queue->numberOfItems(), 2, 'Queue contains two items');
// Try to add project a again.
update_create_fetch_task($projecta);
$this->assertEqual($queue->numberOfItems(), 2, 'Queue still contains two items');
// Clear cache and try again.
_update_cache_clear();
drupal_static_reset('_update_create_fetch_task');
update_create_fetch_task($projecta);
$this->assertEqual($queue->numberOfItems(), 2, 'Queue contains two items');
}
/**
* Sets the version to 7.0 when no project-specific mapping is defined.
*/
protected function setSystemInfo7_0() {
$setting = array(
'#all' => array(
'version' => '7.0',
),
);
variable_set('update_test_system_info', $setting);
}
}
/**
* Tests behavior related to handling updates to contributed modules and themes.
*/
class UpdateTestContribCase extends UpdateTestHelper {
public static function getInfo() {
return array(
'name' => 'Update contrib functionality',
'description' => 'Tests how the Update Manager module handles contributed modules and themes in a series of functional tests using mock XML data.',
'group' => 'Update',
);
}
function setUp() {
parent::setUp('update_test', 'update', 'aaa_update_test', 'bbb_update_test', 'ccc_update_test');
$admin_user = $this->drupalCreateUser(array('administer site configuration'));
$this->drupalLogin($admin_user);
}
/**
* Tests when there is no available release data for a contrib module.
*/
function testNoReleasesAvailable() {
$system_info = array(
'#all' => array(
'version' => '7.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
$this->refreshUpdateStatus(array('drupal' => '0', 'aaa_update_test' => 'no-releases'));
$this->drupalGet('admin/reports/updates');
// Cannot use $this->standardTests() because we need to check for the
// 'No available releases found' string.
$this->assertRaw('<h3>' . t('Drupal core') . '</h3>');
$this->assertRaw(l(t('Drupal'), 'http://example.com/project/drupal'));
$this->assertText(t('Up to date'));
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertNoText(t('Update available'));
$this->assertText(t('No available releases found'));
$this->assertNoRaw(l(t('AAA Update test'), 'http://example.com/project/aaa_update_test'));
}
/**
* Tests the basic functionality of a contrib module on the status report.
*/
function testUpdateContribBasic() {
$system_info = array(
'#all' => array(
'version' => '7.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
$this->refreshUpdateStatus(
array(
'drupal' => '0',
'aaa_update_test' => '1_0',
)
);
$this->standardTests();
$this->assertText(t('Up to date'));
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertNoText(t('Update available'));
$this->assertRaw(l(t('AAA Update test'), 'http://example.com/project/aaa_update_test'), 'Link to aaa_update_test project appears.');
}
/**
* Tests that contrib projects are ordered by project name.
*
* If a project contains multiple modules, we want to make sure that the
* available updates report is sorted by the parent project names, not by the
* names of the modules included in each project. In this test case, we have
* two contrib projects, "BBB Update test" and "CCC Update test". However, we
* have a module called "aaa_update_test" that's part of the "CCC Update test"
* project. We need to make sure that we see the "BBB" project before the
* "CCC" project, even though "CCC" includes a module that's processed first
* if you sort alphabetically by module name (which is the order we see things
* inside system_rebuild_module_data() for example).
*/
function testUpdateContribOrder() {
// We want core to be version 7.0.
$system_info = array(
'#all' => array(
'version' => '7.0',
),
// All the rest should be visible as contrib modules at version 7.x-1.0.
// aaa_update_test needs to be part of the "CCC Update test" project,
// which would throw off the report if we weren't properly sorting by
// the project names.
'aaa_update_test' => array(
'project' => 'ccc_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
// This should be its own project, and listed first on the report.
'bbb_update_test' => array(
'project' => 'bbb_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
// This will contain both aaa_update_test and ccc_update_test, and
// should come after the bbb_update_test project.
'ccc_update_test' => array(
'project' => 'ccc_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
$this->refreshUpdateStatus(array('drupal' => '0', '#all' => '1_0'));
$this->standardTests();
// We're expecting the report to say all projects are up to date.
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
// We want to see all 3 module names listed, since they'll show up either
// as project names or as modules under the "Includes" listing.
$this->assertText(t('AAA Update test'));
$this->assertText(t('BBB Update test'));
$this->assertText(t('CCC Update test'));
// We want aaa_update_test included in the ccc_update_test project, not as
// its own project on the report.
$this->assertNoRaw(l(t('AAA Update test'), 'http://example.com/project/aaa_update_test'), 'Link to aaa_update_test project does not appear.');
// The other two should be listed as projects.
$this->assertRaw(l(t('BBB Update test'), 'http://example.com/project/bbb_update_test'), 'Link to bbb_update_test project appears.');
$this->assertRaw(l(t('CCC Update test'), 'http://example.com/project/ccc_update_test'), 'Link to bbb_update_test project appears.');
// We want to make sure we see the BBB project before the CCC project.
// Instead of just searching for 'BBB Update test' or something, we want
// to use the full markup that starts the project entry itself, so that
// we're really testing that the project listings are in the right order.
$bbb_project_link = '<div class="project"><a href="http://example.com/project/bbb_update_test">BBB Update test</a>';
$ccc_project_link = '<div class="project"><a href="http://example.com/project/ccc_update_test">CCC Update test</a>';
$this->assertTrue(strpos($this->drupalGetContent(), $bbb_project_link) < strpos($this->drupalGetContent(), $ccc_project_link), "'BBB Update test' project is listed before the 'CCC Update test' project");
}
/**
* Tests that subthemes are notified about security updates for base themes.
*/
function testUpdateBaseThemeSecurityUpdate() {
// Only enable the subtheme, not the base theme.
db_update('system')
->fields(array('status' => 1))
->condition('type', 'theme')
->condition('name', 'update_test_subtheme')
->execute();
// Define the initial state for core and the subtheme.
$system_info = array(
// We want core to be version 7.0.
'#all' => array(
'version' => '7.0',
),
// Show the update_test_basetheme
'update_test_basetheme' => array(
'project' => 'update_test_basetheme',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
// Show the update_test_subtheme
'update_test_subtheme' => array(
'project' => 'update_test_subtheme',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
$xml_mapping = array(
'drupal' => '0',
'update_test_subtheme' => '1_0',
'update_test_basetheme' => '1_1-sec',
);
$this->refreshUpdateStatus($xml_mapping);
$this->assertText(t('Security update required!'));
$this->assertRaw(l(t('Update test base theme'), 'http://example.com/project/update_test_basetheme'), 'Link to the Update test base theme project appears.');
}
/**
* Tests that the admin theme is always notified about security updates.
*/
function testUpdateAdminThemeSecurityUpdate() {
// Disable the admin theme.
db_update('system')
->fields(array('status' => 0))
->condition('type', 'theme')
->condition('name', 'update_test_%', 'LIKE')
->execute();
variable_set('admin_theme', 'update_test_admintheme');
// Define the initial state for core and the themes.
$system_info = array(
'#all' => array(
'version' => '7.0',
),
'update_test_admintheme' => array(
'project' => 'update_test_admintheme',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
'update_test_basetheme' => array(
'project' => 'update_test_basetheme',
'version' => '7.x-1.1',
'hidden' => FALSE,
),
'update_test_subtheme' => array(
'project' => 'update_test_subtheme',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
variable_set('update_check_disabled', FALSE);
$xml_mapping = array(
// This is enough because we don't check the update status of the admin
// theme. We want to check that the admin theme is included in the list.
'drupal' => '0',
);
$this->refreshUpdateStatus($xml_mapping);
// The admin theme is displayed even if it's disabled.
$this->assertText('update_test_admintheme', "The admin theme is checked for update even if it's disabled");
// The other disabled themes are not displayed.
$this->assertNoText('update_test_basetheme', 'Disabled theme is not checked for update in the list.');
$this->assertNoText('update_test_subtheme', 'Disabled theme is not checked for update in the list.');
}
/**
* Tests that disabled themes are only shown when desired.
*/
function testUpdateShowDisabledThemes() {
// Make sure all the update_test_* themes are disabled.
db_update('system')
->fields(array('status' => 0))
->condition('type', 'theme')
->condition('name', 'update_test_%', 'LIKE')
->execute();
// Define the initial state for core and the test contrib themes.
$system_info = array(
// We want core to be version 7.0.
'#all' => array(
'version' => '7.0',
),
// The update_test_basetheme should be visible and up to date.
'update_test_basetheme' => array(
'project' => 'update_test_basetheme',
'version' => '7.x-1.1',
'hidden' => FALSE,
),
// The update_test_subtheme should be visible and up to date.
'update_test_subtheme' => array(
'project' => 'update_test_subtheme',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
// When there are contributed modules in the site's file system, the
// total number of attempts made in the test may exceed the default value
// of update_max_fetch_attempts. Therefore this variable is set very high
// to avoid test failures in those cases.
variable_set('update_max_fetch_attempts', 99999);
variable_set('update_test_system_info', $system_info);
$xml_mapping = array(
'drupal' => '0',
'update_test_subtheme' => '1_0',
'update_test_basetheme' => '1_1-sec',
);
$base_theme_project_link = l(t('Update test base theme'), 'http://example.com/project/update_test_basetheme');
$sub_theme_project_link = l(t('Update test subtheme'), 'http://example.com/project/update_test_subtheme');
foreach (array(TRUE, FALSE) as $check_disabled) {
variable_set('update_check_disabled', $check_disabled);
$this->refreshUpdateStatus($xml_mapping);
// In neither case should we see the "Themes" heading for enabled themes.
$this->assertNoText(t('Themes'));
if ($check_disabled) {
$this->assertText(t('Disabled themes'));
$this->assertRaw($base_theme_project_link, 'Link to the Update test base theme project appears.');
$this->assertRaw($sub_theme_project_link, 'Link to the Update test subtheme project appears.');
}
else {
$this->assertNoText(t('Disabled themes'));
$this->assertNoRaw($base_theme_project_link, 'Link to the Update test base theme project does not appear.');
$this->assertNoRaw($sub_theme_project_link, 'Link to the Update test subtheme project does not appear.');
}
}
}
/**
* Makes sure that if we fetch from a broken URL, sane things happen.
*/
function testUpdateBrokenFetchURL() {
$system_info = array(
'#all' => array(
'version' => '7.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
'bbb_update_test' => array(
'project' => 'bbb_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
'ccc_update_test' => array(
'project' => 'ccc_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
$xml_mapping = array(
'drupal' => '0',
'aaa_update_test' => '1_0',
'bbb_update_test' => 'does-not-exist',
'ccc_update_test' => '1_0',
);
$this->refreshUpdateStatus($xml_mapping);
$this->assertText(t('Up to date'));
// We're expecting the report to say most projects are up to date, so we
// hope that 'Up to date' is not unique.
$this->assertNoUniqueText(t('Up to date'));
// It should say we failed to get data, not that we're missing an update.
$this->assertNoText(t('Update available'));
// We need to check that this string is found as part of a project row,
// not just in the "Failed to get available update data for ..." message
// at the top of the page.
$this->assertRaw('<div class="version-status">' . t('Failed to get available update data'));
// We should see the output messages from fetching manually.
$this->assertUniqueText(t('Checked available update data for 3 projects.'));
$this->assertUniqueText(t('Failed to get available update data for one project.'));
// The other two should be listed as projects.
$this->assertRaw(l(t('AAA Update test'), 'http://example.com/project/aaa_update_test'), 'Link to aaa_update_test project appears.');
$this->assertNoRaw(l(t('BBB Update test'), 'http://example.com/project/bbb_update_test'), 'Link to bbb_update_test project does not appear.');
$this->assertRaw(l(t('CCC Update test'), 'http://example.com/project/ccc_update_test'), 'Link to bbb_update_test project appears.');
}
/**
* Checks that hook_update_status_alter() works to change a status.
*
* We provide the same external data as if aaa_update_test 7.x-1.0 were
* installed and that was the latest release. Then we use
* hook_update_status_alter() to try to mark this as missing a security
* update, then assert if we see the appropriate warnings on the right pages.
*/
function testHookUpdateStatusAlter() {
variable_set('allow_authorize_operations', TRUE);
$update_admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer software updates'));
$this->drupalLogin($update_admin_user);
$system_info = array(
'#all' => array(
'version' => '7.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '7.x-1.0',
'hidden' => FALSE,
),
);
variable_set('update_test_system_info', $system_info);
$update_status = array(
'aaa_update_test' => array(
'status' => UPDATE_NOT_SECURE,
),
);
variable_set('update_test_update_status', $update_status);
$this->refreshUpdateStatus(
array(
'drupal' => '0',
'aaa_update_test' => '1_0',
)
);
$this->drupalGet('admin/reports/updates');
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertText(t('Security update required!'));
$this->assertRaw(l(t('AAA Update test'), 'http://example.com/project/aaa_update_test'), 'Link to aaa_update_test project appears.');
// Visit the reports page again without the altering and make sure the
// status is back to normal.
variable_set('update_test_update_status', array());
$this->drupalGet('admin/reports/updates');
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertNoText(t('Security update required!'));
$this->assertRaw(l(t('AAA Update test'), 'http://example.com/project/aaa_update_test'), 'Link to aaa_update_test project appears.');
// Turn the altering back on and visit the Update manager UI.
variable_set('update_test_update_status', $update_status);
$this->drupalGet('admin/modules/update');
$this->assertText(t('Security update'));
// Turn the altering back off and visit the Update manager UI.
variable_set('update_test_update_status', array());
$this->drupalGet('admin/modules/update');
$this->assertNoText(t('Security update'));
}
}
/**
* Tests project upload and extract functionality.
*/
class UpdateTestUploadCase extends UpdateTestHelper {
public static function getInfo() {
return array(
'name' => 'Upload and extract module functionality',
'description' => 'Tests the Update Manager module\'s upload and extraction functionality.',
'group' => 'Update',
);
}
public function setUp() {
parent::setUp('update', 'update_test');
variable_set('allow_authorize_operations', TRUE);
$admin_user = $this->drupalCreateUser(array('administer software updates', 'administer site configuration'));
$this->drupalLogin($admin_user);
}
/**
* Tests upload and extraction of a module.
*/
public function testUploadModule() {
// Images are not valid archives, so get one and try to install it. We
// need an extra variable to store the result of drupalGetTestFiles()
// since reset() takes an argument by reference and passing in a constant
// emits a notice in strict mode.
$imageTestFiles = $this->drupalGetTestFiles('image');
$invalidArchiveFile = reset($imageTestFiles);
$edit = array(
'files[project_upload]' => $invalidArchiveFile->uri,
);
// This also checks that the correct archive extensions are allowed.
$this->drupalPost('admin/modules/install', $edit, t('Install'));
$this->assertText(t('Only files with the following extensions are allowed: @archive_extensions.', array('@archive_extensions' => archiver_get_extensions())),'Only valid archives can be uploaded.');
// Check to ensure an existing module can't be reinstalled. Also checks that
// the archive was extracted since we can't know if the module is already
// installed until after extraction.
$validArchiveFile = drupal_get_path('module', 'update') . '/tests/aaa_update_test.tar.gz';
$edit = array(
'files[project_upload]' => $validArchiveFile,
);
$this->drupalPost('admin/modules/install', $edit, t('Install'));
$this->assertText(t('@module_name is already installed.', array('@module_name' => 'AAA Update test')), 'Existing module was extracted and not reinstalled.');
}
/**
* Ensures that archiver extensions are properly merged in the UI.
*/
function testFileNameExtensionMerging() {
$this->drupalGet('admin/modules/install');
// Make sure the bogus extension supported by update_test.module is there.
$this->assertPattern('/file extensions are supported:.*update-test-extension/', "Found 'update-test-extension' extension");
// Make sure it didn't clobber the first option from core.
$this->assertPattern('/file extensions are supported:.*tar/', "Found 'tar' extension");
}
/**
* Checks the messages on update manager pages when missing a security update.
*/
function testUpdateManagerCoreSecurityUpdateMessages() {
$setting = array(
'#all' => array(
'version' => '7.0',
),
);
variable_set('update_test_system_info', $setting);
variable_set('update_fetch_url', url('update-test', array('absolute' => TRUE)));
variable_set('update_test_xml_map', array('drupal' => '2-sec'));
// Initialize the update status.
$this->drupalGet('admin/reports/updates');
// Now, make sure none of the Update manager pages have duplicate messages
// about core missing a security update.
$this->drupalGet('admin/modules/install');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/modules/update');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/appearance/install');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/appearance/update');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates/install');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates/update');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/update/ready');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
}
/**
* Tests update functionality unrelated to the database.
*/
class UpdateCoreUnitTestCase extends DrupalUnitTestCase {
public static function getInfo() {
return array(
'name' => "Unit tests",
'description' => 'Test update funcionality unrelated to the database.',
'group' => 'Update',
);
}
function setUp() {
parent::setUp('update');
module_load_include('inc', 'update', 'update.fetch');
}
/**
* Tests that _update_build_fetch_url() builds the URL correctly.
*/
function testUpdateBuildFetchUrl() {
//first test that we didn't break the trivial case
$project['name'] = 'update_test';
$project['project_type'] = '';
$project['info']['version'] = '';
$project['info']['project status url'] = 'http://www.example.com';
$project['includes'] = array('module1' => 'Module 1', 'module2' => 'Module 2');
$site_key = '';
$expected = 'http://www.example.com/' . $project['name'] . '/' . DRUPAL_CORE_COMPATIBILITY;
$url = _update_build_fetch_url($project, $site_key);
$this->assertEqual($url, $expected, "'$url' when no site_key provided should be '$expected'.");
//For disabled projects it shouldn't add the site key either.
$site_key = 'site_key';
$project['project_type'] = 'disabled';
$expected = 'http://www.example.com/' . $project['name'] . '/' . DRUPAL_CORE_COMPATIBILITY;
$url = _update_build_fetch_url($project, $site_key);
$this->assertEqual($url, $expected, "'$url' should be '$expected' for disabled projects.");
//for enabled projects, adding the site key
$project['project_type'] = '';
$expected = 'http://www.example.com/' . $project['name'] . '/' . DRUPAL_CORE_COMPATIBILITY;
$expected .= '?site_key=site_key';
$expected .= '&list=' . rawurlencode('module1,module2');
$url = _update_build_fetch_url($project, $site_key);
$this->assertEqual($url, $expected, "When site_key provided, '$url' should be '$expected'.");
// http://drupal.org/node/1481156 test incorrect logic when URL contains
// a question mark.
$project['info']['project status url'] = 'http://www.example.com/?project=';
$expected = 'http://www.example.com/?project=/' . $project['name'] . '/' . DRUPAL_CORE_COMPATIBILITY;
$expected .= '&site_key=site_key';
$expected .= '&list=' . rawurlencode('module1,module2');
$url = _update_build_fetch_url($project, $site_key);
$this->assertEqual($url, $expected, "When ? is present, '$url' should be '$expected'.");
}
}