Compare commits

..
12 Commits
273 changed files with 16914 additions and 4169 deletions
+1
View File
@@ -21,3 +21,4 @@ node_modules
.sass-cache
typescript
.directory
+4
View File
@@ -24,3 +24,7 @@ termreferencetree
views
wysiwyg
views_rss_media
node_export :
- https://www.drupal.org/node/1869918
- https://www.drupal.org/node/1911638
-4
View File
@@ -1,4 +0,0 @@
[Dolphin]
Timestamp=2015,4,27,12,4,40
Version=3
ViewMode=2
@@ -203,7 +203,7 @@ function features_export_form($form, $form_state, $feature = NULL) {
$form['advanced']['generate'] = array(
'#type' => 'submit',
'#value' => t('Generate feature'),
'#submit' => array('features_export_build_form_submit'),
'#submit' => array('features_export_build_form_submit', 'features_form_rebuild'),
);
}
// build the Component Listing panel on the right
@@ -239,7 +239,7 @@ function features_export_form($form, $form_state, $feature = NULL) {
'#type' => 'submit',
'#value' => t('Download feature'),
'#weight' => 10,
'#submit' => array('features_export_build_form_submit'),
'#submit' => array('features_export_build_form_submit', 'features_form_rebuild'),
);
$form['#attached']['library'][] = array('system', 'ui.dialog');
@@ -597,6 +597,7 @@ function _features_export_build($feature, &$form_state) {
$component_export['selected'][$section] = array();
}
$options = features_invoke($component, 'features_export_options');
drupal_alter('features_export_options', $options, $component);
if (!empty($options)) {
$exported_components = !empty($exported_features_info[$component]) ? $exported_features_info[$component] : array();
$new_components = !empty($new_features_info[$component]) ? $new_features_info[$component] : array();
@@ -843,7 +844,7 @@ function _features_export_generate($export, $form_state, $feature = NULL) {
}
// If either update status-related keys are provided, add a project key
// corresponding to the module name.
if (!empty($form_state['values']['version']) || !empty($form_state['values']['project_status_url'])) {
if (!empty($form_state['values']['version']) && !empty($form_state['values']['project_status_url'])) {
$export['project'] = $form_state['values']['module_name'];
}
if (!empty($form_state['values']['version'])) {
@@ -900,6 +901,35 @@ function features_export_build_form_submit($form, &$form_state) {
$tar = array();
$filenames = array();
// Copy any files if _files key is there.
if (!empty($files['_files'])) {
foreach ($files['_files'] as $file_name => $file_info) {
if ($generate) {
// See if files are in a sub directory.
if (strpos($file_name, '/')) {
$file_directory = $directory . '/' . substr($file_name, 0, strrpos($file_name, '/'));
if (!is_dir($file_directory)) {
mkdir($file_directory);
}
}
if (!empty($file_info['file_path'])) {
file_unmanaged_copy($file_info['file_path'], "{$directory}/{$file_name}", FILE_EXISTS_REPLACE);
}
elseif ($file_info['file_content']) {
file_put_contents("{$directory}/{$file_name}", $file_info['file_content']);
}
}
else {
if (!empty($file_info['file_path'])) {
print features_tar_create("{$module_name}/{$file_name}", file_get_contents($file_info['file_path']));
}
elseif ($file_info['file_content']) {
features_tar_create("{$directory}/{$file_name}", $file_info['file_content']);
}
}
}
unset($files['_files']);
}
foreach ($files as $extension => $file_contents) {
if (!in_array($extension, array('module', 'info'))) {
$extension .= '.inc';
@@ -973,28 +1003,14 @@ function features_filter_hidden($module) {
* Form constructor for the features configuration form.
*/
function features_admin_form($form, $form_state) {
$features = _features_get_features_list();
$modules = array_filter(features_get_modules(), 'features_filter_hidden');
$conflicts = features_get_conflicts();
// Load export functions to use in comparison.
module_load_include('inc', 'features', 'features.export');
// Clear & rebuild key caches
features_get_info(NULL, NULL, TRUE);
features_rebuild();
$modules = array_filter(features_get_modules(), 'features_filter_hidden');
$features = array_filter(features_get_features(), 'features_filter_hidden');
$conflicts = features_get_conflicts();
foreach ($modules as $key => $module) {
if ($module->status && !empty($module->info['dependencies'])) {
foreach ($module->info['dependencies'] as $dependent) {
if (isset($features[$dependent])) {
$features[$dependent]->dependents[$key] = $module->info['name'];
}
}
}
}
if ( empty($features) ) {
if (empty($features) ) {
$form['no_features'] = array(
'#markup' => t('No Features were found. Please use the !create_link link to create
a new Feature module, or upload an existing Feature to your modules directory.',
@@ -1328,6 +1344,13 @@ function features_form_submit(&$form, &$form_state) {
}
}
/**
* Submit handler for the 'manage features' form rebuild button.
*/
function features_form_rebuild() {
cache_clear_all('features:features_list', 'cache');
}
/**
* Form for clearing cache after enabling a feature.
*/
@@ -1588,3 +1611,42 @@ function _features_get_used($module_name = NULL) {
$features_ignore_conflicts = $old_value;
return $conflicts;
}
/**
* Retrieves the array of features as expected on the Manage Features form.
* Uses caching for performance reasons if caching is enabled.
*
* @internal - This function might return cached result with outdated data,
* use with caution.
*/
function _features_get_features_list() {
$features = array();
$cache = cache_get('features:features_list');
if ($cache) {
$features = $cache->data;
}
if (empty($features)) {
// Clear & rebuild key caches
features_get_info(NULL, NULL, TRUE);
features_rebuild();
$modules = array_filter(features_get_modules(), 'features_filter_hidden');
$features = array_filter(features_get_features(), 'features_filter_hidden');
foreach ($modules as $key => $module) {
if ($module->status && !empty($module->info['dependencies'])) {
foreach ($module->info['dependencies'] as $dependent) {
if (isset($features[$dependent])) {
$features[$dependent]->dependents[$key] = $module->info['name'];
}
}
}
}
cache_set('features:features_list', $features);
}
return $features;
}
@@ -157,7 +157,8 @@ function hook_features_export_options() {
* of the module, e.g. the key for `hook_example` should simply be `example`
* The values in the array can also be in the form of an associative array
* with the required key of 'code' and optional key of 'args', if 'args' need
* to be added to the hook.
* to be added to the hook. Alternate it can be an associative array in the
* same style as hook_features_export_files() to add additional files.
*/
function hook_features_export_render($module_name, $data, $export = NULL) {
$code = array();
@@ -314,6 +315,26 @@ function hook_features_pipe_alter(&$pipe, $data, $export) {
}
}
/**
* Add extra files to the exported file.
*
* @return array
* An array of files, keyed by file name that will appear in feature and
* with either file_path key to indicate where to copy the file from or
* file_content key to indicate the contents of the file.
*/
function hook_features_export_files($module_name, $export) {
return array('css/main.css' => array('file_content' => 'body {background-color:blue;}'));
}
/**
* Alter the extra files added to the export.
*/
function hook_features_export_files_alter(&$files, $module_name, $export) {
$files['css/main.css']['file_content'] = 'body {background-color:black;}';
}
/**
* @defgroup features_component_alter_hooks Feature's component alter hooks
* @{
@@ -610,6 +610,28 @@ function _drush_features_export($info, $module_name = NULL, $directory = NULL) {
drupal_flush_all_caches();
$export = _drush_features_generate_export($info, $module_name);
$files = features_export_render($export, $module_name, TRUE);
// Copy any files if _files key is there.
if (!empty($files['_files'])) {
foreach ($files['_files'] as $file_name => $file_info) {
// See if files are in a sub directory.
if (strpos($file_name, '/')) {
$file_directory = $directory . '/' . substr($file_name, 0, strrpos($file_name, '/'));
if (!is_dir($file_directory)) {
drush_op('mkdir', $file_directory);
}
}
if (!empty($file_info['file_path'])) {
drush_op('file_unmanaged_copy', $file_info['file_path'], "{$directory}/{$file_name}", FILE_EXISTS_REPLACE);
}
elseif (!empty($file_info['file_content'])) {
drush_op('file_put_contents', "{$directory}/{$file_name}", $file_info['file_content']);
}
else {
drush_log(dt("Entry for @file_name.in !module is invalid. ", array('!module' => $module_name, '@file_name' => $file_name)), 'ok');
}
}
unset($files['_files']);
}
foreach ($files as $extension => $file_contents) {
if (!in_array($extension, array('module', 'info'))) {
$extension .= '.inc';
@@ -45,6 +45,9 @@ function features_populate($info, $module_name) {
* @return fully populated $export array.
*/
function _features_populate($pipe, &$export, $module_name = '', $reset = FALSE) {
// Ensure that the export will be created in the english language.
_features_set_export_language();
if ($reset) {
drupal_static_reset(__FUNCTION__);
}
@@ -295,6 +298,11 @@ function features_export_render($export, $module_name, $reset = FALSE) {
}
foreach ($hooks as $hook_name => $hook_info) {
// These are purely files that will be copied over.
if (is_array($hook_info) && (!empty($hook_info['file_path']) || !empty($hook_info['file_content']))) {
$code['_files'][$hook_name] = $hook_info;
continue;
}
$hook_code = is_array($hook_info) ? $hook_info['code'] : $hook_info;
$hook_args = is_array($hook_info) && !empty($hook_info['args']) ? $hook_info['args'] : '';
$hook_file = is_array($hook_info) && !empty($hook_info['file']) ? $hook_info['file'] : $file['name'];
@@ -305,7 +313,17 @@ function features_export_render($export, $module_name, $reset = FALSE) {
// Finalize strings to be written to files
$code = array_filter($code);
foreach ($code as $filename => $contents) {
$code[$filename] = "<?php\n/**\n * @file\n * {$module_name}.{$filename}.inc\n */\n\n". implode("\n\n", $contents) ."\n";
if ($filename != '_files') {
$code[$filename] = "<?php\n/**\n * @file\n * {$module_name}.{$filename}.inc\n */\n\n". implode("\n\n", $contents) ."\n";
}
}
// Allow extra files be added to feature.
if ($files = module_invoke_all('features_export_files', $module_name, $export)) {
$code['_files'] = !empty($code['_files']) ? $code['_files'] + $files : $files;
}
if (!empty($code['_files'])) {
drupal_alter('features_export_files', $code['_files'], $module_name, $export);
}
// Generate info file output
@@ -394,8 +412,8 @@ function features_detect_overrides($module) {
$overridden = array();
// Compare feature info
_features_sanitize($module->info);
_features_sanitize($export);
features_sanitize($module->info);
features_sanitize($export);
$compare = array('normal' => features_export_info($export), 'default' => features_export_info($module->info));
if ($compare['normal'] !== $compare['default']) {
@@ -408,8 +426,8 @@ function features_detect_overrides($module) {
if ($state != FEATURES_DEFAULT) {
$normal = features_get_normal($component, $module->name);
$default = features_get_default($component, $module->name);
_features_sanitize($normal);
_features_sanitize($default);
features_sanitize($normal, $component);
features_sanitize($default, $component);
$compare = array('normal' => features_var_export($normal), 'default' => features_var_export($default));
if (_features_linetrim($compare['normal']) !== _features_linetrim($compare['default'])) {
@@ -663,8 +681,7 @@ function features_get_signature($state = 'default', $module_name, $component, $r
break;
}
if (!empty($objects)) {
$objects = (array) $objects;
_features_sanitize($objects);
features_sanitize($objects, $component);
return md5(_features_linetrim(features_var_export($objects)));
}
return FALSE;
@@ -721,7 +738,7 @@ function features_get_normal($component, $module_name, $reset = FALSE) {
// Special handling for dependencies component.
if ($component === 'dependencies') {
$cache[$module_name][$component] = isset($module->info['dependencies']) ? array_filter($module->info['dependencies'], 'module_exists') : array();
$cache[$module_name][$component] = isset($module->info['dependencies']) ? array_filter($module->info['dependencies'], '_features_module_exists') : array();
}
// All other components.
else {
@@ -739,6 +756,17 @@ function features_get_normal($component, $module_name, $reset = FALSE) {
return isset($cache[$module_name][$component]) ? $cache[$module_name][$component] : FALSE;
}
/**
* Helper function to determine if a module is enabled
* @param $module
* This module name comes from the .info file and can have version info in it.
*/
function _features_module_exists($module) {
$parsed_dependency = drupal_parse_dependency($module);
$name = $parsed_dependency['name'];
return module_exists($name);
}
/**
* Get defaults for a given module/component pair.
*/
@@ -970,25 +998,52 @@ function _features_linetrim($code) {
return implode("\n", $code);
}
/**
* Helper function to "sanitize" an array or object.
* Converts everything to an array, sorts the keys, removes recursion.
* @param $array
* @param $component string name of component
* @param bool $remove_empty if set, remove null or empty values for assoc arrays.
*/
function features_sanitize(&$array, $component = NULL, $remove_empty = TRUE) {
// make a deep copy of data to prevent problems when removing recursion later.
$array = unserialize(serialize($array));
if (isset($component)) {
$ignore_keys = _features_get_ignore_keys($component);
// remove keys to be ignored
// doing this now allows us to better control which recursive parts are removed
if (count($ignore_keys)) {
_features_remove_ignores($array, $ignore_keys);
}
}
features_remove_recursion($array);
_features_sanitize($array, $remove_empty);
}
/**
* "Sanitizes" an array recursively, performing two key operations:
* - Sort an array by its keys (assoc) or values (non-assoc)
* - Remove any null or empty values for associative arrays (array_filter()).
* @param bool $remove_empty if set, remove null or empty values for assoc arrays.
*/
function _features_sanitize(&$array) {
function _features_sanitize(&$array, $remove_empty = TRUE) {
if (is_object($array)) {
$array = get_object_vars($array);
}
if (is_array($array)) {
$is_assoc = _features_is_assoc($array);
if ($is_assoc) {
ksort($array, SORT_STRING);
$array = array_filter($array);
if ($remove_empty) {
$array = array_filter($array);
}
}
else {
sort($array);
}
foreach ($array as $k => $v) {
if (is_array($v)) {
if (is_array($v) or is_object($v)) {
_features_sanitize($array[$k]);
if ($is_assoc && empty($array[$k])) {
if ($remove_empty && $is_assoc && empty($array[$k])) {
unset($array[$k]);
}
}
@@ -1010,3 +1065,127 @@ function _features_sanitize(&$array) {
function _features_is_assoc($array) {
return (is_array($array) && (0 !== count(array_diff_key($array, array_keys(array_keys($array)))) || count($array)==0));
}
/**
* Removes recursion from an object or array.
*
* @param $item
* An object or array passed by reference.
*/
function features_remove_recursion(&$item) {
$uniqid = __FUNCTION__ . mt_rand(); // use of uniqid() here impacts performance
$stack = array();
return _features_remove_recursion($item, $stack, $uniqid);
}
/**
* Helper to removes recursion from an object/array.
*
* @param $item
* An object or array passed by reference.
*/
function _features_remove_recursion(&$object, &$stack = array(), $uniqid) {
if ((is_object($object) || is_array($object)) && $object) {
$in_stack = FALSE;
foreach ($stack as &$item) {
if (_features_is_ref_to($object, $item, $uniqid)) {
$in_stack = TRUE;
break;
}
}
unset($item);
if (!$in_stack) {
$stack[] = $object;
foreach ($object as $key => &$subobject) {
if (_features_remove_recursion($subobject, $stack, $uniqid)) {
if (is_object($object)) {
unset($object->$key);
}
else {
unset($object[$key]);
}
}
}
unset($subobject);
}
else {
return TRUE;
}
}
return FALSE;
}
/**
* Helper function in determining equality of arrays. Credit to http://stackoverflow.com/a/4263181
*
* @see _features_remove_recursion()
*
* @param $a
* object a
* @param $b
* object b
* @return bool
*
*/
function _features_is_ref_to(&$a, &$b, $uniqid) {
if (is_object($a) && is_object($b)) {
return ($a === $b);
}
$temp_a = $a;
$temp_b = $b;
$b = $uniqid;
if ($a === $uniqid) $return = true;
else $return = false;
$a = $temp_a;
$b = $temp_b;
return $return;
}
/**
* Helper to removes a set of keys an object/array.
*
* @param $item
* An object or array passed by reference.
* @param $ignore_keys
* Array of keys to be ignored. Values are the level of the key.
* @param $level
* Level of key to remove. Up to 2 levels deep because $item can still be
* recursive
*/
function _features_remove_ignores(&$item, $ignore_keys, $level = -1) {
$is_object = is_object($item);
if (!is_array($item) && !is_object($item)) {
return;
}
foreach ($item as $key => $value) {
if (isset($ignore_keys[$key]) && ($ignore_keys[$key] == $level)) {
if ($is_object) {
unset($item->$key);
}
else {
unset($item[$key]);
}
}
elseif (($level < 2) && (is_array($value) || is_object($value))) {
_features_remove_ignores($value, $ignore_keys, $level+1);
}
}
}
/**
* Returns an array of keys to be ignored for various exportables
* @param $component
* The component to retrieve ignore_keys from.
*/
function _features_get_ignore_keys($component) {
static $cache;
if (!isset($cache[$component])) {
$cache[$component] = module_invoke_all('features_ignore', $component);
}
return $cache[$component];
}
@@ -6,9 +6,9 @@ files[] = tests/features.test
configure = admin/structure/features/settings
; Information added by Drupal.org packaging script on 2015-04-13
version = "7.x-2.5"
; Information added by Drupal.org packaging script on 2015-06-24
version = "7.x-2.6"
core = "7.x"
project = "features"
datestamp = "1428944073"
datestamp = "1435165997"
@@ -5,6 +5,15 @@
* Install, update and uninstall functions for the features module.
*/
/**
* Implements hook_schema().
*/
function features_schema() {
$schema['cache_features'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_features']['description'] = 'Cache table for features to store module info.';
return $schema;
}
/**
* Implements hook_install().
*/
@@ -33,7 +42,7 @@ function features_uninstall() {
->execute();
db_delete('variable')
->condition('name', 'features_component_locked_%', 'LIKE')
->execute();variable_del('features_component_locked_' . $component);
->execute();
if (db_table_exists('menu_custom')) {
db_delete('menu_custom')
@@ -130,3 +139,13 @@ function features_update_6101() {
}
return array();
}
/**
* Add {cache_features} table.
*/
function features_update_7200() {
if (!db_table_exists('cache_features')) {
$schema = drupal_get_schema_unprocessed('system', 'cache');
db_create_table('cache_features', $schema);
}
}
@@ -128,10 +128,12 @@ jQuery.fn.sortElements = (function(){
if (!$(this).hasClass('features-checkall')) {
var key = $(this).attr('name');
var matches = key.match(/^([^\[]+)(\[.+\])?\[(.+)\]\[(.+)\]$/);
var component = matches[1];
var item = matches[4];
if ((component in moduleConflicts) && (moduleConflicts[component].indexOf(item) != -1)) {
$(this).parent().addClass('features-conflict');
if (matches != null) {
var component = matches[1];
var item = matches[4];
if ((component in moduleConflicts) && (moduleConflicts[component].indexOf(item) != -1)) {
$(this).parent().addClass('features-conflict');
}
}
}
});
@@ -290,7 +292,7 @@ jQuery.fn.sortElements = (function(){
}
// Handle component selection UI
$('#features-export-wrapper input[type=checkbox]', context).click(function() {
$('#features-export-wrapper input[type=checkbox]:not(.processed)', context).addClass('processed').click(function() {
_resetTimeout();
if ($(this).hasClass('component-select')) {
moveCheckbox(this, 'added', true);
@@ -268,14 +268,17 @@ function features_theme() {
* Implements hook_flush_caches().
*/
function features_flush_caches() {
if (variable_get('features_rebuild_on_flush', TRUE)) {
if (($modules_changed = variable_get('features_modules_changed', FALSE)) || variable_get('features_rebuild_on_flush', TRUE)) {
if ($modules_changed) {
variable_set('features_modules_changed', FALSE);
}
features_rebuild();
// Don't flush the modules cache during installation, for performance reasons.
if (variable_get('install_task') == 'done') {
features_get_modules(NULL, TRUE);
}
}
return array();
return array('cache_features');
}
/**
@@ -349,6 +352,15 @@ function features_modules_disabled($modules) {
* Implements hook_modules_enabled().
*/
function features_modules_enabled($modules) {
// Allow distributions to disable this behavior and rebuild the features
// manually inside a batch.
if (!variable_get('features_rebuild_on_module_install', TRUE)) {
return;
}
// mark modules as being changed for test in features_flush_caches
variable_set('features_modules_changed', TRUE);
// Go through all modules and gather features that can be enabled.
$items = array();
foreach ($modules as $module) {
@@ -385,7 +397,7 @@ function features_include($reset = FALSE) {
// Features provides integration on behalf of these modules.
// The features include provides handling for the feature dependencies.
// Note that ctools is placed last because it implements hooks "dynamically" for other modules.
$modules = array('features', 'block', 'context', 'field', 'filter', 'image', 'locale', 'menu', 'node', 'taxonomy', 'user', 'views', 'ctools');
$modules = array('features', 'block', 'contact', 'context', 'field', 'filter', 'image', 'locale', 'menu', 'node', 'taxonomy', 'user', 'views', 'ctools');
foreach (array_filter($modules, 'module_exists') as $module) {
module_load_include('inc', 'features', "includes/features.$module");
@@ -535,13 +547,13 @@ function features_get_components($component = NULL, $key = NULL, $reset = FALSE)
if ($reset || !isset($components) || !isset($component_by_key)) {
$components = $component_by_key = array();
if (!$reset && ($cache = cache_get('features_api'))) {
if (!$reset && ($cache = cache_get('features_api', 'cache_features'))) {
$components = $cache->data;
}
else {
$components = module_invoke_all('features_api');
drupal_alter('features_api', $components);
cache_set('features_api', $components);
cache_set('features_api', $components, 'cache_features');
}
foreach ($components as $component_type => $component_information) {
@@ -607,6 +619,8 @@ function features_hook($component, $hook, $reset = FALSE) {
* Clear the module info cache.
*/
function features_install_modules($modules) {
variable_set('features_modules_changed', TRUE);
module_load_include('inc', 'features', 'features.export');
$files = system_rebuild_module_data();
@@ -650,7 +664,7 @@ function features_get_features($name = NULL, $reset = FALSE) {
function features_get_info($type = 'module', $name = NULL, $reset = FALSE) {
static $cache;
if (!isset($cache)) {
$cache = cache_get('features_module_info');
$cache = cache_get('features_module_info', 'cache_features');
}
if (empty($cache) || $reset) {
$data = array(
@@ -738,7 +752,7 @@ function features_get_info($type = 'module', $name = NULL, $reset = FALSE) {
$data['feature'] = $sorted;
variable_set('features_ignored_orphans', $ignored);
cache_set("features_module_info", $data);
cache_set('features_module_info', $data, 'cache_features');
$cache = new stdClass();
$cache->data = $data;
}
@@ -1067,6 +1081,7 @@ function features_hook_info() {
'features_api',
'features_pipe_alter',
'features_export_alter',
'features_export_options_alter',
);
return array_fill_keys($hooks, array('group' => 'features'));
}
@@ -1189,7 +1204,6 @@ function features_feature_lock($feature, $component = NULL) {
variable_set('features_feature_locked', $locked);
}
/**
* Unlocks a feature or it's component.
*/
@@ -1203,3 +1217,115 @@ function features_feature_unlock($feature, $component = NULL) {
}
variable_set('features_feature_locked', $locked);
}
/**
* Sets the current language to english to ensure a proper export.
*/
function _features_set_export_language() {
// Ensure this is only done if the language isn't already en.
// This can be called multiple times - ensure the handling is done just once.
if ($GLOBALS['language']->language != 'en' && !drupal_static(__FUNCTION__)) {
// Create the language object as language_default() does.
$GLOBALS['language'] = (object) array(
'language' => 'en',
'name' => 'English',
'native' => 'English',
'direction' => 0,
'enabled' => 1,
'plurals' => 0,
'formula' => '',
'domain' => '',
'prefix' => '',
'weight' => 0,
'javascript' => '',
);
// Ensure that static caches are cleared, as they might contain language
// specific information. But keep some important ones. The call below
// accesses a non existing key and requests to reset it. In such cases the
// whole caching data array is returned.
$static = drupal_static(uniqid('', TRUE), NULL, TRUE);
drupal_static_reset();
// Restore some of the language independent, runtime state information to
// keep everything working and avoid unnecessary double processing.
$static_caches_to_keep = array(
'conf_path',
'system_list',
'ip_address',
'drupal_page_is_cacheable',
'list_themes',
'drupal_page_header',
'drupal_send_headers',
'drupal_http_headers',
'language_list',
'module_implements',
'drupal_alter',
'path_is_admin',
'path_get_admin_paths',
'drupal_match_path',
'menu_get_custom_theme',
'menu_get_item',
'arg',
'drupal_system_listing',
'drupal_parse_info_file',
'libraries_get_path',
'module_hook_info',
'drupal_add_js',
'drupal_add_js:jquery_added',
'drupal_add_library',
'drupal_get_library',
'drupal_add_css',
'menu_set_active_trail',
'menu_link_get_preferred',
'menu_set_active_menu_names',
'theme_get_registry',
'features_get_components',
'features_get_components_by_key',
);
foreach ($static_caches_to_keep as $cid) {
if (isset($static[$cid])) {
$data = &drupal_static($cid);
$data = $static[$cid];
}
}
$called = &drupal_static(__FUNCTION__);
$called = TRUE;
}
}
/**
* Implements hook_features_ignore().
*/
function features_features_ignore($component) {
// Determine which keys need to be ignored for override diff for various components.
// Value is how many levels deep the key is.
$ignores = array();
switch ($component) {
case 'views_view':
$ignores['current_display'] = 0;
$ignores['display_handler'] = 0;
$ignores['handler'] = 2;
$ignores['query'] = 0;
$ignores['localization_plugin'] = 0;
// Views automatically adds these two on export to set values.
$ignores['api_version'] = 0;
$ignores['disabled'] = 0;
break;
case 'image':
$ignores['module'] = 0;
$ignores['name'] = 0;
$ignores['storage'] = 0;
// Various properties are loaded into the effect in image_styles.
$ignores['summary theme'] = 2;
$ignores['module'] = 2;
$ignores['label'] = 2;
$ignores['help'] = 2;
$ignores['form callback'] = 2;
$ignores['effect callback'] = 2;
$ignores['dimensions callback'] = 2;
break;
case 'field':
$ignores['locked'] = 1;
break;
}
return $ignores;
}
@@ -274,7 +274,8 @@ function field_base_features_rebuild($module) {
// Create or update field.
if (isset($existing_fields[$field['field_name']])) {
$existing_field = $existing_fields[$field['field_name']];
if ($field + $existing_field !== $existing_field) {
$array_diff_result = drupal_array_diff_assoc_recursive($field + $existing_field, $existing_field);
if (!empty($array_diff_result)) {
field_update_field($field);
}
}
@@ -483,7 +484,8 @@ function field_features_rebuild($module) {
$field_config = $field['field_config'];
if (isset($existing_fields[$field_config['field_name']])) {
$existing_field = $existing_fields[$field_config['field_name']];
if ($field_config + $existing_field !== $existing_field) {
$array_diff_result = drupal_array_diff_assoc_recursive($field_config + $existing_field, $existing_field);
if (!empty($array_diff_result)) {
try {
field_update_field($field_config);
}
@@ -253,11 +253,11 @@ function menu_links_features_export_render($module, $data, $export = NULL) {
$translatables[] = $link['link_title'];
}
}
$code[] = '';
if (!empty($translatables)) {
$code[] = features_translatables_export($translatables, ' ');
}
$code[] = '';
$code[] = ' return $menu_links;';
$code = implode("\n", $code);
return array('menu_default_menu_links' => $code);
@@ -287,3 +287,43 @@ class FeaturesCtoolsIntegrationTest extends DrupalWebTestCase {
}
}
}
/**
* Test detecting modules as features.
*/
class FeaturesDetectionTestCase extends DrupalWebTestCase {
protected $profile = 'testing';
/**
* Test info.
*/
public static function getInfo() {
return array(
'name' => t('Feature Detection tests'),
'description' => t('Run tests for detecting items as features.') ,
'group' => t('Features'),
);
}
/**
* Set up test.
*/
public function setUp() {
parent::setUp(array(
'features',
));
}
/**
* Run test.
*/
public function test() {
module_load_include('inc', 'features', 'features.export');
// First test that features_populate inserts the features api key.
$export = features_populate(array(), array(), 'features_test_empty_fake');
$this->assertTrue(!empty($export['features']['features_api']) && key($export['features']['features_api']) == 'api:' . FEATURES_API, 'Features API key added to new export.');
$this->assertTrue((bool)features_get_features('features_test'), 'Features test recognized as a feature.');
$this->assertFalse((bool)features_get_features('features'), 'Features module not recognized as a feature.');
}
}
@@ -21,9 +21,9 @@ features[user_permission][] = create features_test content
features[views_view][] = features_test
hidden = 1
; Information added by Drupal.org packaging script on 2015-04-13
version = "7.x-2.5"
; Information added by Drupal.org packaging script on 2015-06-24
version = "7.x-2.6"
core = "7.x"
project = "features"
datestamp = "1428944073"
datestamp = "1435165997"
@@ -0,0 +1,13 @@
Index: node_export.module
===================================================================
--- node_export.module (revision 172)
+++ node_export.module (working copy)
@@ -1146,7 +1146,7 @@
if (!empty($query)) {
watchdog('node_export', 'kept existing managed file at uri "%uri"', array('%uri' => $file->uri), WATCHDOG_NOTICE);
- $file = file_load(array_shift($query));
+ $file = (object) array_merge((array) $file, (array) file_load(array_shift($query)));
}
$file = file_save($file);
@@ -38,7 +38,7 @@ function node_export_menu() {
'description' => 'Configure the settings for Node export.',
'file' => 'node_export.pages.inc',
);
$selected_formats = variable_get('node_export_format', array('drupal'));
$selected_formats = variable_get('node_export_format', array('drupal' => 'drupal'));
if (count(array_filter($selected_formats)) > 1) {
$format_handlers = node_export_format_handlers();
foreach ($format_handlers as $format_handler => $format) {
@@ -218,7 +218,7 @@ function node_export_node_operations() {
$operations = array();
if (user_access('export nodes')) {
$selected_formats = variable_get('node_export_format', array('drupal'));
$selected_formats = variable_get('node_export_format', array('drupal' => 'drupal'));
if (count(array_filter($selected_formats)) > 1) {
$format_handlers = node_export_format_handlers();
foreach ($format_handlers as $format_handler => $format) {
@@ -258,7 +258,7 @@ function node_export_bulk_operation($nodes = NULL, $format = NULL, $delivery = N
function node_export_action_info() {
$actions = array();
if (user_access('export nodes')) {
$selected_formats = variable_get('node_export_format', array('drupal'));
$selected_formats = variable_get('node_export_format', array('drupal' => 'drupal'));
$format_handlers = node_export_format_handlers();
foreach ($format_handlers as $format_handler => $format) {
if (!empty($selected_formats[$format_handler])) {
@@ -296,10 +296,13 @@ function node_export_action_info() {
function node_export_action_form($context, &$form_state, $format = NULL) {
// Get the name of the vbo views field
$vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
// Adjust the selection in case the user chose 'select all'
_views_bulk_operations_adjust_selection($form_state['selection'], $form_state['select_all_pages'], $vbo);
if (!empty($form_state['select_all_pages'])) {
views_bulk_operations_direct_adjust($form_state['selection'], $vbo);
}
$nodes = array_combine($form_state['selection'], $form_state['selection']);
return node_export_bulk_operation($nodes);
return node_export_bulk_operation($nodes, $format);
}
/**
@@ -347,7 +350,7 @@ function node_export($nids, $format = NULL, $msg_t = 't') {
// Get the node code from the format handler
$format_handlers = node_export_format_handlers();
$node_export_format = variable_get('node_export_format', array('drupal'));
$node_export_format = variable_get('node_export_format', array('drupal' => 'drupal'));
$format_handler = $format ? $format : reset($node_export_format);
if (!isset($format_handlers[$format_handler])) {
$format_handler = 'drupal';
@@ -1146,7 +1149,7 @@ function _node_export_file_field_import_file(&$file) {
if (!empty($query)) {
watchdog('node_export', 'kept existing managed file at uri "%uri"', array('%uri' => $file->uri), WATCHDOG_NOTICE);
$file = file_load(array_shift($query));
$file = (object) array_merge((array) $file, (array) file_load(array_shift($query)));
}
$file = file_save($file);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,56 @@
diff --git a/node_export.module b/node_export.module
index 8bdadb9..052fa6c 100755
--- a/node_export.module
+++ b/node_export.module
@@ -38,7 +38,7 @@ function node_export_menu() {
'description' => 'Configure the settings for Node export.',
'file' => 'node_export.pages.inc',
);
- $selected_formats = variable_get('node_export_format', array('drupal'));
+ $selected_formats = variable_get('node_export_format', array('drupal' => 'drupal'));
if (count(array_filter($selected_formats)) > 1) {
$format_handlers = node_export_format_handlers();
foreach ($format_handlers as $format_handler => $format) {
@@ -218,7 +218,7 @@ function node_export_node_operations() {
$operations = array();
if (user_access('export nodes')) {
- $selected_formats = variable_get('node_export_format', array('drupal'));
+ $selected_formats = variable_get('node_export_format', array('drupal' => 'drupal'));
if (count(array_filter($selected_formats)) > 1) {
$format_handlers = node_export_format_handlers();
foreach ($format_handlers as $format_handler => $format) {
@@ -258,7 +258,7 @@ function node_export_bulk_operation($nodes = NULL, $format = NULL, $delivery = N
function node_export_action_info() {
$actions = array();
if (user_access('export nodes')) {
- $selected_formats = variable_get('node_export_format', array('drupal'));
+ $selected_formats = variable_get('node_export_format', array('drupal' => 'drupal'));
$format_handlers = node_export_format_handlers();
foreach ($format_handlers as $format_handler => $format) {
if (!empty($selected_formats[$format_handler])) {
@@ -296,10 +296,13 @@ function node_export_action_info() {
function node_export_action_form($context, &$form_state, $format = NULL) {
// Get the name of the vbo views field
$vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
+
// Adjust the selection in case the user chose 'select all'
- _views_bulk_operations_adjust_selection($form_state['selection'], $form_state['select_all_pages'], $vbo);
+ if (!empty($form_state['select_all_pages'])) {
+ views_bulk_operations_direct_adjust($form_state['selection'], $vbo);
+ }
$nodes = array_combine($form_state['selection'], $form_state['selection']);
- return node_export_bulk_operation($nodes);
+ return node_export_bulk_operation($nodes, $format);
}
/**
@@ -347,7 +350,7 @@ function node_export($nids, $format = NULL, $msg_t = 't') {
// Get the node code from the format handler
$format_handlers = node_export_format_handlers();
- $node_export_format = variable_get('node_export_format', array('drupal'));
+ $node_export_format = variable_get('node_export_format', array('drupal' => 'drupal'));
$format_handler = $format ? $format : reset($node_export_format);
if (!isset($format_handlers[$format_handler])) {
$format_handler = 'drupal';
@@ -1,149 +0,0 @@
This document explains how to provide "Pathauto integration" in a
module. You need this if you would like to provide additional tokens
or if your module has paths and you wish to have them automatically
aliased. The simplest integration is just to provide tokens so we
cover that first. More advanced integration requires an
implementation of hook_pathauto to provide a settings form.
It may be helpful to review some examples of integration from the
pathauto_node.inc, pathauto_taxonomy.inc, and pathauto_user.inc files.
==================
1 - Providing additional tokens
==================
If all you want is to enable tokens for your module you will simply
need to implement two functions:
hook_token_values
hook_token_list
See the token.module and it's API.txt for more information about this
process.
If the token is intended to generate a path expected to contain slashes,
the token name must end in 'path', 'path-raw' or 'alias'. This indicates to
Pathauto that the slashes should not be removed from the replacement value.
When an object is created (whether it is a node or a user or a
taxonomy term) the data that Pathauto hands to the token_values in the
$object is in a specific format. This is the format that most people
write code to handle. However, during edits and bulk updates the data
may be in a totally different format. So, if you are writing a
hook_token_values implementation to add special tokens, be sure to
test creation, edit, and bulk update cases to make sure your code will
handle it.
==================
2 - Settings hook - To create aliases for your module
==================
You must implement hook_pathauto($op), where $op is always (at this
time) 'settings'. Return an object (NOT an array) containing the
following members, which will be used by pathauto to build a group
of settings for your module and define the variables for saving your
settings:
module - The name of your module (e.g., 'node')
groupheader - The translated label for the settings group (e.g.,
t('Content path settings')
patterndescr - The translated label for the default pattern (e.g.,
t('Default path pattern (applies to all content types with blank patterns below)')
patterndefault - A translated default pattern (e.g., t('[cat]/[title].html'))
token_type - The token type (e.g. 'node', 'user') that can be used.
patternitems - For modules which need to express multiple patterns
(for example, the node module supports a separate pattern for each
content type), an array whose keys consist of identifiers for each
pattern (e.g., the content type name) and values consist of the
translated label for the pattern
bulkname - For modules which support a bulk update operation, the
translated label for the action (e.g., t('Bulk update content paths'))
bulkdescr - For modules which support a bulk update operation, a
translated, more thorough description of what the operation will do
(e.g., t('Generate aliases for all existing content items which do not already have aliases.'))
==================
2 - $alias = pathauto_create_alias($module, $op, $placeholders, $src, $type=NULL)
==================
At the appropriate time (usually when a new item is being created for
which a generated alias is desired), call pathauto_create_alias() to
generate and create the alias. See the user, taxonomy, and nodeapi hook
implementations in pathauto.module for examples.
$module - The name of your module (e.g., 'node')
$op - Operation being performed on the item ('insert', 'update', or
'bulkupdate')
$placeholders - An array whose keys consist of the translated placeholders
which appear in patterns and values are the "clean" values to be
substituted into the pattern. Call pathauto_cleanstring() on any
values which you do not know to be purely alphanumeric, to substitute
any non-alphanumerics with the user's designated separator. Note that
if the pattern has multiple slash-separated components (e.g., [term:path]),
pathauto_cleanstring() should be called for each component, not the
complete string.
Example: $placeholders[t('[title]')] = pathauto_cleanstring($node->title);
$src - The "real" URI of the content to be aliased (e.g., "node/$node->nid")
$type - For modules which provided patternitems in hook_autopath(),
the relevant identifier for the specific item to be aliased (e.g.,
$node->type)
pathauto_create_alias() returns the alias that was created.
==================
3 - Bulk update function
==================
If a module supports bulk updating of aliases, it must provide a
function of this form, to be called by pathauto when the corresponding
checkbox is selected and the settings page submitted:
function <module>_pathauto_bulkupdate()
The function should iterate over the content items controlled by the
module, calling pathauto_create_alias() for each one. It is
recommended that the function report on its success (e.g., with a
count of created aliases) via drupal_set_message().
==================
4 - Bulk delete hook_path_alias_types()
==================
For modules that create new types of pages that can be aliased with pathauto, a
hook implementation is needed to allow the user to delete them all at once.
function hook_path_alias_types()
This hook returns an array whose keys match the beginning of the source paths
(e.g.: "node/", "user/", etc.) and whose values describe the type of page (e.g.:
"content", "users"). Like all displayed strings, these descriptionsshould be
localized with t(). Use % to match interior pieces of a path; "user/%/track". This
is a database wildcard, so be careful.
==================
Modules that extend node and/or taxonomy
==================
NOTE: this is basically not true any more. If you feel you need this file an issue.
Many contributed Drupal modules extend the core node and taxonomy
modules. To extend pathauto patterns to support their extensions, they
may implement the pathauto_node and pathauto_taxonomy hooks.
To do so, implement the function <modulename>_pathauto_node (or _taxonomy),
accepting the arguments $op and $node (or $term). Two operations are
supported:
$op = 'placeholders' - return an array keyed on placeholder strings
(e.g., t('[eventyyyy]')) valued with descriptions (e.g. t('The year the
event starts.')).
$op = 'values' - return an array keyed on placeholder strings, valued
with the "clean" actual value for the passed node or category (e.g.,
pathauto_cleanstring(date('M', $eventstart)));
See contrib/pathauto_node_event.inc for an example of extending node
patterns.
@@ -1,48 +1,49 @@
Please read this file and also the INSTALL.txt.
Please read this file and also the INSTALL.txt.
They contain answers to many common questions.
If you are developing for this module, the API.txt may be interesting.
If you are upgrading, check the CHANGELOG.txt for major changes.
**Description:
The Pathauto module provides support functions for other modules to
automatically generate aliases based on appropriate criteria, with a
** Description:
The Pathauto module provides support functions for other modules to
automatically generate aliases based on appropriate criteria, with a
central settings path for site administrators.
Implementations are provided for core entity types: content, taxonomy terms,
and users (including blogs and tracker pages).
and users (including blogs and forum pages).
Pathauto also provides a way to delete large numbers of aliases. This feature
is available at Administer > Site building > URL aliases > Delete aliases
Pathauto also provides a way to delete large numbers of aliases. This feature
is available at Administer > Configuration > Search and metadata > URL aliases
> Delete aliases.
**Benefits:
** Benefits:
Besides making the page address more reflective of its content than
"node/138", it's important to know that modern search engines give
heavy weight to search terms which appear in a page's URL. By
automatically using keywords based directly on the page content in the URL,
"node/138", it's important to know that modern search engines give
heavy weight to search terms which appear in a page's URL. By
automatically using keywords based directly on the page content in the URL,
relevant search engine hits for your page can be significantly
enhanced.
**Installation AND Upgrades:
** Installation AND Upgrades:
See the INSTALL.txt file.
**Notices:
** Notices:
Pathauto just adds URL aliases to content, users, and taxonomy terms.
Because it's an alias, the standard Drupal URL (for example node/123 or
taxonomy/term/1) will still function as normal. If you have external links
to your site pointing to standard Drupal URLs, or hardcoded links in a module,
Because it's an alias, the standard Drupal URL (for example node/123 or
taxonomy/term/1) will still function as normal. If you have external links
to your site pointing to standard Drupal URLs, or hardcoded links in a module,
template, content or menu which point to standard Drupal URLs it will bypass
the alias set by Pathauto.
There are reasons you might not want two URLs for the same content on your
site. If this applies to you, please note that you will need to update any
hard coded links in your content or blocks.
There are reasons you might not want two URLs for the same content on your
site. If this applies to you, please note that you will need to update any
hard coded links in your content or blocks.
If you use the "system path" (i.e. node/10) for menu items and settings like
that, Drupal will replace it with the url_alias.
For external links, you might want to consider the Path Redirect or
Global Redirect modules, which allow you to set forwarding either per item or
across the site to your aliased URLs.
For external links, you might want to consider the Path Redirect or
Global Redirect modules, which allow you to set forwarding either per item or
across the site to your aliased URLs.
URLs (not) Getting Replaced With Aliases:
Please bear in mind that only URLs passed through Drupal's l() or url()
@@ -54,41 +55,27 @@ Drupal API instead:
* 'href="'. url("node/$node->nid") .'"' or
* l("Your link title", "node/$node->nid")
See http://api.drupal.org/api/HEAD/function/url and
See http://api.drupal.org/api/HEAD/function/url and
http://api.drupal.org/api/HEAD/function/l for more information.
** Disabling Pathauto for a specific content type (or taxonomy)
When the pattern for a content type is left blank, the default pattern will be
used. But if the default pattern is also blank, Pathauto will be disabled
When the pattern for a content type is left blank, the default pattern will be
used. But if the default pattern is also blank, Pathauto will be disabled
for that content type.
** Bulk Updates Must be Run Multiple Times:
As of 5.x-2.x Pathauto now performs bulk updates in a manner which is more
likely to succeed on large sites. The drawback is that it needs to be run
multiple times. If you want to reduce the number of times that you need to
run Pathauto you can increase the "Maximum number of objects to alias in a
bulk update:" setting under General Settings.
**WYSIWYG Conflicts - FCKEditor, TinyMCE, etc.
If you use a WYSIWYG editor, please disable it for the Pathauto admin page.
Failure to do so may cause errors about "preg_replace" problems due to the <p>
tag being added to the "strings to replace". See http://drupal.org/node/175772
**Credits:
** Credits:
The original module combined the functionality of Mike Ryan's autopath with
Tommy Sundstrom's path_automatic.
Significant enhancements were contributed by jdmquin @ www.bcdems.net.
Matt England added the tracker support.
Matt England added the tracker support (tracker support has been removed in
recent changes).
Other suggestions and patches contributed by the Drupal community.
Current maintainers:
Greg Knaddison - http://growingventuresolutions.com
Current maintainers:
Dave Reid - http://www.davereid.net
Greg Knaddison - http://www.knaddison.com
Mike Ryan - http://mikeryan.name
Frederik 'Freso' S. Olesen - http://freso.dk
**Changes:
See the CHANGELOG.txt file.
@@ -64,17 +64,11 @@ function pathauto_patterns_form($form, $form_state) {
}
}
// Display the user documentation of placeholders supported by
// this module, as a description on the last pattern
// Show the token help relevant to this pattern type.
$form[$module]['token_help'] = array(
'#title' => t('Replacement patterns'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form[$module]['token_help']['help'] = array(
'#theme' => 'token_tree',
'#token_types' => array($settings->token_type),
'#dialog' => TRUE,
);
}
@@ -144,7 +138,7 @@ function pathauto_settings_form($form) {
$description = t('What should Pathauto do when updating an existing content item which already has an alias?');
if (module_exists('redirect')) {
$description .= ' ' . t('The <a href="!url">Redirect module settings</a> affect whether a redirect is created when an alias is deleted.', array('!url' => url('admin/config/search/redirect')));
$description .= ' ' . t('The <a href="!url">Redirect module settings</a> affect whether a redirect is created when an alias is deleted.', array('!url' => url('admin/config/search/redirect/settings')));
}
else {
$description .= ' ' . t('Considering installing the <a href="!url">Redirect module</a> to get redirects when your aliases change.', array('!url' => 'http://drupal.org/project/redirect'));
@@ -165,7 +159,7 @@ function pathauto_settings_form($form) {
'#type' => 'checkbox',
'#title' => t('Transliterate prior to creating alias'),
'#default_value' => variable_get('pathauto_transliterate', FALSE) && module_exists('transliteration'),
'#description' => t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the ASCII-96 alphabet? Transliteration is handled by the Transliteration module.'),
'#description' => t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the US-ASCII alphabet? Transliteration is handled by the Transliteration module.'),
'#access' => module_exists('transliteration'),
);
@@ -1,17 +1,171 @@
<?php
/**
* @file
* Documentation for pathauto API.
*
* @see hook_token_info
* @see hook_tokens
* It may be helpful to review some examples of integration from
* pathauto.pathauto.inc.
*
* Pathauto works by using tokens in path patterns. Thus the simplest
* integration is just to provide tokens. Token support is provided by Drupal
* core. To provide additional token from your module, implement the following
* hooks:
*
* hook_tokens() - http://api.drupal.org/api/function/hook_tokens
* hook_token_info() - http://api.drupal.org/api/function/hook_token_info
*
* If you wish to provide pathauto integration for custom paths provided by your
* module, there are a few steps involved.
*
* 1. hook_pathauto()
* Provide information required by pathauto for the settings form as well as
* bulk generation. See the documentation for hook_pathauto() for more
* details.
*
* 2. pathauto_create_alias()
* At the appropriate time (usually when a new item is being created for
* which a generated alias is desired), call pathauto_create_alias() with the
* appropriate parameters to generate and create the alias. See the user,
* taxonomy, and node hook implementations in pathauto.module for examples.
* Also see the documentation for pathauto_create_alias().
*
* 3. pathauto_path_delete_all()
* At the appropriate time (usually when an item is being deleted), call
* pathauto_path_delete_all() to remove any aliases that were created for the
* content being removed. See the documentation for
* pathauto_path_delete_all() for more details.
*
* 4. hook_path_alias_types()
* For modules that create new types of content that can be aliased with
* pathauto, a hook implementation is needed to allow the user to delete them
* all at once. See the documentation for hook_path_alias_types() below for
* more information.
*
* There are other integration points with pathauto, namely alter hooks that
* allow you to change the data used by pathauto at various points in the
* process. See the below hook documentation for details.
*/
/**
* Used primarily by the bulk delete form. This hooks provides pathauto the
* information needed to bulk delete aliases created by your module. The keys
* of the return array are used by pathauto as the system path prefix to delete
* from the url_aliases table. The corresponding value is simply used as the
* label for each type of path on the bulk delete form.
*
* @return
* An array whose keys match the beginning of the source paths
* (e.g.: "node/", "user/", etc.) and whose values describe the type of page
* (e.g.: "Content", "Users"). Like all displayed strings, these descriptions
* should be localized with t(). Use % to match interior pieces of a path,
* like "user/%/track". This is a database wildcard (meaning "user/%/track"
* matches "user/1/track" as well as "user/1/view/track").
*/
function hook_path_alias_types() {
$objects['user/'] = t('Users');
$objects['node/'] = t('Content');
return $objects;
}
/**
* Provide information about the way your module's aliases will be built.
*
* The information you provide here is used to build the form
* on search/path/patterns. File pathauto.pathauto.inc provides example
* implementations for system modules.
*
* @see node_pathauto
*
* @param $op
* At the moment this will always be 'settings'.
*
* @return object|null
* An object, or array of objects (if providing multiple groups of path
* patterns). Each object should have the following members:
* - 'module': The module or entity type.
* - 'token_type': Which token type should be allowed in the patterns form.
* - 'groupheader': Translated label for the settings group
* - 'patterndescr': The translated label for the default pattern (e.g.,
* t('Default path pattern (applies to all content types with blank
* patterns below)')
* - 'patterndefault': Default pattern (e.g. 'content/[node:title]'
* - 'batch_update_callback': The name of function that should be ran for
* bulk update. @see node_pathauto_bulk_update_batch_process for example
* - 'batch_file': The name of the file with the bulk update function.
* - 'patternitems': Optional. An array of descritpions keyed by bundles.
*/
function hook_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'file';
$settings['token_type'] = 'file';
$settings['groupheader'] = t('File paths');
$settings['patterndescr'] = t('Default path pattern (applies to all file types with blank patterns below)');
$settings['patterndefault'] = 'files/[file:name]';
$settings['batch_update_callback'] = 'file_entity_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'file_entity') . '/file_entity.pathauto.inc';
foreach (file_type_get_enabled_types() as $file_type => $type) {
$settings['patternitems'][$file_type] = t('Pattern for all @file_type paths.', array('@file_type' => $type->label));
}
return (object) $settings;
default:
break;
}
}
/**
* Determine if a possible URL alias would conflict with any existing paths.
*
* Returning TRUE from this function will trigger pathauto_alias_uniquify() to
* generate a similar URL alias with a suffix to avoid conflicts.
*
* @param string $alias
* The potential URL alias.
* @param string $source
* The source path for the alias (e.g. 'node/1').
* @param string $langcode
* The language code for the alias (e.g. 'en').
*
* @return bool
* TRUE if $alias conflicts with an existing, reserved path, or FALSE/NULL if
* it does not match any reserved paths.
*
* @see pathauto_alias_uniquify()
*/
function hook_pathauto_is_alias_reserved($alias, $source, $langcode) {
// Check our module's list of paths and return TRUE if $alias matches any of
// them.
return (bool) db_query("SELECT 1 FROM {mytable} WHERE path = :path", array(':path' => $alias))->fetchField();
}
/**
* Alter the pattern to be used before an alias is generated by Pathauto.
*
* This hook will only be called if a default pattern is configured (on
* admin/config/search/path/patterns).
*
* @param string $pattern
* The alias pattern for Pathauto to pass to token_replace() to generate the
* URL alias.
* @param array $context
* An associative array of additional options, with the following elements:
* - 'module': The module or entity type being aliased.
* - 'op': A string with the operation being performed on the object being
* aliased. Can be either 'insert', 'update', 'return', or 'bulkupdate'.
* - 'source': A string of the source path for the alias (e.g. 'node/1').
* - 'data': An array of keyed objects to pass to token_replace().
* - 'type': The sub-type or bundle of the object being aliased.
* - 'language': A string of the language code for the alias (e.g. 'en').
* This can be altered by reference.
*/
function hook_pathauto_pattern_alter(&$pattern, array $context) {
// Switch out any [node:created:*] tokens with [node:updated:*] on update.
if ($context['module'] == 'node' && ($context['op'] == 'update')) {
$pattern = preg_replace('/\[node:created(\:[^]]*)?\]/', '[node:updated$1]', $pattern);
}
}
/**
@@ -59,30 +59,27 @@ define('PATHAUTO_PUNCTUATION_DO_NOTHING', 2);
* A string alias.
* @param $source
* A string that is the internal path.
* @param $language
* @param $langcode
* A string indicating the path's language.
* @return
*
* @return bool
* TRUE if an alias exists, FALSE if not.
*
* @deprecated Use path_pathauto_is_alias_reserved() instead.
*/
function _pathauto_alias_exists($alias, $source, $language = LANGUAGE_NONE) {
$pid = db_query_range("SELECT pid FROM {url_alias} WHERE source <> :source AND alias = :alias AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", 0, 1, array(
':source' => $source,
':alias' => $alias,
':language' => $language,
':language_none' => LANGUAGE_NONE,
))->fetchField();
return !empty($pid);
function _pathauto_alias_exists($alias, $source, $langcode = LANGUAGE_NONE) {
return path_pathauto_is_alias_reserved($alias, $source, $langcode);
}
/**
* Fetches an existing URL alias given a path and optional language.
*
* @param $source
* @param string $source
* An internal Drupal path.
* @param $language
* @param string $language
* An optional language code to look up the path in.
* @return
*
* @return bool|array
* FALSE if no alias was found or an associative array containing the
* following keys:
* - pid: Unique path alias identifier.
@@ -111,12 +108,17 @@ function _pathauto_existing_alias_data($source, $language = LANGUAGE_NONE) {
* This function should *not* be called on URL alias or path strings because it
* is assumed that they are already clean.
*
* @param $string
* @param string $string
* A string to clean.
* @return
* @param array $options
* (optional) A keyed array of settings and flags to control the Pathauto
* clean string replacement process. Supported options are:
* - langcode: A language code to be used when translating strings.
*
* @return string
* The cleaned string.
*/
function pathauto_cleanstring($string) {
function pathauto_cleanstring($string, array $options = array()) {
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
@@ -161,6 +163,7 @@ function pathauto_cleanstring($string) {
if ($ignore_words_regex) {
$cache['ignore_words_regex'] = '\b' . $ignore_words_regex . '\b';
if (function_exists('mb_eregi_replace')) {
mb_regex_encoding('UTF-8');
$cache['ignore_words_callback'] = 'mb_eregi_replace';
}
else {
@@ -170,15 +173,23 @@ function pathauto_cleanstring($string) {
}
}
// Empty strings do not need any proccessing.
// Empty strings do not need any processing.
if ($string === '' || $string === NULL) {
return '';
}
$langcode = NULL;
if (!empty($options['language']->language)) {
$langcode = $options['language']->language;
}
elseif (!empty($options['langcode'])) {
$langcode = $options['langcode'];
}
// Check if the string has already been processed, and if so return the
// cached result.
if (isset($cache['strings'][$string])) {
return $cache['strings'][$string];
if (isset($cache['strings'][$langcode][$string])) {
return $cache['strings'][$langcode][$string];
}
// Remove all HTML tags from the string.
@@ -186,7 +197,10 @@ function pathauto_cleanstring($string) {
// Optionally transliterate (by running through the Transliteration module)
if ($cache['transliterate']) {
$output = transliteration_get($output);
// If the reduce strings to letters and numbers is enabled, don't bother
// replacing unknown characters with a question mark. Use an empty string
// instead.
$output = transliteration_get($output, $cache['reduce_ascii'] ? '' : '?', $langcode);
}
// Replace or drop punctuation based on user settings
@@ -220,7 +234,7 @@ function pathauto_cleanstring($string) {
$output = truncate_utf8($output, $cache['maxlength'], TRUE);
// Cache this result in the static array.
$cache['strings'][$string] = $output;
$cache['strings'][$langcode][$string] = $output;
return $output;
}
@@ -228,11 +242,12 @@ function pathauto_cleanstring($string) {
/**
* Trims duplicate, leading, and trailing separators from a string.
*
* @param $string
* @param string $string
* The string to clean path separators from.
* @param $separator
* @param string $separator
* The path separator to use when cleaning.
* @return
*
* @return string
* The cleaned version of the string.
*
* @see pathauto_cleanstring()
@@ -250,21 +265,20 @@ function _pathauto_clean_separators($string, $separator = NULL) {
$output = $string;
// Clean duplicate or trailing separators.
if (strlen($separator)) {
// Escape the separator.
$seppattern = preg_quote($separator, '/');
// Trim any leading or trailing separators.
$output = preg_replace("/^$seppattern+|$seppattern+$/", '', $output);
$output = trim($output, $separator);
// Replace trailing separators around slashes.
if ($separator !== '/') {
$output = preg_replace("/$seppattern+\/|\/$seppattern+/", "/", $output);
}
// Escape the separator for use in regular expressions.
$seppattern = preg_quote($separator, '/');
// Replace multiple separators with a single one.
$output = preg_replace("/$seppattern+/", $separator, $output);
// Replace trailing separators around slashes.
if ($separator !== '/') {
$output = preg_replace("/\/+$seppattern\/+|$seppattern\/+|\/+$seppattern/", "/", $output);
}
}
return $output;
@@ -278,9 +292,10 @@ function _pathauto_clean_separators($string, $separator = NULL) {
* - Trim duplicate, leading, and trailing separators.
* - Shorten to a desired length and logical position based on word boundaries.
*
* @param $alias
* @param string $alias
* A string with the URL alias to clean up.
* @return
*
* @return string
* The cleaned URL alias.
*/
function pathauto_clean_alias($alias) {
@@ -294,12 +309,15 @@ function pathauto_clean_alias($alias) {
$output = $alias;
// Trim duplicate, leading, and trailing back-slashes.
$output = _pathauto_clean_separators($output, '/');
// Trim duplicate, leading, and trailing separators.
// Trim duplicate, leading, and trailing separators. Do this before cleaning
// backslashes since a pattern like "[token1]/[token2]-[token3]/[token4]"
// could end up like "value1/-/value2" and if backslashes were cleaned first
// this would result in a duplicate blackslash.
$output = _pathauto_clean_separators($output);
// Trim duplicate, leading, and trailing backslashes.
$output = _pathauto_clean_separators($output, '/');
// Shorten to a logical place based on word boundaries.
$output = truncate_utf8($output, $cache['maxlength'], TRUE);
@@ -328,8 +346,10 @@ function pathauto_clean_alias($alias) {
* (e.g., $node->type).
* @param $language
* A string specify the path's language.
* @return
* The alias that was created.
*
* @return array|null|false
* The alias array that was created, NULL if an empty alias was generated, or
* FALSE if the alias generation was not possible.
*
* @see _pathauto_set_alias()
* @see token_replace()
@@ -337,20 +357,32 @@ function pathauto_clean_alias($alias) {
function pathauto_create_alias($module, $op, $source, $data, $type = NULL, $language = LANGUAGE_NONE) {
// Retrieve and apply the pattern for this content type.
$pattern = pathauto_pattern_load_by_entity($module, $type, $language);
// Allow other modules to alter the pattern.
$context = array(
'module' => $module,
'op' => $op,
'source' => $source,
'data' => $data,
'type' => $type,
'language' => &$language,
);
drupal_alter('pathauto_pattern', $pattern, $context);
if (empty($pattern)) {
// No pattern? Do nothing (otherwise we may blow away existing aliases...)
return '';
return FALSE;
}
// Special handling when updating an item which is already aliased.
$existing_alias = NULL;
if ($op == 'update' || $op == 'bulkupdate') {
if ($op != 'insert') {
if ($existing_alias = _pathauto_existing_alias_data($source, $language)) {
switch (variable_get('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE)) {
case PATHAUTO_UPDATE_ACTION_NO_NEW:
// If an alias already exists, and the update action is set to do nothing,
// then gosh-darn it, do nothing.
return '';
return FALSE;
}
}
}
@@ -369,26 +401,19 @@ function pathauto_create_alias($module, $op, $source, $data, $type = NULL, $lang
// @see token_scan()
$pattern_tokens_removed = preg_replace('/\[[^\s\]:]*:[^\s\]]*\]/', '', $pattern);
if ($alias === $pattern_tokens_removed) {
return '';
return;
}
$alias = pathauto_clean_alias($alias);
// Allow other modules to alter the alias.
$context = array(
'module' => $module,
'op' => $op,
'source' => &$source,
'data' => $data,
'type' => $type,
'language' => &$language,
'pattern' => $pattern,
);
$context['source'] = &$source;
$context['pattern'] = $pattern;
drupal_alter('pathauto_alias', $alias, $context);
// If we have arrived at an empty string, discontinue.
if (!drupal_strlen($alias)) {
return '';
return;
}
// If the alias already exists, generate a new, hopefully unique, variant.
@@ -432,7 +457,7 @@ function pathauto_create_alias($module, $op, $source, $data, $type = NULL, $lang
* A string with a language code.
*/
function pathauto_alias_uniquify(&$alias, $source, $langcode) {
if (!_pathauto_alias_exists($alias, $source, $langcode)) {
if (!pathauto_is_alias_reserved($alias, $source, $langcode)) {
return;
}
@@ -445,9 +470,9 @@ function pathauto_alias_uniquify(&$alias, $source, $langcode) {
do {
// Append an incrementing numeric suffix until we find a unique alias.
$unique_suffix = $separator . $i;
$alias = truncate_utf8($original_alias, $maxlength - drupal_strlen($unique_suffix, TRUE)) . $unique_suffix;
$alias = truncate_utf8($original_alias, $maxlength - drupal_strlen($unique_suffix), TRUE) . $unique_suffix;
$i++;
} while (_pathauto_alias_exists($alias, $source, $langcode));
} while (pathauto_is_alias_reserved($alias, $source, $langcode));
}
/**
@@ -463,7 +488,7 @@ function pathauto_alias_uniquify(&$alias, $source, $langcode) {
function _pathauto_path_is_callback($path) {
// We need to use a try/catch here because of a core bug which will throw an
// exception if $path is something like 'node/foo/bar'.
// @todo Remove when http://drupal.org/node/1302158 is fixed in core.
// @todo Remove when http://drupal.org/node/1003788 is fixed in core.
try {
$menu = menu_get_item($path);
}
@@ -498,26 +523,19 @@ function _pathauto_path_is_callback($path) {
* An optional string with the operation being performed.
*
* @return
* The saved path from path_save() or NULL if the path was not saved.
* The saved path from path_save() or FALSE if the path was not saved.
*
* @see path_save()
*/
function _pathauto_set_alias(array $path, $existing_alias = NULL, $op = NULL) {
$verbose = _pathauto_verbose(NULL, $op);
// Alert users that an existing callback cannot be overridden automatically
if (_pathauto_path_is_callback($path['alias'])) {
if ($verbose) {
_pathauto_verbose(t('Ignoring alias %alias due to existing path conflict.', array('%alias' => $path['alias'])));
}
return;
}
// Alert users if they are trying to create an alias that is the same as the internal path
if ($path['source'] == $path['alias']) {
if ($verbose) {
_pathauto_verbose(t('Ignoring alias %alias because it is the same as the internal path.', array('%alias' => $path['alias'])));
}
return;
return FALSE;
}
// Skip replacing the current alias with an identical alias
@@ -529,7 +547,7 @@ function _pathauto_set_alias(array $path, $existing_alias = NULL, $op = NULL) {
switch (variable_get('pathauto_update_action', PATHAUTO_UPDATE_ACTION_DELETE)) {
case PATHAUTO_UPDATE_ACTION_NO_NEW:
// Do not create the alias.
return;
return FALSE;
case PATHAUTO_UPDATE_ACTION_LEAVE:
// Create a new alias instead of overwriting the existing by leaving
// $path['pid'] empty.
@@ -605,7 +623,7 @@ function pathauto_clean_token_values(&$replacements, $data = array(), $options =
foreach ($replacements as $token => $value) {
// Only clean non-path tokens.
if (!preg_match('/(path|alias|url|url-brief)\]$/', $token)) {
$replacements[$token] = pathauto_cleanstring($value);
$replacements[$token] = pathauto_cleanstring($value, $options);
}
}
}
@@ -3,13 +3,14 @@ description = Provides a mechanism for modules to automatically generate aliases
dependencies[] = path
dependencies[] = token
core = 7.x
files[] = pathauto.migrate.inc
files[] = pathauto.test
configure = admin/config/search/path/patterns
recommends[] = redirect
; Information added by drupal.org packaging script on 2012-08-09
version = "7.x-1.2"
; Information added by Drupal.org packaging script on 2015-10-07
version = "7.x-1.3"
core = "7.x"
project = "pathauto"
datestamp = "1344525185"
datestamp = "1444232655"
@@ -7,19 +7,59 @@
* @ingroup pathauto
*/
/**
* Implements hook_schema().
*/
function pathauto_schema() {
$schema['pathauto_state'] = array(
'description' => 'The status of each entity alias (whether it was automatically generated or not).',
'fields' => array(
'entity_type' => array(
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'description' => 'An entity type.',
),
'entity_id' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'An entity ID.',
),
'pathauto' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 0,
'description' => 'The automatic alias status of the entity.',
),
),
'primary key' => array('entity_type', 'entity_id'),
);
return $schema;
}
/**
* Implements hook_install().
*/
function pathauto_install() {
// Set some default variables necessary for the module to perform.
variable_set('pathauto_node_pattern', 'content/[node:title]');
variable_set('pathauto_taxonomy_term_pattern', '[term:vocabulary]/[term:name]');
variable_set('pathauto_forum_pattern', '[term:vocabulary]/[term:name]');
variable_set('pathauto_user_pattern', 'users/[user:name]');
variable_set('pathauto_blog_pattern', 'blogs/[user:name]');
// Set the default separator character to replace instead of remove (default).
variable_set('pathauto_punctuation_hyphen', 1);
$defaults = array(
'pathauto_node_pattern' => 'content/[node:title]',
'pathauto_taxonomy_term_pattern' => '[term:vocabulary]/[term:name]',
'pathauto_forum_pattern' => '[term:vocabulary]/[term:name]',
'pathauto_user_pattern' => 'users/[user:name]',
'pathauto_blog_pattern' => 'blogs/[user:name]',
// Set hyphen character to replace instead of remove.
'pathauto_punctuation_hyphen' => 1,
);
foreach ($defaults as $variable => $default) {
if (variable_get($variable) === NULL) {
variable_set($variable, $default);
}
}
// Set the weight to 1
db_update('system')
@@ -38,6 +78,23 @@ function pathauto_uninstall() {
cache_clear_all('variables', 'cache');
}
/**
* Implements hook_requirements().
*/
function pathauto_requirements($phase) {
$requirements = array();
$t = get_t();
if ($phase == 'runtime' && module_exists('pathauto_persist')) {
$requirements['pathauto'] = array(
'title' => $t('Pathauto Persist'),
'value' => $t('Enabled'),
'description' => $t('Pathauto Persist is installed and enabled. As Pathauto Persist has been merged into Pathauto, the Pathauto Persist module can be safely disabled and removed. All Pathauto Persist settings have been migrated to the Pathauto implementation.'),
'severity' => REQUIREMENT_INFO,
);
}
return $requirements;
}
/**
* Remove the unsupported user/%/contact and user/%/tracker pattern variables.
*/
@@ -168,6 +225,55 @@ function pathauto_update_7005() {
return 'Your Pathauto taxonomy and forum patterns have been corrected. You may wish to regenerate your taxonomy and forum term URL aliases.';
}
/**
* Create pathauto_state table, using data from pathauto_persist if it exists.
*/
function pathauto_update_7006() {
if (!db_table_exists('pathauto_state')) {
$schema['pathauto_state'] = array(
'description' => 'The status of each entity alias (whether it was automatically generated or not).',
'fields' => array(
'entity_type' => array(
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'description' => 'The entity type.',
),
'entity_id' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'The entity ID.',
),
'pathauto' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 0,
'description' => 'The automatic alias status of the entity.',
),
),
'primary key' => array('entity_type', 'entity_id'),
);
if (db_table_exists('pathauto_persist')) {
// Rename pathauto_persist's table, then create a new empty one just so
// that we can cleanly disable that module.
db_rename_table('pathauto_persist', 'pathauto_state');
db_create_table('pathauto_persist', $schema['pathauto_state']);
// Disable the module and inform the user.
if (module_exists('pathauto_persist')) {
module_disable(array('pathauto_persist'));
}
return t('The Pathauto Persist module and all of its data has been merged into Pathauto. The Pathauto Persist module has been disabled and can be safely uninstalled.');
}
else {
db_create_table('pathauto_state', $schema['pathauto_state']);
}
}
}
/**
* Build a list of Drupal 6 tokens and their Drupal 7 token names.
*/
@@ -3,13 +3,13 @@
Drupal.behaviors.pathFieldsetSummaries = {
attach: function (context) {
$('fieldset.path-form', context).drupalSetSummary(function (context) {
var path = $('.form-item-path-alias input').val();
var automatic = $('.form-item-path-pathauto input').attr('checked');
var path = $('.form-item-path-alias input', context).val();
var automatic = $('.form-item-path-pathauto input', context).attr('checked');
if (automatic) {
return Drupal.t('Automatic alias');
}
if (path) {
else if (path) {
return Drupal.t('Alias: @alias', { '@alias': path });
}
else {
@@ -0,0 +1,56 @@
<?php
/**
* @file
* Support for the Pathauto module.
*/
/**
* Field handler.
*/
class PathautoMigrationHandler extends MigrateDestinationHandler {
public function __construct() {
$this->registerTypes(array('entity'));
}
/**
* Make the destination field visible.
*/
public function fields() {
return array(
'pathauto' => t('Pathauto: Perform aliasing (set to 0 to prevent alias generation during migration'),
);
}
public function prepare($entity, stdClass $row) {
if (isset($entity->pathauto)) {
if (!isset($entity->path)) {
$entity->path = array();
}
elseif (is_string($entity->path)) {
// If MigratePathEntityHandler->prepare() hasn't run yet, support
// the alias (set as $entity->path as a string) being formatted properly
// in the path alias array.
$path = $entity->path;
$entity->path = array();
$entity->path['alias'] = $path;
}
$entity->path['pathauto'] = $entity->pathauto;
if (!isset($entity->path['alias'])) {
$entity->path['alias'] = '';
}
unset($entity->pathauto);
}
}
}
/*
* Implementation of hook_migrate_api().
*/
function pathauto_migrate_api() {
$api = array(
'api' => 2,
'destination handlers' => array('PathautoMigrationHandler'),
);
return $api;
}
@@ -26,30 +26,14 @@ define('PATHAUTO_IGNORE_WORDS', 'a, an, as, at, before, but, by, for, from, is,
* Implements hook_hook_info().
*/
function pathauto_hook_info() {
$info['pathauto'] = array('group' => 'pathauto');
$info['path_alias_types'] = array('group' => 'pathauto');
return $info;
}
/**
* Implements hook_module_implements_alter().
*
* Adds pathauto support for core modules.
*/
function pathauto_module_implements_alter(&$implementations, $hook) {
$hooks = pathauto_hook_info();
if (isset($hooks[$hook])) {
$modules = array('node', 'taxonomy', 'user', 'forum', 'blog');
foreach ($modules as $module) {
if (module_exists($module)) {
$implementations[$module] = TRUE;
}
}
// Move pathauto.module to get included first since it is responsible for
// other modules.
unset($implementations['pathauto']);
$implementations = array_merge(array('pathauto' => 'pathauto'), $implementations);
}
$hooks = array(
'pathauto',
'path_alias_types',
'pathauto_pattern_alter',
'pathauto_alias_alter',
'pathauto_is_alias_reserved',
);
return array_fill_keys($hooks, array('group' => 'pathauto'));
}
/**
@@ -67,6 +51,9 @@ function pathauto_help($path, $arg) {
$output .= '<dd>' . t('The <strong>maximum alias length</strong> and <strong>maximum component length</strong> values default to 100 and have a limit of @max from Pathauto. This length is limited by the length of the "alias" column of the url_alias database table. The default database schema for this column is @max. If you set a length that is equal to that of the one set in the "alias" column it will cause problems in situations where the system needs to append additional words to the aliased URL. You should enter a value that is the length of the "alias" column minus the length of any strings that might get added to the end of the URL. The length of strings that might get added to the end of your URLs depends on which modules you have enabled and on your Pathauto settings. The recommended and default value is 100.', array('@max' => _pathauto_get_schema_alias_maxlength())) . '</dd>';
$output .= '</dl>';
return $output;
case 'admin/config/search/path/update_bulk':
$output = '<p>' . t('Bulk generation will only generate URL aliases for items that currently have no aliases. This is typically used when installing Pathauto on a site that has existing un-aliased content that needs to be aliased in bulk.') . '</p>';
return $output;
}
}
@@ -109,7 +96,7 @@ function pathauto_menu() {
'file' => 'pathauto.admin.inc',
);
$items['admin/config/search/path/update_bulk'] = array(
'title' => 'Bulk update',
'title' => 'Bulk generate',
'page callback' => 'drupal_get_form',
'page arguments' => array('pathauto_bulk_update_form'),
'access arguments' => array('administer url aliases'),
@@ -295,9 +282,19 @@ function pathauto_field_attach_form($entity_type, $entity, &$form, &$form_state,
if (!empty($id)) {
module_load_include('inc', 'pathauto');
$uri = entity_uri($entity_type, $entity);
$path = drupal_get_path_alias($uri['path'], $langcode);
$pathauto_alias = pathauto_create_alias($entity_type, 'return', $uri['path'], array($entity_type => $entity), $bundle, $langcode);
$entity->path['pathauto'] = ($path != $uri['path'] && $path == $pathauto_alias);
if ($pathauto_alias === FALSE) {
// If Pathauto is not going to be able to generate an alias, then we
// should not bother to show the checkbox since it wouldn't do anything.
// Note that if a pattern does apply, but all the tokens currently
// evaluate to empty strings, then $pathauto_alias would equal null and
// not false.
return;
}
else {
$path = drupal_get_path_alias($uri['path'], $langcode);
$entity->path['pathauto'] = ($path != $uri['path'] && $path == $pathauto_alias);
}
}
else {
$entity->path['pathauto'] = TRUE;
@@ -341,10 +338,54 @@ function pathauto_field_attach_form($entity_type, $entity, &$form, &$form_state,
}
}
/**
* Implements hook_entity_load().
*/
function pathauto_entity_load($entities, $entity_type) {
// Statically cache which entity types have data in the pathauto_state
// table to avoid unnecessary queries for entities that would not have any
// data anyway.
static $loadable_types;
if (!isset($loadable_types)) {
$loadable_types = &drupal_static(__FUNCTION__);
if (!isset($loadable_types)) {
// Prevent errors if pathauto_update_7006() has not yet been run.
if (!db_table_exists('pathauto_state')) {
$loadable_types = array();
}
else {
$loadable_types = db_query("SELECT DISTINCT entity_type FROM {pathauto_state}")->fetchCol();
}
}
}
// Check if this entity type has loadable records.
if (!in_array($entity_type, $loadable_types)) {
return;
}
$states = pathauto_entity_state_load_multiple($entity_type, array_keys($entities));
foreach ($states as $id => $state) {
if (!isset($entities[$id]->path)) {
$entities[$id]->path = array();
}
if (is_array($entities[$id]->path) && !isset($entities[$id]->path['pathauto'])) {
$entities[$id]->path['pathauto'] = $state;
}
}
}
/**
* Implements hook_entity_presave().
*/
function pathauto_entity_presave($entity, $type) {
function pathauto_entity_presave($entity, $entity_type) {
if (isset($entity->path['pathauto']) && is_array($entity->path)) {
// We must set an empty alias string for the path to prevent saving an
// alias.
$entity->path += array('alias' => '');
}
// About to be saved (before insert/update)
if (!empty($entity->path['pathauto']) && isset($entity->path['old_alias'])
&& $entity->path['alias'] == '' && $entity->path['old_alias'] != '') {
@@ -366,6 +407,109 @@ function pathauto_entity_presave($entity, $type) {
}
}
/**
* Implements hook_entity_insert().
*/
function pathauto_entity_insert($entity, $entity_type) {
if (isset($entity->path['pathauto'])) {
pathauto_entity_state_save($entity_type, $entity, $entity->path['pathauto']);
}
}
/**
* Implements hook_entity_update().
*/
function pathauto_entity_update($entity, $entity_type) {
if (isset($entity->path['pathauto'])) {
pathauto_entity_state_save($entity_type, $entity, $entity->path['pathauto']);
}
}
/**
* Implements hook_entity_delete().
*/
function pathauto_entity_delete($entity, $entity_type) {
if (isset($entity->path['pathauto'])) {
pathauto_entity_state_delete($entity_type, $entity);
}
}
/**
* Load a pathauto state for an entity.
*
* @param string $entity_type
* An entity type.
* @param int $entity_id
* An entity ID.
*
* @return bool
* A value that evaluates to TRUE if Pathauto should control this entity's
* path. A value that evaluates to FALSE if Pathauto should not manage the
* entity's path.
*/
function pathauto_entity_state_load($entity_type, $entity_id) {
$pathauto_state = pathauto_entity_state_load_multiple($entity_type, array($entity_id));
return !empty($pathauto_state) ? reset($pathauto_state) : FALSE;
}
/**
* Load a pathauto state for multiple entities.
*
* @param string $entity_type
* The entity type.
* @param int[] $entity_ids
* The array of entity IDs.
*
* @return bool[]
* An array of Pathauto states keyed by entity ID.
*/
function pathauto_entity_state_load_multiple($entity_type, $entity_ids) {
return db_query("SELECT entity_id, pathauto FROM {pathauto_state} WHERE entity_type = :entity_type AND entity_id IN (:entity_ids)", array(':entity_type' => $entity_type, ':entity_ids' => $entity_ids))->fetchAllKeyed();
}
/**
* Save the pathauto state for an entity.
*
* @param string $entity_type
* The entity type.
* @param object $entity
* The entity object.
* @param bool $pathauto_state
* A value that evaluates to TRUE means that Pathauto should keep controlling
* this entity's path in the future. A value that evaluates to FALSE means
* that Pathauto should not manage the entity's path.
*/
function pathauto_entity_state_save($entity_type, $entity, $pathauto_state) {
list($entity_id) = entity_extract_ids($entity_type, $entity);
db_merge('pathauto_state')
->key(array(
'entity_type' => $entity_type,
'entity_id' => $entity_id,
))
->fields(array(
'pathauto' => $pathauto_state ? 1 : 0,
))
->execute();
drupal_static_reset('pathauto_entity_load');
}
/**
* Delete the pathauto state for an entity.
*
* @param string $entity_type
* The entity type.
* @param object $entity
* The entity object.
*/
function pathauto_entity_state_delete($entity_type, $entity) {
list($entity_id) = entity_extract_ids($entity_type, $entity);
db_delete('pathauto_state')
->condition('entity_type', $entity_type)
->condition('entity_id', $entity_id)
->execute();
drupal_static_reset('pathauto_entity_load');
}
/**
* Implements hook_action_info().
*/
@@ -374,16 +518,19 @@ function pathauto_action_info() {
'type' => 'node',
'label' => t('Update node alias'),
'configurable' => FALSE,
'triggers' => array(),
);
$info['pathauto_taxonomy_term_update_action'] = array(
'type' => 'taxonomy_term',
'label' => t('Update taxonomy term alias'),
'configurable' => FALSE,
'triggers' => array(),
);
$info['pathauto_user_update_action'] = array(
'type' => 'user',
'label' => t('Update user alias'),
'configurable' => FALSE,
'triggers' => array(),
);
return $info;
@@ -393,7 +540,7 @@ function pathauto_action_info() {
* Returns the language code of the given entity.
*
* Backward compatibility layer to ensure that installations running an older
* version of core where entity_language() is not avilable do not break.
* version of core where entity_language() is not available do not break.
*
* @param string $entity_type
* An entity type.
@@ -417,6 +564,46 @@ function pathauto_entity_language($entity_type, $entity, $check_language_propert
return !empty($langcode) ? $langcode : LANGUAGE_NONE;
}
function pathauto_is_alias_reserved($alias, $source, $langcode = LANGUAGE_NONE) {
foreach (module_implements('pathauto_is_alias_reserved') as $module) {
$result = module_invoke($module, 'pathauto_is_alias_reserved', $alias, $source, $langcode);
if (!empty($result)) {
// As soon as the first module says that an alias is in fact reserved,
// then there is no point in checking the rest of the modules.
return TRUE;
}
}
return FALSE;
}
/**
* Implements hook_pathauto_is_alias_reserved() on behalf of path.module.
*/
function path_pathauto_is_alias_reserved($alias, $source, $langcode) {
// For language neutral content, we need to make sure the alias doesn't
// collide with any existing aliases. For localized content, just make sure
// it doesn't collide with same language or language neutral aliases.
$query = db_select('url_alias', 'ua')
->fields('ua', array('pid'))
->condition('source', $source, '<>')
->condition('alias', $alias);
if ($langcode != LANGUAGE_NONE) {
$query->condition('language', array($langcode, LANGUAGE_NONE), 'IN');
}
return $query->execute()->rowCount() > 0;
}
/**
* Implements hook_pathauto_is_alias_reserved().
*/
function pathauto_pathauto_is_alias_reserved($alias, $source, $langcode) {
module_load_include('inc', 'pathauto');
return _pathauto_path_is_callback($alias);
}
if (!function_exists('path_field_extra_fields')) {
/**
* Implements hook_field_extra_fields() on behalf of path.module.
@@ -459,6 +646,47 @@ function path_field_extra_fields() {
* @{
*/
/**
* Implements hook_path_alias_types() on behalf of node module.
*/
function node_path_alias_types() {
return array('node/' => t('Content'));
}
/**
* Implements hook_pathauto() on behalf of node module.
*/
function node_pathauto($op) {
if ($op == 'settings') {
$settings = array();
$settings['module'] = 'node';
$settings['token_type'] = 'node';
$settings['groupheader'] = t('Content paths');
$settings['patterndescr'] = t('Default path pattern (applies to all content types with blank patterns below)');
$settings['patterndefault'] = 'content/[node:title]';
$settings['batch_update_callback'] = 'node_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
$languages = array();
if (module_exists('locale')) {
$languages = array(LANGUAGE_NONE => t('language neutral')) + locale_language_list('name');
}
foreach (node_type_get_names() as $node_type => $node_name) {
if (count($languages) && variable_get('language_content_type_' . $node_type, 0)) {
$settings['patternitems'][$node_type] = t('Default path pattern for @node_type (applies to all @node_type content types with blank patterns below)', array('@node_type' => $node_name));
foreach ($languages as $lang_code => $lang_name) {
$settings['patternitems'][$node_type . '_' . $lang_code] = t('Pattern for all @language @node_type paths', array('@node_type' => $node_name, '@language' => $lang_name));
}
}
else {
$settings['patternitems'][$node_type] = t('Pattern for all @node_type paths', array('@node_type' => $node_name));
}
}
return (object) $settings;
}
}
/**
* Implements hook_node_insert().
*/
@@ -517,20 +745,20 @@ function pathauto_node_operations() {
*/
function pathauto_node_update_alias(stdClass $node, $op, array $options = array()) {
// Skip processing if the user has disabled pathauto for the node.
if (isset($node->path['pathauto']) && empty($node->path['pathauto'])) {
return;
if (isset($node->path['pathauto']) && empty($node->path['pathauto']) && empty($options['force'])) {
return FALSE;
}
$options += array('language' => pathauto_entity_language('node', $node));
// Skip processing if the node has no pattern.
if (!pathauto_pattern_load_by_entity('node', $node->type, $options['language'])) {
return;
return FALSE;
}
module_load_include('inc', 'pathauto');
$uri = entity_uri('node', $node);
pathauto_create_alias('node', $op, $uri['path'], array('node' => $node), $node->type, $options['language']);
return pathauto_create_alias('node', $op, $uri['path'], array('node' => $node), $node->type, $options['language']);
}
/**
@@ -573,6 +801,42 @@ function pathauto_node_update_action($node, $context = array()) {
* @{
*/
/**
* Implements hook_path_alias_types() on behalf of taxonomy module.
*/
function taxonomy_path_alias_types() {
return array('taxonomy/term/' => t('Taxonomy terms'));
}
/**
* Implements hook_pathauto() on behalf of taxonomy module.
*/
function taxonomy_pathauto($op) {
if ($op == 'settings') {
$settings = array();
$settings['module'] = 'taxonomy_term';
$settings['token_type'] = 'term';
$settings['groupheader'] = t('Taxonomy term paths');
$settings['patterndescr'] = t('Default path pattern (applies to all vocabularies with blank patterns below)');
$settings['patterndefault'] = '[term:vocabulary]/[term:name]';
$settings['batch_update_callback'] = 'taxonomy_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
$vocabularies = taxonomy_get_vocabularies();
if (count($vocabularies)) {
$settings['patternitems'] = array();
foreach ($vocabularies as $vid => $vocabulary) {
if ($vid == variable_get('forum_nav_vocabulary', '')) {
// Skip the forum vocabulary.
continue;
}
$settings['patternitems'][$vocabulary->machine_name] = t('Pattern for all %vocab-name paths', array('%vocab-name' => $vocabulary->name));
}
}
return (object) $settings;
}
}
/**
* Implements hook_taxonomy_term_insert().
*/
@@ -617,8 +881,8 @@ function pathauto_form_taxonomy_form_term_alter(&$form, $form_state) {
*/
function pathauto_taxonomy_term_update_alias(stdClass $term, $op, array $options = array()) {
// Skip processing if the user has disabled pathauto for the term.
if (isset($term->path['pathauto']) && empty($term->path['pathauto'])) {
return;
if (isset($term->path['pathauto']) && empty($term->path['pathauto']) && empty($options['force'])) {
return FALSE;
}
$module = 'taxonomy_term';
@@ -627,7 +891,7 @@ function pathauto_taxonomy_term_update_alias(stdClass $term, $op, array $options
$module = 'forum';
}
else {
return;
return FALSE;
}
}
@@ -644,21 +908,22 @@ function pathauto_taxonomy_term_update_alias(stdClass $term, $op, array $options
// Skip processing if the term has no pattern.
if (!pathauto_pattern_load_by_entity($module, $term->vocabulary_machine_name)) {
return;
return FALSE;
}
module_load_include('inc', 'pathauto');
$uri = entity_uri('taxonomy_term', $term);
pathauto_create_alias($module, $op, $uri['path'], array('term' => $term), $term->vocabulary_machine_name, $options['language']);
$result = pathauto_create_alias($module, $op, $uri['path'], array('term' => $term), $term->vocabulary_machine_name, $options['language']);
if (!empty($options['alias children'])) {
// For all children generate new aliases.
$options['alias children'] = FALSE;
unset($options['language']);
foreach (taxonomy_get_tree($term->vid, $term->tid) as $subterm) {
foreach (taxonomy_get_children($term->tid, $term->vid) as $subterm) {
pathauto_taxonomy_term_update_alias($subterm, $op, $options);
}
}
return $result;
}
/**
@@ -696,11 +961,68 @@ function pathauto_taxonomy_term_update_action($term, $context = array()) {
* @} End of "name pathauto_taxonomy".
*/
/**
* @name pathauto_forum Pathauto integration for the core forum module.
* @{
*/
/**
* Implements hook_path_alias_types() on behalf of forum module.
*/
function forum_path_alias_types() {
return array('forum/' => t('Forums'));
}
/**
* Implements hook_pathauto() for forum module.
*/
function forum_pathauto($op) {
if ($op == 'settings') {
$settings = array();
$settings['module'] = 'forum';
$settings['token_type'] = 'term';
$settings['groupheader'] = t('Forum paths');
$settings['patterndescr'] = t('Pattern for forums and forum containers');
$settings['patterndefault'] = '[term:vocabulary]/[term:name]';
$settings['batch_update_callback'] = 'forum_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
}
}
/**
* @} End of "name pathauto_forum".
*/
/**
* @name pathauto_user Pathauto integration for the core user and blog modules.
* @{
*/
/**
* Implements hook_path_alias_types() on behalf of user module.
*/
function user_path_alias_types() {
return array('user/' => t('Users'));
}
/**
* Implements hook_pathauto() on behalf of user module.
*/
function user_pathauto($op) {
if ($op == 'settings') {
$settings = array();
$settings['module'] = 'user';
$settings['token_type'] = 'user';
$settings['groupheader'] = t('User paths');
$settings['patterndescr'] = t('Pattern for user account page paths');
$settings['patterndefault'] = 'users/[user:name]';
$settings['batch_update_callback'] = 'user_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
}
}
/**
* Implements hook_user_insert().
*/
@@ -748,8 +1070,8 @@ function pathauto_user_operations() {
*/
function pathauto_user_update_alias(stdClass $account, $op, array $options = array()) {
// Skip processing if the user has disabled pathauto for the account.
if (isset($account->path['pathauto']) && empty($account->path['pathauto'])) {
return;
if (isset($account->path['pathauto']) && empty($account->path['pathauto']) && empty($options['force'])) {
return FALSE;
}
$options += array(
@@ -761,17 +1083,19 @@ function pathauto_user_update_alias(stdClass $account, $op, array $options = arr
// Skip processing if the account has no pattern.
if (!pathauto_pattern_load_by_entity('user', '', $options['language'])) {
return;
return FALSE;
}
module_load_include('inc', 'pathauto');
$uri = entity_uri('user', $account);
pathauto_create_alias('user', $op, $uri['path'], array('user' => $account), NULL, $options['language']);
$return = pathauto_create_alias('user', $op, $uri['path'], array('user' => $account), NULL, $options['language']);
// Because blogs are also associated with users, also generate the blog paths.
if (!empty($options['alias blog'])) {
pathauto_blog_update_alias($account, $op, $options);
}
return $return;
}
/**
@@ -805,6 +1129,39 @@ function pathauto_user_update_action($account, $context = array()) {
pathauto_user_update_alias($account, 'bulkupdate', array('message' => TRUE));
}
/**
* @} End of "name pathauto_user".
*/
/**
* @name pathauto_blog Pathauto integration for the core blog module.
* @{
*/
/**
* Implements hook_path_alias_types() on behalf of blog module.
*/
function blog_path_alias_types() {
return array('blog/' => t('User blogs'));
}
/**
* Implements hook_pathauto() on behalf of blog module.
*/
function blog_pathauto($op) {
if ($op == 'settings') {
$settings = array();
$settings['module'] = 'blog';
$settings['token_type'] = 'user';
$settings['groupheader'] = t('Blog paths');
$settings['patterndescr'] = t('Pattern for blog page paths');
$settings['patterndefault'] = 'blogs/[user:name]';
$settings['batch_update_callback'] = 'blog_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
}
}
/**
* Update the blog URL aliases for an individual user account.
*
@@ -819,7 +1176,7 @@ function pathauto_user_update_action($account, $context = array()) {
function pathauto_blog_update_alias(stdClass $account, $op, array $options = array()) {
// Skip processing if the blog has no pattern.
if (!pathauto_pattern_load_by_entity('blog')) {
return;
return FALSE;
}
$options += array(
@@ -828,7 +1185,7 @@ function pathauto_blog_update_alias(stdClass $account, $op, array $options = arr
module_load_include('inc', 'pathauto');
if (node_access('create', 'blog', $account)) {
pathauto_create_alias('blog', $op, "blog/{$account->uid}", array('user' => $account), NULL, $options['language']);
return pathauto_create_alias('blog', $op, "blog/{$account->uid}", array('user' => $account), NULL, $options['language']);
}
else {
pathauto_path_delete_all("blog/{$account->uid}");
@@ -836,5 +1193,30 @@ function pathauto_blog_update_alias(stdClass $account, $op, array $options = arr
}
/**
* @} End of "name pathauto_user".
* @} End of "name pathauto_blog".
*/
/**
* Implements hook_features_pipe_COMPONENT_alter().
*/
function pathauto_features_pipe_node_alter(&$pipe, $data, $export) {
foreach ($data as $node_type) {
$pipe['variable'][] = "pathauto_node_{$node_type}_pattern";
if (module_exists('locale')) {
$langcodes = array_keys(locale_language_list('name'));
$langcodes[] = LANGUAGE_NONE;
foreach ($langcodes as $langcode) {
$pipe['variable'][] = "pathauto_node_{$node_type}_{$langcode}_pattern";
}
}
}
}
/**
* Implements hook_features_pipe_COMPONENT_alter().
*/
function pathauto_features_pipe_taxonomy_alter(&$pipe, $data, $export) {
foreach ($data as $vocabulary) {
$pipe['variable'][] = "pathauto_taxonomy_term_{$vocabulary}_pattern";
}
}
@@ -7,79 +7,6 @@
* @ingroup pathauto
*/
/**
* Implements hook_path_alias_types().
*
* Used primarily by the bulk delete form.
*/
function pathauto_path_alias_types() {
$objects['user/'] = t('Users');
$objects['node/'] = t('Content');
if (module_exists('blog')) {
$objects['blog/'] = t('User blogs');
}
if (module_exists('taxonomy')) {
$objects['taxonomy/term/'] = t('Taxonomy terms');
}
if (module_exists('forum')) {
$objects['forum/'] = t('Forums');
}
return $objects;
}
/**
* Implements hook_pathauto().
*
* This function is empty so that the other core module implementations can be
* defined in this file. This is because in pathauto_module_implements_alter()
* we add pathauto to be included first. The module system then peforms a
* check on any subsequent run if this function still exists. If this does not
* exist, than this file will not get included and the core implementations
* will never get run.
*
* @see pathauto_module_implements_alter().
*/
function pathauto_pathauto() {
// Empty hook; see the above comment.
}
/**
* Implements hook_pathauto().
*/
function node_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'node';
$settings['token_type'] = 'node';
$settings['groupheader'] = t('Content paths');
$settings['patterndescr'] = t('Default path pattern (applies to all content types with blank patterns below)');
$settings['patterndefault'] = 'content/[node:title]';
$settings['batch_update_callback'] = 'node_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
$languages = array();
if (module_exists('locale')) {
$languages = array(LANGUAGE_NONE => t('language neutral')) + locale_language_list('name');
}
foreach (node_type_get_names() as $node_type => $node_name) {
if (count($languages) && variable_get('language_content_type_' . $node_type, 0)) {
$settings['patternitems'][$node_type] = t('Default path pattern for @node_type (applies to all @node_type content types with blank patterns below)', array('@node_type' => $node_name));
foreach ($languages as $lang_code => $lang_name) {
$settings['patternitems'][$node_type . '_' . $lang_code] = t('Pattern for all @language @node_type paths', array('@node_type' => $node_name, '@language' => $lang_name));
}
}
else {
$settings['patternitems'][$node_type] = t('Pattern for all @node_type paths', array('@node_type' => $node_name));
}
}
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for nodes.
*/
@@ -122,38 +49,6 @@ function node_pathauto_bulk_update_batch_process(&$context) {
}
}
/**
* Implements hook_pathauto().
*/
function taxonomy_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'taxonomy_term';
$settings['token_type'] = 'term';
$settings['groupheader'] = t('Taxonomy term paths');
$settings['patterndescr'] = t('Default path pattern (applies to all vocabularies with blank patterns below)');
$settings['patterndefault'] = '[term:vocabulary]/[term:name]';
$settings['batch_update_callback'] = 'taxonomy_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
$vocabularies = taxonomy_get_vocabularies();
if (count($vocabularies)) {
$settings['patternitems'] = array();
foreach ($vocabularies as $vid => $vocabulary) {
if ($vid == variable_get('forum_nav_vocabulary', '')) {
// Skip the forum vocabulary.
continue;
}
$settings['patternitems'][$vocabulary->machine_name] = t('Pattern for all %vocab-name paths', array('%vocab-name' => $vocabulary->name));
}
}
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for taxonomy terms.
*/
@@ -200,26 +95,6 @@ function taxonomy_pathauto_bulk_update_batch_process(&$context) {
}
}
/**
* Implements hook_pathauto() for forum module.
*/
function forum_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'forum';
$settings['token_type'] = 'term';
$settings['groupheader'] = t('Forum paths');
$settings['patterndescr'] = t('Pattern for forums and forum containers');
$settings['patterndefault'] = '[term:vocabulary]/[term:name]';
$settings['batch_update_callback'] = 'forum_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for forums.
*/
@@ -263,26 +138,6 @@ function forum_pathauto_bulk_update_batch_process(&$context) {
}
}
/**
* Implements hook_pathauto().
*/
function user_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'user';
$settings['token_type'] = 'user';
$settings['groupheader'] = t('User paths');
$settings['patterndescr'] = t('Pattern for user account page paths');
$settings['patterndefault'] = 'users/[user:name]';
$settings['batch_update_callback'] = 'user_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for users.
*/
@@ -325,26 +180,6 @@ function user_pathauto_bulk_update_batch_process(&$context) {
}
}
/**
* Implements hook_pathauto().
*/
function blog_pathauto($op) {
switch ($op) {
case 'settings':
$settings = array();
$settings['module'] = 'blog';
$settings['token_type'] = 'user';
$settings['groupheader'] = t('Blog paths');
$settings['patterndescr'] = t('Pattern for blog page paths');
$settings['patterndefault'] = 'blogs/[user:name]';
$settings['batch_update_callback'] = 'blog_pathauto_bulk_update_batch_process';
$settings['batch_file'] = drupal_get_path('module', 'pathauto') . '/pathauto.pathauto.inc';
return (object) $settings;
default:
break;
}
}
/**
* Batch processing callback; Generate aliases for blogs.
*/
@@ -55,9 +55,13 @@ class PathautoTestHelper extends DrupalWebTestCase {
$this->assertEntityAlias($entity_type, $entity, $uri['path'], $language);
}
function assertNoEntityAliasExists($entity_type, $entity) {
function assertNoEntityAliasExists($entity_type, $entity, $alias = NULL) {
$uri = entity_uri($entity_type, $entity);
$this->assertNoAliasExists(array('source' => $uri['path']));
$path = array('source' => $uri['path']);
if (!empty($alias)) {
$path['alias'] = $alias;
}
$this->assertNoAliasExists($path);
}
function assertAlias($source, $expected_alias, $language = LANGUAGE_NONE) {
@@ -192,6 +196,23 @@ class PathautoUnitTestCase extends PathautoTestHelper {
}
}
/**
* Test pathauto_clean_alias().
*/
function testCleanAlias() {
$tests = array();
$tests['one/two/three'] = 'one/two/three';
$tests['/one/two/three/'] = 'one/two/three';
$tests['one//two///three'] = 'one/two/three';
$tests['one/two--three/-/--/-/--/four---five'] = 'one/two-three/four-five';
$tests['one/-//three--/four'] = 'one/three/four';
foreach ($tests as $input => $expected) {
$output = pathauto_clean_alias($input);
$this->assertEqual($output, $expected, t("pathauto_clean_alias('@input') expected '@expected', actual '@output'", array('@input' => $input, '@expected' => $expected, '@output' => $output)));
}
}
/**
* Test pathauto_path_delete_multiple().
*/
@@ -244,7 +265,7 @@ class PathautoUnitTestCase extends PathautoTestHelper {
$node->title = 'Fifth title';
pathauto_node_update($node);
$this->assertEntityAlias('node', $node, 'content/fourth-title');
$this->assertNoAliasExists(array('alias' => 'content/fith-title'));
$this->assertNoAliasExists(array('alias' => 'content/fifth-title'));
// Test PATHAUTO_UPDATE_ACTION_NO_NEW with unaliased node and 'update'.
$this->deleteAllAliases();
@@ -289,6 +310,40 @@ class PathautoUnitTestCase extends PathautoTestHelper {
$this->assertEntityAlias('taxonomy_term', $term2, 'My Crazy/Alias/child-term');
}
/**
* Test using fields for path structures.
*/
function testParentChildPathTokens() {
// First create a field which will be used to create the path. It must
// begin with a letter.
$fieldname = 'a' . drupal_strtolower($this->randomName());
field_create_field(array('field_name' => $fieldname, 'type' => 'text'));
field_create_instance(array('field_name' => $fieldname, 'entity_type' => 'taxonomy_term', 'bundle' => 'tags'));
// Make the path pattern of a field use the value of this field appended
// to the parent taxonomy term's pattern if there is one.
variable_set('pathauto_taxonomy_term_tags_pattern', '[term:parents:join-path]/[term:' . $fieldname . ']');
// Start by creating a parent term.
$parent = new stdClass();
$parent->$fieldname = array(LANGUAGE_NONE => array(array('value' => $parent->name = $this->randomName())));
$parent->vid = 1;
taxonomy_term_save($parent);
// Create the child term.
$child = new stdClass();
$child->name = $this->randomName();
$child->$fieldname = array(LANGUAGE_NONE => array(array('value' => $child->name = $this->randomName())));
$child->vid = 1;
$child->parent = $parent->tid;
taxonomy_term_save($child);
$this->assertEntityAlias('taxonomy_term', $child, drupal_strtolower($parent->name . '/' . $child->name));
// Re-saving the parent term should not modify the child term's alias.
taxonomy_term_save($parent);
$this->assertEntityAlias('taxonomy_term', $child, drupal_strtolower($parent->name . '/' . $child->name));
}
function testEntityBundleRenamingDeleting() {
// Create a vocabulary and test that it's pattern variable works.
$vocab = $this->addVocabulary(array('machine_name' => 'old_name'));
@@ -315,17 +370,17 @@ class PathautoUnitTestCase extends PathautoTestHelper {
// Check that Pathauto does not create an alias of '/admin'.
$node = $this->drupalCreateNode(array('title' => 'Admin', 'type' => 'page'));
$this->assertNoEntityAlias('node', $node);
$this->assertEntityAlias('node', $node, 'admin-0');
// Check that Pathauto does not create an alias of '/modules'.
$node->title = 'Modules';
node_save($node);
$this->assertNoEntityAlias('node', $node);
$this->assertEntityAlias('node', $node, 'modules-0');
// Check that Pathauto does not create an alias of '/index.php'.
$node->title = 'index.php';
node_save($node);
$this->assertNoEntityAlias('node', $node);
$this->assertEntityAlias('node', $node, 'index.php-0');
// Check that a safe value gets an automatic alias. This is also a control
// to ensure the above tests work properly.
@@ -333,6 +388,18 @@ class PathautoUnitTestCase extends PathautoTestHelper {
node_save($node);
$this->assertEntityAlias('node', $node, 'safe-value');
}
function testPathAliasUniquifyWordsafe() {
variable_set('pathauto_max_length', 25);
$node_1 = $this->drupalCreateNode(array('title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page'));
$node_2 = $this->drupalCreateNode(array('title' => 'thequick brownfox jumpedover thelazydog', 'type' => 'page'));
// Check that pathauto_alias_uniquify is calling truncate_utf8 with $wordsafe param set to TRUE.
// If it doesn't path alias result would be content/thequick-brownf-0
$this->assertEntityAlias('node', $node_1, 'content/thequick-brownfox');
$this->assertEntityAlias('node', $node_2, 'content/thequick-0');
}
}
/**
@@ -408,13 +475,23 @@ class PathautoFunctionalTestCase extends PathautoFunctionalTestHelper {
$this->drupalGet($automatic_alias);
$this->assertText($title, 'Node accessible through automatic alias.');
// Disable the update action. The checkbox should not be visible.
variable_set('pathauto_update_action', 0);
$this->drupalGet("node/{$node->nid}/edit");
$this->assertNoFieldById('edit-path-pathauto');
// Reset the update action back to default. The checkbox should be visible.
variable_del('pathauto_update_action');
$this->drupalGet("node/{$node->nid}/edit");
$this->assertFieldChecked('edit-path-pathauto');
// Manually set the node's alias.
$manual_alias = 'content/' . $node->nid;
$edit = array(
'path[pathauto]' => FALSE,
'path[alias]' => $manual_alias,
);
$this->drupalPost("node/{$node->nid}/edit", $edit, t('Save'));
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertText("Basic page $title has been updated.");
// Check that the automatic alias checkbox is now unchecked by default.
@@ -449,6 +526,26 @@ class PathautoFunctionalTestCase extends PathautoFunctionalTestHelper {
$this->assertNoFieldById('edit-path-pathauto');
$this->assertFieldByName('path[alias]', '');
$this->assertNoEntityAlias('node', $node);
// Set the page pattern to use only tokens so we can test the checkbox
// behavior if none of the tokens have a value currently.
variable_set('pathauto_node_page_pattern', '[node:title]');
// Create a node with an empty title. The Pathauto checkbox should still be
// visible but unchecked.
$node = $this->drupalCreateNode(array('type' => 'page', 'title' => ''));
$this->drupalGet('node/' . $node->nid . '/edit');
$this->assertNoFieldChecked('edit-path-pathauto');
$this->assertFieldByName('path[alias]', '');
$this->assertNoEntityAlias('node', $node);
$edit = array();
$edit['title'] = 'Valid title';
$edit['path[pathauto]'] = TRUE;
$this->drupalPost(NULL, $edit, t('Save'));
$this->drupalGet('node/' . $node->nid . '/edit');
$this->assertFieldChecked('edit-path-pathauto');
$this->assertFieldByName('path[alias]', 'valid-title');
}
/**
@@ -472,6 +569,83 @@ class PathautoFunctionalTestCase extends PathautoFunctionalTestHelper {
$this->assertEntityAlias('node', $node2, 'node/' . $node2->nid);
}
/**
* @todo Merge this with existing node test methods?
*/
public function testNodeState() {
$nodeNoAliasUser = $this->drupalCreateUser(array('bypass node access'));
$nodeAliasUser = $this->drupalCreateUser(array('bypass node access', 'create url aliases'));
$node = $this->drupalCreateNode(array(
'title' => 'Node version one',
'type' => 'page',
'path' => array(
'pathauto' => FALSE,
),
));
$this->assertNoEntityAlias('node', $node);
// Set a manual path alias for the node.
$node->path['alias'] = 'test-alias';
node_save($node);
// Ensure that the pathauto field was saved to the database.
$node = node_load($node->nid, NULL, TRUE);
$this->assertFalse($node->path['pathauto']);
// Ensure that the manual path alias was saved and an automatic alias was not generated.
$this->assertEntityAlias('node', $node, 'test-alias');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-one');
// Save the node as a user who does not have access to path fieldset.
$this->drupalLogin($nodeNoAliasUser);
$this->drupalGet('node/' . $node->nid . '/edit');
$this->assertNoFieldByName('path[pathauto]');
$edit = array('title' => 'Node version two');
$this->drupalPost(NULL, $edit, 'Save');
$this->assertText('Basic page Node version two has been updated.');
$this->assertEntityAlias('node', $node, 'test-alias');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-one');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-two');
// Load the edit node page and check that the Pathauto checkbox is unchecked.
$this->drupalLogin($nodeAliasUser);
$this->drupalGet('node/' . $node->nid . '/edit');
$this->assertNoFieldChecked('edit-path-pathauto');
// Edit the manual alias and save the node.
$edit = array(
'title' => 'Node version three',
'path[alias]' => 'manually-edited-alias',
);
$this->drupalPost(NULL, $edit, 'Save');
$this->assertText('Basic page Node version three has been updated.');
$this->assertEntityAlias('node', $node, 'manually-edited-alias');
$this->assertNoEntityAliasExists('node', $node, 'test-alias');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-one');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-two');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-three');
// Programatically save the node with an automatic alias.
$node = node_load($node->nid, NULL, TRUE);
$node->path['pathauto'] = TRUE;
node_save($node);
// Ensure that the pathauto field was saved to the database.
$node = node_load($node->nid, NULL, TRUE);
$this->assertTrue($node->path['pathauto']);
$this->assertEntityAlias('node', $node, 'content/node-version-three');
$this->assertNoEntityAliasExists('node', $node, 'manually-edited-alias');
$this->assertNoEntityAliasExists('node', $node, 'test-alias');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-one');
$this->assertNoEntityAliasExists('node', $node, 'content/node-version-two');
}
/**
* Basic functional testing of Pathauto with taxonomy terms.
*/
@@ -672,6 +846,14 @@ class PathautoLocaleTestCase extends PathautoFunctionalTestHelper {
$this->assertEntityAlias('node', $node, 'content/english-node-0', 'en');
$this->assertEntityAlias('node', $node, 'french-node', 'fr');
$this->assertAliasExists(array('pid' => $english_alias['pid'], 'alias' => 'content/english-node-0'));
// Create a new node with the same title as before but without
// specifying a language.
$node = $this->drupalCreateNode(array('title' => 'English node'));
// Check that the new node had a unique alias generated with the '-1'
// suffix.
$this->assertEntityAlias('node', $node, 'content/english-node-1');
}
}
@@ -718,11 +900,11 @@ class PathautoBulkUpdateTestCase extends PathautoFunctionalTestHelper {
// Add a new node.
$new_node = $this->drupalCreateNode(array('path' => array('alias' => '', 'pathauto' => FALSE)));
// Run the update again which should only run against the new node.
// Run the update again which should not run against any nodes.
$this->drupalPost('admin/config/search/path/update_bulk', $edit, t('Update'));
$this->assertText('Generated 1 URL alias.'); // 1 node + 0 users
$this->assertText('No new URL aliases to generate.');
$this->assertEntityAliasExists('node', $new_node);
$this->assertNoEntityAliasExists('node', $new_node);
}
}
@@ -35,7 +35,7 @@ function pathauto_tokens($type, $tokens, array $data = array(), array $options =
$values = array();
foreach (element_children($array) as $key) {
$value = is_array($array[$key]) ? render($array[$key]) : (string) $array[$key];
$value = pathauto_cleanstring($value);
$value = pathauto_cleanstring($value, $options);
$values[] = $value;
}
$replacements[$original] = implode('/', $values);
@@ -113,6 +113,20 @@ Production monitor
6. If you wish to fetch the data immediately, check the appropriate box and save
the settings. Good to go!
Cron setup
----------
To automatically check the site status and/or module updates on cron, you will
need to install drush and configure the following tasks in the crontab:
# Check ALL sites for updates, once a day starting at 0100H at night.
0 1 * * * /path/to/drush -r /path/to/docroot prod-monitor-updates -y --quiet
# Fetch ALL site data every five minutes (or whatever you please obviously).
0/5 * * * * /path/to/drush -r /path/to/docroot prod-monitor-fetch -y --quiet
Obviously, the time and frequency of these cron jobs is at your discretion.
Do note that, depending on the number of sites you have configured, the crons
may be running for quite some time, especially the module update checking job!
Upgrading
---------
When upgrading Production monitor to a newer version, always run update.php to
@@ -123,9 +137,9 @@ Nagios
------
1. Download and install the Nagios module from http://drupal.org/project/nagios
as per its readme instructions
2. Enable Nagios support in the prod_check module on /admin/settings/prod-check
2. Enable Nagios support in the prod_check module on /admin/config/system/prod-check
by ticking the appropriate box.
3. Untick the checboxes for those items you do not whish to be monitored by
3. Untick the checkboxes for those items you do not whish to be monitored by
Nagios.
4. Save the settings and you're good to go!
@@ -172,7 +186,7 @@ For Production monitor, these commands are available:
$ drush prod-monitor-fetch [id]
$ drush prod-monitor-flush [id]
$ drush prod-monitor-delete [id]
$ drush prod-monitor-updates [id] (--check)
$ drush prod-monitor-updates [id] (--check, --security-only)
or their aliases:
@@ -180,7 +194,7 @@ or their aliases:
$ drush pmon-fe [id]
$ drush pmon-fl [id]
$ drush pmon-rm [id]
$ drush pmon-up [id] (--check)
$ drush pmon-up [id] (--check, --security-only)
The id parameter is optional for the prod-monitor command. The best usage is to
first get a list of sites:
@@ -200,16 +214,19 @@ You can pass multiple ID's by separating them with spaces:
The prod-monitor-updates command acts on one id only!
APC
---
APC/OPcache
-----------
Production Check complains about APC not being installed or misconfigured. What
is APC you wonder? Well, APC is an opcode caching mechanism that will pre-com-
pile PHP files and keep them stored in memory. The full manual can be found
here: http://php.net/manual/en/book.apc.php .
For Drupal sites, it is important to tune APC in order to achieve maximum per-
formance there. Drupal uses a massive amount of files and therefore you should
assign a proper amount of RAM to APC. For a dedicated setup 64Mb should be
sufficient, in shared setups, you should easily double that!
PHP version 5.5 comes bundled with an alternative to APC named OPcache. The full
manual can be found here: http://php.net/manual/en/book.opcache.php .
For Drupal sites, it is important to tune APC/OPcache in order to achieve
maximum performance there. Drupal uses a massive amount of files and therefore
you should assign a proper amount of RAM to APC/OPcache. For a dedicated setup
64Mb should be sufficient, in shared setups, you will need to multiply that!
To tune your setup, you can use the aforementioned hidden link provided by
Production check. You can see the memory usage there, verify your settings and
much more.
@@ -219,6 +236,7 @@ extension (drupal.org CVS did not seem to accept files with .ini extension?).
Note: This 'hidden link' makes use of the APC supplied PHP code and is subject
to the PHP license: http://www.php.net/license/3_01.txt .
The OPcache variant is taken from https://github.com/rlerdorf/opcache-status .
Updates
@@ -233,8 +251,8 @@ Cron is NOT used to do this, since we want to keep the transfer to a minimum.
Hidden link
===========
Production check adds some 'hidden links' to the site where you can check the
APC, Memcache and DB status of your site. These pages can be found on:
/admin/reports/status/apc
APC/OPcache, Memcache and DB status of your site. These pages can be found on:
/admin/reports/status/apc-opc
/admin/reports/status/memcache
/admin/reports/status/database
@@ -251,8 +269,8 @@ The detailed report page
The page is divided into 4 sections:
- Settings: checks various Drupal settings
- Server: checks that are 'outside of Drupal' such as APC and wether or not you
have removed the release note files from the root.
- Server: checks that are 'outside of Drupal' such as APC/OPcache and wether or
not you have removed the release note files from the root.
- Performance: checks relevant to the performance settings in Drupal such as
page / block caching.
- Modules: checks if certain modules are on / off
@@ -97,8 +97,8 @@ function prod_check_settings_form($form, &$form_state) {
$form['prod_check_apc'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced APC settings'),
'#description' => t('These settings are used in the !link functionality.', prod_check_link_array('advanced APC', 'admin/reports/status/apc')),
'#title' => t('Advanced APC/OPcache settings'),
'#description' => t('These settings are used in the !link functionality.', prod_check_link_array('advanced APC', 'admin/reports/status/apc-opc')),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
@@ -106,7 +106,7 @@ function prod_check_settings_form($form, &$form_state) {
// Cache full count threshold
$form['prod_check_apc']['prod_check_apc_expunge'] = array(
'#type' => 'textfield',
'#title' => t('APC cache full count threshold'),
'#title' => t('APC/OPcache cache full count threshold'),
'#default_value' => variable_get('prod_check_apc_expunge', 0),
'#size' => 2,
'#description' => t('Issue a critical error when the cache full count is greater than the number entered here.'),
@@ -293,7 +293,7 @@ function prod_check_settings_form($form, &$form_state) {
'!settings' => l(t('Nagios page callback'), 'admin/config/system/nagios'),
'%callback' => 'prod_check_nagios_status_page',
)
) .'</p>',
) . '</p>',
);
$form['prod_check_nagios']['nagios']['settings']['prod_check_nagios_verbose'] = array(
@@ -428,7 +428,7 @@ function prod_check_settings_form_validate($form, &$form_state) {
}
if (!is_numeric($form_state['values']['prod_check_apc_expunge'])) {
form_set_error('prod_check_apc_expunge', t('APC Cache full count threshold should be numeric!'));
form_set_error('prod_check_apc_expunge', t('APC/OPcache Cache full count threshold should be numeric!'));
}
if (isset($form_state['values']['prod_check_enable_nagios']) && $form_state['values']['prod_check_enable_nagios']) {
@@ -461,9 +461,11 @@ function prod_check_settings_form_submit($form, &$form_state) {
case t('Save configuration'):
variable_set('prod_check_sitemail', $form_state['values']['prod_check_sitemail']);
// PHP errors.
variable_set('prod_check_dblog_php', $form_state['values']['prod_check_dblog_php']);
variable_set('prod_check_dblog_php_threshold', $form_state['values']['prod_check_dblog_php_threshold']);
// APC.
if (module_exists('dblog')) {
variable_set('prod_check_dblog_php', $form_state['values']['prod_check_dblog_php']);
variable_set('prod_check_dblog_php_threshold', $form_state['values']['prod_check_dblog_php_threshold']);
}
// APC/OPcache.
variable_set('prod_check_apc_expunge', $form_state['values']['prod_check_apc_expunge']);
variable_set('prod_check_apcuser', $form_state['values']['prod_check_apcuser']);
if (!empty($form_state['values']['prod_check_apcpass'])) {
@@ -1031,11 +1033,22 @@ function _prod_check_dbstatus_pgsql($db_name, $details) {
/**
* Integration of the APC status page.
*/
function prod_check_apc() {
define('ADMIN_USERNAME', variable_get('prod_check_apcuser', 'apc'));
define('ADMIN_PASSWORD', variable_get('prod_check_apcpass', 'password'));
include(drupal_get_path('module', 'prod_check') . '/includes/prod_check.apc.inc');
exit;
function prod_check_apc_opc() {
// APC.
if (function_exists('apc_cache_info')) {
define('ADMIN_USERNAME', variable_get('prod_check_apcuser', 'apc'));
define('ADMIN_PASSWORD', variable_get('prod_check_apcpass', 'password'));
include(drupal_get_path('module', 'prod_check') . '/includes/prod_check.apc.inc');
exit;
}
// OPcache.
elseif (function_exists('opcache_get_status')) {
include(drupal_get_path('module', 'prod_check') . '/includes/prod_check.opcache.inc');
exit;
}
else {
return t('APC nor OPcache is installed on this webserver!');
}
}
/**
@@ -0,0 +1,502 @@
<?php
function opcache_get_status() {
return array (
'opcache_enabled' => true,
'cache_full' => false,
'memory_usage' =>
array (
'used_memory' => 12028872,
'free_memory' => 4235696,
'wasted_memory' => 512648,
'current_wasted_percentage' => 3.0556201934814,
),
'opcache_statistics' =>
array (
'num_cached_scripts' => 59,
'num_cached_keys' => 78,
'max_cached_keys' => 223,
'hits' => 66817,
'last_restart_time' => 0,
'misses' => 126,
'blacklist_misses' => 0,
'blacklist_miss_ratio' => 0,
'opcache_hit_rate' => 99.81178017119,
'oom_restarts' => 0,
'manual_restarts' => 0,
'hash_restarts' => 0,
),
'scripts' =>
array (
'/var/www/phpweb/manual/en/toc/faq.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/faq.inc',
'hits' => 9,
'memory_consumption' => 5680,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345905,
),
'/var/www/phpweb/downloads.php' =>
array (
'full_path' => '/var/www/phpweb/downloads.php',
'hits' => 86,
'memory_consumption' => 9488,
'last_used' => 'Sat Mar 16 12:03:47 2013',
'last_used_timestamp' => 1363460627,
'timestamp' => 1355102402,
),
'/var/www/phpweb/include/languages.inc' =>
array (
'full_path' => '/var/www/phpweb/include/languages.inc',
'hits' => 5605,
'memory_consumption' => 16984,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1362994804,
),
'/var/www/phpweb/include/header.inc' =>
array (
'full_path' => '/var/www/phpweb/include/header.inc',
'hits' => 9,
'memory_consumption' => 20352,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1357938001,
),
'/var/www/phpweb/manual/en/toc/getting-started.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/getting-started.inc',
'hits' => 9,
'memory_consumption' => 1936,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345409,
),
'/var/www/phpweb/manual/en/faq.php' =>
array (
'full_path' => '/var/www/phpweb/manual/en/faq.php',
'hits' => 122,
'memory_consumption' => 5152,
'last_used' => 'Sat Mar 16 12:06:15 2013',
'last_used_timestamp' => 1363460775,
'timestamp' => 1363345906,
),
'/var/www/phpweb/include/footer.inc' =>
array (
'full_path' => '/var/www/phpweb/include/footer.inc',
'hits' => 9,
'memory_consumption' => 1976,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1347648001,
),
'/var/www/phpweb/include/site.inc' =>
array (
'full_path' => '/var/www/phpweb/include/site.inc',
'hits' => 5605,
'memory_consumption' => 63488,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1354724402,
),
'/var/www/phpweb/include/mirrors.inc' =>
array (
'full_path' => '/var/www/phpweb/include/mirrors.inc',
'hits' => 5605,
'memory_consumption' => 96160,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363419613,
),
'/var/www/phpweb/manual/en/toc/refs.basic.vartype.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/refs.basic.vartype.inc',
'hits' => 9,
'memory_consumption' => 5032,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345844,
),
'/var/www/phpweb/include/layout.inc' =>
array (
'full_path' => '/var/www/phpweb/include/layout.inc',
'hits' => 5605,
'memory_consumption' => 145704,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1356610801,
),
'/var/www/phpweb/sites.php' =>
array (
'full_path' => '/var/www/phpweb/sites.php',
'hits' => 73,
'memory_consumption' => 2024,
'last_used' => 'Sat Mar 16 12:10:10 2013',
'last_used_timestamp' => 1363461010,
'timestamp' => 1354724402,
),
'/var/www/phpweb/search.php' =>
array (
'full_path' => '/var/www/phpweb/search.php',
'hits' => 3083,
'memory_consumption' => 19728,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1347648005,
),
'/var/www/phpweb/manual/en/toc/langref.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/langref.inc',
'hits' => 49,
'memory_consumption' => 7416,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345411,
),
'/var/www/phpweb/manual/en/toc/index.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/index.inc',
'hits' => 132,
'memory_consumption' => 4680,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345409,
),
'/var/www/phpweb/docs.php' =>
array (
'full_path' => '/var/www/phpweb/docs.php',
'hits' => 73,
'memory_consumption' => 4536,
'last_used' => 'Sat Mar 16 12:04:36 2013',
'last_used_timestamp' => 1363460676,
'timestamp' => 1347648000,
),
'/var/www/phpweb/include/shared-manual.inc' =>
array (
'full_path' => '/var/www/phpweb/include/shared-manual.inc',
'hits' => 122,
'memory_consumption' => 107688,
'last_used' => 'Sat Mar 16 12:06:15 2013',
'last_used_timestamp' => 1363460775,
'timestamp' => 1357938001,
),
'/var/www/phpweb/include/mozopensearch.inc' =>
array (
'full_path' => '/var/www/phpweb/include/mozopensearch.inc',
'hits' => 14,
'memory_consumption' => 1232,
'last_used' => 'Sat Mar 16 12:00:34 2013',
'last_used_timestamp' => 1363460434,
'timestamp' => 1347648001,
),
'/var/www/phpweb/include/ip-to-country.inc' =>
array (
'full_path' => '/var/www/phpweb/include/ip-to-country.inc',
'hits' => 5605,
'memory_consumption' => 21840,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1347648001,
),
'/var/www/phpweb/include/version.inc' =>
array (
'full_path' => '/var/www/phpweb/include/version.inc',
'hits' => 775,
'memory_consumption' => 7880,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363321202,
),
'/var/www/phpweb/include/errors.inc' =>
array (
'full_path' => '/var/www/phpweb/include/errors.inc',
'hits' => 691,
'memory_consumption' => 59888,
'last_used' => 'Sat Mar 16 12:10:33 2013',
'last_used_timestamp' => 1363461033,
'timestamp' => 1347648001,
),
'/var/www/phpweb/include/countries.inc' =>
array (
'full_path' => '/var/www/phpweb/include/countries.inc',
'hits' => 5605,
'memory_consumption' => 31184,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363419614,
),
'/var/www/phpweb/error.php' =>
array (
'full_path' => '/var/www/phpweb/error.php',
'hits' => 691,
'memory_consumption' => 61952,
'last_used' => 'Sat Mar 16 12:10:33 2013',
'last_used_timestamp' => 1363461033,
'timestamp' => 1347648000,
),
'/var/www/phpweb/manual/en/toc/refs.basic.text.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/refs.basic.text.inc',
'hits' => 9,
'memory_consumption' => 3312,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345831,
),
'/var/www/phpweb/include/loadavg.inc' =>
array (
'full_path' => '/var/www/phpweb/include/loadavg.inc',
'hits' => 3775,
'memory_consumption' => 12184,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1354738801,
),
'/var/www/phpweb/include/prepend.inc' =>
array (
'full_path' => '/var/www/phpweb/include/prepend.inc',
'hits' => 5605,
'memory_consumption' => 23432,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1347648001,
),
'/var/www/phpweb/o.php' =>
array (
'full_path' => '/var/www/phpweb/o.php',
'hits' => 1,
'memory_consumption' => 13424,
'last_used' => 'Sat Mar 16 18:11:21 2013',
'last_used_timestamp' => 1363482681,
'timestamp' => 1363482654,
),
'/var/www/phpweb/include/pregen-events.inc' =>
array (
'full_path' => '/var/www/phpweb/include/pregen-events.inc',
'hits' => 1141,
'memory_consumption' => 840,
'last_used' => 'Sat Mar 16 12:15:07 2013',
'last_used_timestamp' => 1363461307,
'timestamp' => 1363419615,
),
'/var/www/phpweb/opcache.php' =>
array (
'full_path' => '/var/www/phpweb/opcache.php',
'hits' => 0,
'memory_consumption' => 13944,
'last_used' => 'Sun Mar 17 01:22:31 2013',
'last_used_timestamp' => 1363508551,
'timestamp' => 1363508542,
),
'/var/www/phpweb/manual/en/toc/refs.calendar.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/refs.calendar.inc',
'hits' => 9,
'memory_consumption' => 2264,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345437,
),
'/var/www/phpweb/manual/en/toc/security.inc' =>
array (
'full_path' => '/var/www/phpweb/manual/en/toc/security.inc',
'hits' => 19,
'memory_consumption' => 5352,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363345419,
),
'/var/www/phpweb/include/pregen-news.inc' =>
array (
'full_path' => '/var/www/phpweb/include/pregen-news.inc',
'hits' => 1161,
'memory_consumption' => 57896,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363419615,
),
'/var/www/phpweb/my.php' =>
array (
'full_path' => '/var/www/phpweb/my.php',
'hits' => 34,
'memory_consumption' => 22640,
'last_used' => 'Sat Mar 16 12:15:15 2013',
'last_used_timestamp' => 1363461315,
'timestamp' => 1354724402,
),
'/var/www/phpweb/include/pregen-confs.inc' =>
array (
'full_path' => '/var/www/phpweb/include/pregen-confs.inc',
'hits' => 678,
'memory_consumption' => 1400,
'last_used' => 'Sat Mar 16 12:02:49 2013',
'last_used_timestamp' => 1363460569,
'timestamp' => 1363419615,
),
'/var/www/index.php' =>
array (
'full_path' => '/var/www/index.php',
'hits' => 1,
'memory_consumption' => 744,
'last_used' => 'Sat Mar 16 12:01:20 2013',
'last_used_timestamp' => 1363460480,
'timestamp' => 1358644238,
),
'/var/www/phpweb/index-stable.php' =>
array (
'full_path' => '/var/www/phpweb/index-stable.php',
'hits' => 679,
'memory_consumption' => 22208,
'last_used' => 'Sat Mar 16 12:02:49 2013',
'last_used_timestamp' => 1363460569,
'timestamp' => 1347648003,
),
'/var/www/phpweb/conferences/index.php' =>
array (
'full_path' => '/var/www/phpweb/conferences/index.php',
'hits' => 462,
'memory_consumption' => 3872,
'last_used' => 'Sat Mar 16 12:15:07 2013',
'last_used_timestamp' => 1363461307,
'timestamp' => 1347648000,
),
'/var/www/phpweb/support.php' =>
array (
'full_path' => '/var/www/phpweb/support.php',
'hits' => 73,
'memory_consumption' => 1912,
'last_used' => 'Sat Mar 16 12:06:40 2013',
'last_used_timestamp' => 1363460800,
'timestamp' => 1347648005,
),
'/var/www/phpweb/op.php' =>
array (
'full_path' => '/var/www/phpweb/op.php',
'hits' => 0,
'memory_consumption' => 1448,
'last_used' => 'Sun Mar 17 01:34:33 2013',
'last_used_timestamp' => 1363509273,
'timestamp' => 1363509263,
),
'/var/www/phpweb/include/posttohost.inc' =>
array (
'full_path' => '/var/www/phpweb/include/posttohost.inc',
'hits' => 342,
'memory_consumption' => 3824,
'last_used' => 'Sat Mar 16 12:09:18 2013',
'last_used_timestamp' => 1363460958,
'timestamp' => 1347648001,
),
'/var/www/phpweb/include/langchooser.inc' =>
array (
'full_path' => '/var/www/phpweb/include/langchooser.inc',
'hits' => 5605,
'memory_consumption' => 23784,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1347648001,
),
'/var/www/phpweb/include/manual-lookup.inc' =>
array (
'full_path' => '/var/www/phpweb/include/manual-lookup.inc',
'hits' => 624,
'memory_consumption' => 26648,
'last_used' => 'Sat Mar 16 12:10:33 2013',
'last_used_timestamp' => 1363461033,
'timestamp' => 1354750802,
),
'/var/www/phpweb/mailing-lists.php' =>
array (
'full_path' => '/var/www/phpweb/mailing-lists.php',
'hits' => 342,
'memory_consumption' => 31576,
'last_used' => 'Sat Mar 16 12:09:18 2013',
'last_used_timestamp' => 1363460958,
'timestamp' => 1361200802,
),
'/var/www/phpweb/include/last_updated.inc' =>
array (
'full_path' => '/var/www/phpweb/include/last_updated.inc',
'hits' => 5605,
'memory_consumption' => 840,
'last_used' => 'Sat Mar 16 12:16:31 2013',
'last_used_timestamp' => 1363461391,
'timestamp' => 1363419675,
),
'/var/www/phpweb/include/email-validation.inc' =>
array (
'full_path' => '/var/www/phpweb/include/email-validation.inc',
'hits' => 342,
'memory_consumption' => 9168,
'last_used' => 'Sat Mar 16 12:09:18 2013',
'last_used_timestamp' => 1363460958,
'timestamp' => 1362175205,
),
'/var/www/phpweb/index.php' =>
array (
'full_path' => '/var/www/phpweb/index.php',
'hits' => 679,
'memory_consumption' => 1840,
'last_used' => 'Sat Mar 16 12:02:49 2013',
'last_used_timestamp' => 1363460569,
'timestamp' => 1347648003,
),
),
);
}
function opcache_get_configuration() {
return array (
'directives' =>
array (
'opcache.enable' => true,
'opcache.enable_cli' => false,
'opcache.use_cwd' => true,
'opcache.validate_timestamps' => true,
'opcache.inherited_hack' => true,
'opcache.dups_fix' => false,
'opcache.revalidate_path' => false,
'opcache.log_verbosity_level' => 4,
'opcache.memory_consumption' => 16777216,
'opcache.interned_strings_buffer' => 8,
'opcache.max_accelerated_files' => 200,
'opcache.max_wasted_percentage' => 0.05,
'opcache.consistency_checks' => 0,
'opcache.force_restart_timeout' => 180,
'opcache.revalidate_freq' => 0,
'opcache.preferred_memory_model' => '',
'opcache.blacklist_filename' => '/etc/zo_blacklist.txt',
'opcache.max_file_size' => 0,
'opcache.error_log' => '',
'opcache.protect_memory' => false,
'opcache.save_comments' => true,
'opcache.load_comments' => true,
'opcache.fast_shutdown' => true,
'opcache.enable_file_override' => false,
'opcache.optimization_level' => 4294967295,
),
'version' =>
array (
'version' => '7.0.1-dev',
'opcache_product_name' => 'Zend Optimizer+',
),
'blacklist' =>
array (
0 => '/var/www/www.php.net/manual/es',
1 => '/var/www/www.php.net/manual/it',
2 => '/var/www/www.php.net/manual/bg',
3 => '/var/www/www.php.net/manual/fa',
4 => '/var/www/www.php.net/manual/fr',
5 => '/var/www/www.php.net/manual/kr',
6 => '/var/www/www.php.net/manual/pt_BR',
7 => '/var/www/www.php.net/manual/tr',
8 => '/var/www/www.php.net/manual/de',
9 => '/var/www/www.php.net/manual/ro',
10 => '/var/www/www.php.net/manual/ru',
11 => '/var/www/www.php.net/manual/zh',
12 => '/var/www/www.php.net/manual/ja',
13 => '/var/www/www.php.net/manual/pl',
14 => '/var/www/www.php.net/manual/sr',
),
);
}
@@ -0,0 +1,748 @@
<?php
/**
* Taken from https://github.com/rlerdorf/opcache-status
*/
define('THOUSAND_SEPARATOR',true);
if (!extension_loaded('Zend OPcache')) {
echo '<div style="background-color: #F2DEDE; color: #B94A48; padding: 1em;">You do not have the Zend OPcache extension loaded, sample data is being shown instead.</div>';
require 'prod_check.opcache.data_sample.inc';
}
class OpCacheDataModel
{
private $_configuration;
private $_status;
private $_d3Scripts = array();
public function __construct()
{
$this->_configuration = opcache_get_configuration();
$this->_status = opcache_get_status();
}
public function getPageTitle()
{
return 'PHP ' . phpversion() . " with OpCache {$this->_configuration['version']['version']}";
}
public function getStatusDataRows()
{
$rows = array();
foreach ($this->_status as $key => $value) {
if ($key === 'scripts') {
continue;
}
if (is_array($value)) {
foreach ($value as $k => $v) {
if ($v === false) {
$value = 'false';
}
if ($v === true) {
$value = 'true';
}
if ($k === 'used_memory' || $k === 'free_memory' || $k === 'wasted_memory') {
$v = $this->_size_for_humans(
$v
);
}
if ($k === 'current_wasted_percentage' || $k === 'opcache_hit_rate') {
$v = number_format(
$v,
2
) . '%';
}
if ($k === 'blacklist_miss_ratio') {
$v = number_format($v, 2) . '%';
}
if ($k === 'start_time' || $k === 'last_restart_time') {
$v = ($v ? date(DATE_RFC822, $v) : 'never');
}
if (THOUSAND_SEPARATOR === true && is_int($v)) {
$v = number_format($v);
}
$rows[] = "<tr><th>$k</th><td>$v</td></tr>\n";
}
continue;
}
if ($value === false) {
$value = 'false';
}
if ($value === true) {
$value = 'true';
}
$rows[] = "<tr><th>$key</th><td>$value</td></tr>\n";
}
return implode("\n", $rows);
}
public function getConfigDataRows()
{
$rows = array();
foreach ($this->_configuration['directives'] as $key => $value) {
if ($value === false) {
$value = 'false';
}
if ($value === true) {
$value = 'true';
}
if ($key == 'opcache.memory_consumption') {
$value = $this->_size_for_humans($value);
}
$rows[] = "<tr><th>$key</th><td>$value</td></tr>\n";
}
return implode("\n", $rows);
}
public function getScriptStatusRows()
{
foreach ($this->_status['scripts'] as $key => $data) {
$dirs[dirname($key)][basename($key)] = $data;
$this->_arrayPset($this->_d3Scripts, $key, array(
'name' => basename($key),
'size' => $data['memory_consumption'],
));
}
asort($dirs);
$basename = '';
while (true) {
if (count($this->_d3Scripts) !=1) break;
$basename .= DIRECTORY_SEPARATOR . key($this->_d3Scripts);
$this->_d3Scripts = reset($this->_d3Scripts);
}
$this->_d3Scripts = $this->_processPartition($this->_d3Scripts, $basename);
$id = 1;
$rows = array();
foreach ($dirs as $dir => $files) {
$count = count($files);
$file_plural = $count > 1 ? 's' : null;
$m = 0;
foreach ($files as $file => $data) {
$m += $data["memory_consumption"];
}
$m = $this->_size_for_humans($m);
if ($count > 1) {
$rows[] = '<tr>';
$rows[] = "<th class=\"clickable\" id=\"head-{$id}\" colspan=\"3\" onclick=\"toggleVisible('#head-{$id}', '#row-{$id}')\">{$dir} ({$count} file{$file_plural}, {$m})</th>";
$rows[] = '</tr>';
}
foreach ($files as $file => $data) {
$rows[] = "<tr id=\"row-{$id}\">";
$rows[] = "<td>" . $this->_format_value($data["hits"]) . "</td>";
$rows[] = "<td>" . $this->_size_for_humans($data["memory_consumption"]) . "</td>";
$rows[] = $count > 1 ? "<td>{$file}</td>" : "<td>{$dir}/{$file}</td>";
$rows[] = '</tr>';
}
++$id;
}
return implode("\n", $rows);
}
public function getScriptStatusCount()
{
return count($this->_status["scripts"]);
}
public function getGraphDataSetJson()
{
$dataset = array();
$dataset['memory'] = array(
$this->_status['memory_usage']['used_memory'],
$this->_status['memory_usage']['free_memory'],
$this->_status['memory_usage']['wasted_memory'],
);
$dataset['keys'] = array(
$this->_status['opcache_statistics']['num_cached_keys'],
$this->_status['opcache_statistics']['max_cached_keys'] - $this->_status['opcache_statistics']['num_cached_keys'],
0
);
$dataset['hits'] = array(
$this->_status['opcache_statistics']['misses'],
$this->_status['opcache_statistics']['hits'],
0,
);
$dataset['restarts'] = array(
$this->_status['opcache_statistics']['oom_restarts'],
$this->_status['opcache_statistics']['manual_restarts'],
$this->_status['opcache_statistics']['hash_restarts'],
);
if (THOUSAND_SEPARATOR === true) {
$dataset['TSEP'] = 1;
} else {
$dataset['TSEP'] = 0;
}
return json_encode($dataset);
}
public function getHumanUsedMemory()
{
return $this->_size_for_humans($this->getUsedMemory());
}
public function getHumanFreeMemory()
{
return $this->_size_for_humans($this->getFreeMemory());
}
public function getHumanWastedMemory()
{
return $this->_size_for_humans($this->getWastedMemory());
}
public function getUsedMemory()
{
return $this->_status['memory_usage']['used_memory'];
}
public function getFreeMemory()
{
return $this->_status['memory_usage']['free_memory'];
}
public function getWastedMemory()
{
return $this->_status['memory_usage']['wasted_memory'];
}
public function getWastedMemoryPercentage()
{
return number_format($this->_status['memory_usage']['current_wasted_percentage'], 2);
}
public function getD3Scripts()
{
return $this->_d3Scripts;
}
private function _processPartition($value, $name = null)
{
if (array_key_exists('size', $value)) {
return $value;
}
$array = array('name' => $name,'children' => array());
foreach ($value as $k => $v) {
$array['children'][] = $this->_processPartition($v, $k);
}
return $array;
}
private function _format_value($value)
{
if (THOUSAND_SEPARATOR === true) {
return number_format($value);
} else {
return $value;
}
}
private function _size_for_humans($bytes)
{
if ($bytes > 1048576) {
return sprintf('%.2f&nbsp;MB', $bytes / 1048576);
} else {
if ($bytes > 1024) {
return sprintf('%.2f&nbsp;kB', $bytes / 1024);
} else {
return sprintf('%d&nbsp;bytes', $bytes);
}
}
}
// Borrowed from Laravel
private function _arrayPset(&$array, $key, $value)
{
if (is_null($key)) return $array = $value;
$keys = explode(DIRECTORY_SEPARATOR, ltrim($key, DIRECTORY_SEPARATOR));
while (count($keys) > 1) {
$key = array_shift($keys);
if ( ! isset($array[$key]) || ! is_array($array[$key])) {
$array[$key] = array();
}
$array =& $array[$key];
}
$array[array_shift($keys)] = $value;
return $array;
}
}
$dataModel = new OpCacheDataModel();
?>
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<style>
body {
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
margin: 0;
padding: 0;
}
#container {
width: 1024px;
margin: auto;
position: relative;
}
h1 {
padding: 10px 0;
}
table {
border-collapse: collapse;
}
tbody tr:nth-child(even) {
background-color: #eee;
}
p.capitalize {
text-transform: capitalize;
}
.tabs {
position: relative;
float: left;
width: 60%;
}
.tab {
float: left;
}
.tab label {
background: #eee;
padding: 10px 12px;
border: 1px solid #ccc;
margin-left: -1px;
position: relative;
left: 1px;
}
.tab [type=radio] {
display: none;
}
.tab th, .tab td {
padding: 8px 12px;
}
.content {
position: absolute;
top: 28px;
left: 0;
background: white;
border: 1px solid #ccc;
height: 450px;
width: 100%;
overflow: auto;
}
.content table {
width: 100%;
}
.content th, .tab:nth-child(3) td {
text-align: left;
}
.content td {
text-align: right;
}
.clickable {
cursor: pointer;
}
[type=radio]:checked ~ label {
background: white;
border-bottom: 1px solid white;
z-index: 2;
}
[type=radio]:checked ~ label ~ .content {
z-index: 1;
}
#graph {
float: right;
width: 40%;
position: relative;
}
#graph > form {
position: absolute;
right: 60px;
top: -20px;
}
#graph > svg {
position: absolute;
top: 0;
right: 0;
}
#stats {
position: absolute;
right: 125px;
top: 145px;
}
#stats th, #stats td {
padding: 6px 10px;
font-size: 0.8em;
}
#partition {
position: absolute;
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
background: #ddd;
display: none;
}
#close-partition {
display: none;
position: absolute;
z-index: 20;
right: 15px;
top: 15px;
background: #f9373d;
color: #fff;
padding: 12px 15px;
}
#close-partition:hover {
background: #D32F33;
cursor: pointer;
}
#partition rect {
stroke: #fff;
fill: #aaa;
fill-opacity: 1;
}
#partition rect.parent {
cursor: pointer;
fill: steelblue;
}
#partition text {
pointer-events: none;
}
label {
cursor: pointer;
}
</style>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.0.1/d3.v3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var hidden = {};
function toggleVisible(head, row) {
if (!hidden[row]) {
d3.selectAll(row).transition().style('display', 'none');
hidden[row] = true;
d3.select(head).transition().style('color', '#ccc');
} else {
d3.selectAll(row).transition().style('display');
hidden[row] = false;
d3.select(head).transition().style('color', '#000');
}
}
</script>
<title><?php echo $dataModel->getPageTitle(); ?></title>
</head>
<body>
<div id="container">
<h1><?php echo $dataModel->getPageTitle(); ?></h1>
<div class="tabs">
<div class="tab">
<input type="radio" id="tab-status" name="tab-group-1" checked>
<label for="tab-status">Status</label>
<div class="content">
<table>
<?php echo $dataModel->getStatusDataRows(); ?>
</table>
</div>
</div>
<div class="tab">
<input type="radio" id="tab-config" name="tab-group-1">
<label for="tab-config">Configuration</label>
<div class="content">
<table>
<?php echo $dataModel->getConfigDataRows(); ?>
</table>
</div>
</div>
<div class="tab">
<input type="radio" id="tab-scripts" name="tab-group-1">
<label for="tab-scripts">Scripts (<?php echo $dataModel->getScriptStatusCount(); ?>)</label>
<div class="content">
<table style="font-size:0.8em;">
<tr>
<th width="10%">Hits</th>
<th width="20%">Memory</th>
<th width="70%">Path</th>
</tr>
<?php echo $dataModel->getScriptStatusRows(); ?>
</table>
</div>
</div>
<div class="tab">
<input type="radio" id="tab-visualise" name="tab-group-1">
<label for="tab-visualise">Visualise Partition</label>
<div class="content"></div>
</div>
</div>
<div id="graph">
<form>
<label><input type="radio" name="dataset" value="memory" checked> Memory</label>
<label><input type="radio" name="dataset" value="keys"> Keys</label>
<label><input type="radio" name="dataset" value="hits"> Hits</label>
<label><input type="radio" name="dataset" value="restarts"> Restarts</label>
</form>
<div id="stats"></div>
</div>
</div>
<div id="close-partition">&#10006; Close Visualisation</div>
<div id="partition"></div>
<script>
var dataset = <?php echo $dataModel->getGraphDataSetJson(); ?>;
var width = 400,
height = 400,
radius = Math.min(width, height) / 2,
colours = ['#B41F1F', '#1FB437', '#ff7f0e'];
d3.scale.customColours = function() {
return d3.scale.ordinal().range(colours);
};
var colour = d3.scale.customColours();
var pie = d3.layout.pie().sort(null);
var arc = d3.svg.arc().innerRadius(radius - 20).outerRadius(radius - 50);
var svg = d3.select("#graph").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.memory))
.enter().append("path")
.attr("fill", function(d, i) { return colour(i); })
.attr("d", arc)
.each(function(d) { this._current = d; }); // store the initial values
d3.selectAll("input").on("change", change);
set_text("memory");
function set_text(t) {
if (t === "memory") {
d3.select("#stats").html(
"<table><tr><th style='background:#B41F1F;'>Used</th><td><?php echo $dataModel->getHumanUsedMemory()?></td></tr>"+
"<tr><th style='background:#1FB437;'>Free</th><td><?php echo $dataModel->getHumanFreeMemory()?></td></tr>"+
"<tr><th style='background:#ff7f0e;' rowspan=\"2\">Wasted</th><td><?php echo $dataModel->getHumanWastedMemory()?></td></tr>"+
"<tr><td><?php echo $dataModel->getWastedMemoryPercentage()?>%</td></tr></table>"
);
} else if (t === "keys") {
d3.select("#stats").html(
"<table><tr><th style='background:#B41F1F;'>Cached keys</th><td>"+format_value(dataset[t][0])+"</td></tr>"+
"<tr><th style='background:#1FB437;'>Free Keys</th><td>"+format_value(dataset[t][1])+"</td></tr></table>"
);
} else if (t === "hits") {
d3.select("#stats").html(
"<table><tr><th style='background:#B41F1F;'>Misses</th><td>"+format_value(dataset[t][0])+"</td></tr>"+
"<tr><th style='background:#1FB437;'>Cache Hits</th><td>"+format_value(dataset[t][1])+"</td></tr></table>"
);
} else if (t === "restarts") {
d3.select("#stats").html(
"<table><tr><th style='background:#B41F1F;'>Memory</th><td>"+dataset[t][0]+"</td></tr>"+
"<tr><th style='background:#1FB437;'>Manual</th><td>"+dataset[t][1]+"</td></tr>"+
"<tr><th style='background:#ff7f0e;'>Keys</th><td>"+dataset[t][2]+"</td></tr></table>"
);
}
}
function change() {
// Filter out any zero values to see if there is anything left
var remove_zero_values = dataset[this.value].filter(function(value) {
return value > 0;
});
// Skip if the value is undefined for some reason
if (typeof dataset[this.value] !== 'undefined' && remove_zero_values.length > 0) {
$('#graph').find('> svg').show();
path = path.data(pie(dataset[this.value])); // update the data
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
// Hide the graph if we can't draw it correctly, not ideal but this works
} else {
$('#graph').find('> svg').hide();
}
set_text(this.value);
}
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
function size_for_humans(bytes) {
if (bytes > 1048576) {
return (bytes/1048576).toFixed(2) + ' MB';
} else if (bytes > 1024) {
return (bytes/1024).toFixed(2) + ' KB';
} else return bytes + ' bytes';
}
function format_value(value) {
if (dataset["TSEP"] == 1) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return value;
}
}
var w = window.innerWidth,
h = window.innerHeight,
x = d3.scale.linear().range([0, w]),
y = d3.scale.linear().range([0, h]);
var vis = d3.select("#partition")
.style("width", w + "px")
.style("height", h + "px")
.append("svg:svg")
.attr("width", w)
.attr("height", h);
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
root = JSON.parse('<?php echo json_encode($dataModel->getD3Scripts()); ?>');
var g = vis.selectAll("g")
.data(partition.nodes(root))
.enter().append("svg:g")
.attr("transform", function(d) { return "translate(" + x(d.y) + "," + y(d.x) + ")"; })
.on("click", click);
var kx = w / root.dx,
ky = h / 1;
g.append("svg:rect")
.attr("width", root.dy * kx)
.attr("height", function(d) { return d.dx * ky; })
.attr("class", function(d) { return d.children ? "parent" : "child"; });
g.append("svg:text")
.attr("transform", transform)
.attr("dy", ".35em")
.style("opacity", function(d) { return d.dx * ky > 12 ? 1 : 0; })
.text(function(d) { return d.name; })
d3.select(window)
.on("click", function() { click(root); })
function click(d) {
if (!d.children) return;
kx = (d.y ? w - 40 : w) / (1 - d.y);
ky = h / d.dx;
x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
y.domain([d.x, d.x + d.dx]);
var t = g.transition()
.duration(d3.event.altKey ? 7500 : 750)
.attr("transform", function(d) { return "translate(" + x(d.y) + "," + y(d.x) + ")"; });
t.select("rect")
.attr("width", d.dy * kx)
.attr("height", function(d) { return d.dx * ky; });
t.select("text")
.attr("transform", transform)
.style("opacity", function(d) { return d.dx * ky > 12 ? 1 : 0; });
d3.event.stopPropagation();
}
function transform(d) {
return "translate(8," + d.dx * ky / 2 + ")";
}
$(document).ready(function() {
function handleVisualisationToggle(close) {
$('#partition, #close-partition').fadeToggle();
// Is the visualisation being closed? If so show the status tab again
if (close) {
$('#tab-visualise').removeAttr('checked');
$('#tab-status').trigger('click');
}
}
$('label[for="tab-visualise"], #close-partition').on('click', function() {
handleVisualisationToggle(($(this).attr('id') === 'close-partition'));
});
$(document).keyup(function(e) {
if (e.keyCode == 27) handleVisualisationToggle(true);
});
});
</script>
</body>
</html>
@@ -71,7 +71,7 @@ function my_module_additional_check($caller = 'internal') {
$title = 'My modules settings';
$setting1 = t('Enable debug info');
$setting2 = t('Disable debug info');
$path = 'admin/settings/my-module-settings-page';
$path = 'admin/config/system/my-module-settings-page';
if ($caller != 'internal') {
$path = PRODCHECK_BASEURL . $path;
}
@@ -85,7 +85,7 @@ function my_module_additional_check($caller = 'internal') {
'#description_ok' => prod_check_ok_title($title, $path),
'#description_nok' => t('Your !link settings are set to %setting1, they should be set to %setting2 on a producion environment!',
array(
'!link' => '<em>'.l(t($title), $path, array('attributes' => array('title' => t($title)))).'</em>',
'!link' => '<em>' . l(t($title), $path, array('attributes' => array('title' => t($title)))) . '</em>',
'%setting1' => $setting1,
'%setting2' => $setting2,
)
@@ -0,0 +1,91 @@
<?php
/**
* @file
* Simple database connection check that can be placed anywhere within a Drupal
* installation. Does NOT need to be in the root where index.php resides!
*/
/**
* Locate the actual Drupal root. Based on drush_locate_root().
*/
function locate_root() {
$drupal_root = FALSE;
$start_path = isset($_SERVER['PWD']) ? $_SERVER['PWD'] : '';
if (empty($start_path)) {
$start_path = getcwd();
}
foreach (array(TRUE, FALSE) as $follow_symlinks) {
$path = $start_path;
if ($follow_symlinks && is_link($path)) {
$path = realpath($path);
}
// Check the start path.
if (valid_root($path)) {
$drupal_root = $path;
break;
}
else {
// Move up dir by dir and check each.
while ($path = shift_path_up($path)) {
if ($follow_symlinks && is_link($path)) {
$path = realpath($path);
}
if (valid_root($path)) {
$drupal_root = $path;
break 2;
}
}
}
}
return $drupal_root;
}
/**
* Based on the DrupalBoot*::valid_root() from Drush.
*/
function valid_root($path) {
if (!empty($path) && is_dir($path) && file_exists($path . '/index.php')) {
$candidate = 'includes/common.inc';
if (file_exists($path . '/' . $candidate) && file_exists($path . '/misc/drupal.js')) {
return TRUE;
}
}
return FALSE;
}
/**
* Based on _drush_shift_path_up().
*/
function shift_path_up($path) {
if (empty($path)) {
return FALSE;
}
$path = explode('/', $path);
// Move one directory up.
array_pop($path);
return implode('/', $path);
}
/**
* Do the actual database connection check.
*/
define('DRUPAL_ROOT', locate_root());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
$result = db_query('SELECT COUNT(filename) FROM {system}')->fetchField();
if ($result) {
$msg = 'OK';
http_response_code(200);
}
else {
http_response_code(500);
$msg = 'NOK';
}
exit($msg);
@@ -44,14 +44,14 @@ function drush_prod_check_status() {
foreach ($functions as $set => $data) {
$rows[] = array('');
$rows[] = array("\033[1m".dt($data['title'])."\033[0m");
$rows[] = array("\033[1m" . dt($data['title'])."\033[0m");
foreach ($data['functions'] as $function => $title) {
$result = call_user_func($function);
$func = ltrim($function, '_');
if (is_array($result) && !empty($result)) {
$rows[] = array(
$result[$func]['title'],
"\033[".$severity[$result[$func]['severity']].'m'.strip_tags($result[$func]['value'])."\033[0m",
"\033[" . $severity[$result[$func]['severity']] . 'm' . strip_tags($result[$func]['value']) . "\033[0m",
);
if ($error < $result[$func]['severity']) {
$error = $result[$func]['severity'];
@@ -59,12 +59,12 @@ function drush_prod_check_status() {
}
}
}
drush_print("\033[1m".dt('Production Check status')."\033[0m", 1);
drush_print("\033[1m" . dt('Production Check status')."\033[0m", 1);
drush_print_table($rows);
if ($error > 0) {
// Would be cool if we could prefix the admin path with http://<host>/ so it
// will become a clickable link in some terminals. Any ideas?
drush_print("\033[1m".dt('Some errors were reported!')."\033[0m ".dt('Check the full status page on')." \033[1m".'admin/reports/prod-check'."\033[0m ".dt('for details.'));
drush_print("\033[1m" . dt('Some errors were reported!') . "\033[0m " . dt('Check the full status page on') . " \033[1m" . 'admin/reports/prod-check' . "\033[0m " . dt('for details.'));
}
}
@@ -4,9 +4,9 @@ package = Monitoring
core = 7.x
configure = admin/config/system/prod-check
; Information added by packaging script on 2013-11-25
version = "7.x-1.8"
; Information added by Drupal.org packaging script on 2015-08-04
version = "7.x-1.9"
core = "7.x"
project = "prod_check"
datestamp = "1385405033"
datestamp = "1438700931"
@@ -31,15 +31,15 @@ function prod_check_requirements($phase) {
'title' => t('Production check'),
'value' => t('Site e-mail check not properly configured.'),
'severity' => REQUIREMENT_WARNING,
'description' => t('You have not changed the e-mail address on the prod-check !link. The Site e-mail check will not function properly. Please read the README.txt file.', prod_check_link_array('settings page', 'admin/settings/prod-check')),
'description' => t('You have not changed the e-mail address on the prod-check !link. The Site e-mail check will not function properly. Please read the README.txt file.', prod_check_link_array('settings page', 'admin/config/system/prod-check')),
);
}
if (function_exists('apc_cache_info') && variable_get('prod_check_apcpass', 'password') == 'password') {
$requirements['prod_check_apc'] = array(
$requirements['prod_check_apc_opc'] = array(
'title' => t('Production check'),
'value' => t('APC password not configured.'),
'severity' => REQUIREMENT_WARNING,
'description' => t('You have not !link for the APC status page. The page will function, but advanced options require that you set a password. Please read the README.txt file.', prod_check_link_array('changed the password', 'admin/settings/prod-check')),
'description' => t('You have not !link for the APC status page. The page will function, but advanced options require that you set a password. Please read the README.txt file.', prod_check_link_array('changed the password', 'admin/config/system/prod-check')),
);
}
$nagios = variable_get('prod_check_enable_nagios', 0);
@@ -28,7 +28,7 @@ $protocol = 'http://';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$protocol = 'https://';
}
define('PRODCHECK_BASEURL', $protocol.$_SERVER['HTTP_HOST'].'/');
define('PRODCHECK_BASEURL', $protocol . $_SERVER['HTTP_HOST'] . '/');
/**
* Implementation of hook_help().
@@ -37,27 +37,27 @@ function prod_check_help($path, $arg) {
$output = '';
switch ($path) {
case 'admin/help#prod_check':
$output .= '<p>'.t('Production check is a module that will add a report detailing the status of several settings and modules. The report is tailored for a <strong>production environment</strong>. It will tell you which modules should (not) be running, what settings are OK or not and much more. It is an easy way to have an overview of the status of your site when bringing it live, so that you can quickly put all the configuration details in order to be ready for production use.').'</p>';
$output .= '<p>'.t('Using the settings page, you can enable <strong>XMLRPC support</strong> so that it can report back to the <strong>Production monitor</strong> module, available as an extra module in this package. If you install the <em>Production monitor</em> module on a central site, you can monitor several sites in a glance, ensuring that no one changes settings without you knowing about it. See the <em>Production monitor</em> built in help for more information.').'</p>';
$output .= '<p>'.t('If you prefer using <strong>!link</strong> for monitoring, you can simply enable support for that on the settings page by ticking the appropriate checkmark. An extra set of checkboxes will appear, allowing you to configure in detail what exactly you wish !link to monitor.', prod_check_link_array('Nagios', 'http://drupal.org/project/nagios')).'</p>';
$output .= '<p>' . t('Production check is a module that will add a report detailing the status of several settings and modules. The report is tailored for a <strong>production environment</strong>. It will tell you which modules should (not) be running, what settings are OK or not and much more. It is an easy way to have an overview of the status of your site when bringing it live, so that you can quickly put all the configuration details in order to be ready for production use.') . '</p>';
$output .= '<p>' . t('Using the settings page, you can enable <strong>XMLRPC support</strong> so that it can report back to the <strong>Production monitor</strong> module, available as an extra module in this package. If you install the <em>Production monitor</em> module on a central site, you can monitor several sites in a glance, ensuring that no one changes settings without you knowing about it. See the <em>Production monitor</em> built in help for more information.') . '</p>';
$output .= '<p>' . t('If you prefer using <strong>!link</strong> for monitoring, you can simply enable support for that on the settings page by ticking the appropriate checkmark. An extra set of checkboxes will appear, allowing you to configure in detail what exactly you wish !link to monitor.', prod_check_link_array('Nagios', 'http://drupal.org/project/nagios')) . '</p>';
break;
case 'admin/reports/prod-check':
case 'admin/reports/prod-check/status':
$output .= '<p>'.t('This is an overview of all checks performed by the <em>Production check</em> module and their status. You can click the links inside the report to jump to the module\'s settings page, or to go to the project page of a module, in case you need to download it for installation.').'</p>';
$output .= '<p>' . t("This is an overview of all checks performed by the <em>Production check</em> module and their status. You can click the links inside the report to jump to the module's settings page, or to go to the project page of a module, in case you need to download it for installation.") . '</p>';
break;
case 'admin/config/system/prod-check':
$output .= '<p><strong>'.t('Sitemail check').'</strong><br />';
$output .= t('The value entered here is used in a regular expression. Prod check will use it to see if the e-mail address you have entered in <em>Site information</em> is no longer a development e-mail address.').'</p>';
$output .= '<p><strong>'.t('Advanced APC settings').'</strong><br />';
$output .= t('Production check enables a <em>hidden</em> path where you can review your APC setup. This is absolutely unmissable if you want to properly setup APC and tune it specifically for your website.').'</p>';
$output .= '<p><strong>'.t('Enable XMLRPC API').'</strong><br />';
$output .= t('By ticking this box, you open up the module\'s XMLRPC functions so they can be called by the <strong>Production monitor</strong> module for remote monitoring of your site. When enabling XMLRPC, you <strong>must</strong> enter an <strong>API key</strong> to secure the transfer of data. It\'s limited to 128 characters. A mixture of alphanumeric and special characters will increase security.').'</p>';
$output .= '<p><strong>'.t('Report module list every <em>x</em> at time <em>y</em>').'</strong><br />';
$output .= t('Select on which day of the week and at what time <em>Production check</em> is allowed to pass the module list of the site it is on to <em>Production monitor</em>. Set this carefully, as the amount data being transfered is quite big!').'<br />';
$output .= t('Depending on when the cron is run on the <em>Production monitor</em> site, the module list will be reported on or maybe even several hours(!) after the time given here!').'</p>';
$output .= '<p><strong>'.t('Enable Nagios integration').'</strong><br />';
$output .= t('By ticking this box, you open up the module\'s Nagios hooks, so that it can interface with the !link module. You will obviously need to install this module next to <em>Production check</em> to enable this functionality.', prod_check_link_array('Nagios', 'http://drupal.org/project/nagios')).'<br />';
$output .= t('When the checkbox is enabled, a new array of checkboxes will appear, allowing you to specify in detail what will be reported to !link.', prod_check_link_array('Nagios', 'http://drupal.org/project/nagios')).'</p>';
$output .= '<p><strong>' . t('Sitemail check') . '</strong><br />';
$output .= t('The value entered here is used in a regular expression. Prod check will use it to see if the e-mail address you have entered in <em>Site information</em> is no longer a development e-mail address.') . '</p>';
$output .= '<p><strong>' . t('Advanced APC/OPcache settings') . '</strong><br />';
$output .= t('Production check enables a <em>hidden</em> path where you can review your APC setup. This is absolutely unmissable if you want to properly setup APC and tune it specifically for your website.') . '</p>';
$output .= '<p><strong>' . t('Enable XMLRPC API') . '</strong><br />';
$output .= t("By ticking this box, you open up the module's XMLRPC functions so they can be called by the <strong>Production monitor</strong> module for remote monitoring of your site. When enabling XMLRPC, you <strong>must</strong> enter an <strong>API key</strong> to secure the transfer of data. It's limited to 128 characters. A mixture of alphanumeric and special characters will increase security.") . '</p>';
$output .= '<p><strong>' . t('Report module list every <em>x</em> at time <em>y</em>') . '</strong><br />';
$output .= t('Select on which day of the week and at what time <em>Production check</em> is allowed to pass the module list of the site it is on to <em>Production monitor</em>. Set this carefully, as the amount data being transfered is quite big!') . '<br />';
$output .= t('Depending on when the cron is run on the <em>Production monitor</em> site, the module list will be reported on or maybe even several hours(!) after the time given here!') . '</p>';
$output .= '<p><strong>' . t('Enable Nagios integration') . '</strong><br />';
$output .= t("By ticking this box, you open up the module's Nagios hooks, so that it can interface with the !link module. You will obviously need to install this module next to <em>Production check</em> to enable this functionality.", prod_check_link_array('Nagios', 'http://drupal.org/project/nagios')) . '<br />';
$output .= t('When the checkbox is enabled, a new array of checkboxes will appear, allowing you to specify in detail what will be reported to !link.', prod_check_link_array('Nagios', 'http://drupal.org/project/nagios')) . '</p>';
break;
}
return $output;
@@ -140,9 +140,9 @@ function prod_check_menu() {
'page callback' => 'prod_check_dbstatus',
) + $admin_defaults;
$items['admin/reports/status/apc'] = array(
'title' => 'APC',
'page callback' => 'prod_check_apc',
$items['admin/reports/status/apc-opc'] = array(
'title' => 'APC/OPcache',
'page callback' => 'prod_check_apc_opc',
'access callback' => 'user_access',
) + $admin_defaults;
@@ -263,7 +263,7 @@ function prod_check_xmlrpc() {
'prod_check.get_settings',
'prod_check_get_settings',
array('struct', 'string'),
t('Returns a struct containing a form to be displayed on the prod_monitor module\'s settings page for site specific configuration.')
t("Returns a struct containing a form to be displayed on the prod_monitor module's settings page for site specific configuration.")
),
array(
'prod_check.get_data',
@@ -431,9 +431,9 @@ function prod_check_nagios() {
if (!$value['count']) {
continue;
}
$message .= '@'.strtolower($state).' '.$state;
$message .= '@' . strtolower($state) . ' ' . $state;
if(isset($nagios[$state]['items'])) {
$message .= ': '.implode('|', $nagios[$state]['items']);
$message .= ': ' . implode('|', $nagios[$state]['items']);
}
$message .= ', ';
}
@@ -521,7 +521,7 @@ function prod_check_execute_check($checks, $caller, $compatibility = 'all') {
}
}
// Special stuff here, only compatible with prod_monitor!
else if (is_array($checks) && $compatibility == 'prod_mon') {
elseif (is_array($checks) && $compatibility == 'prod_mon') {
$result = $checks;
}
@@ -532,7 +532,7 @@ function prod_check_execute_check($checks, $caller, $compatibility = 'all') {
* Helper function to generate generic 'settings OK' description.
*/
function prod_check_ok_title($title, $path, $text = 'Your !link settings are OK for production use.') {
return t($text, array('!link' => '<em>'.l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())).'</em>'));
return t($text, array('!link' => '<em>' . l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())) . '</em>'));
}
/**
@@ -550,7 +550,7 @@ function prod_check_link_array($title, $path, $fragment=NULL) {
if ($fragment) {
$options['fragment'] = $fragment;
}
return array('!link' => '<em>'.l(t($title), $path, $options).'</em>');
return array('!link' => '<em>' . l(t($title), $path, $options) . '</em>');
}
// --- All check functions follow here ---
@@ -582,7 +582,7 @@ function _prod_check_functions() {
'title' => 'Server',
'description' => 'Checks certain server side parameters such as APC.',
'functions' => array(
'_prod_check_apc' => 'APC',
'_prod_check_apc_opc' => 'APC/OPcache',
'_prod_check_dblog_php' => 'PHP errors',
'_prod_check_release_notes' => 'Release notes',
),
@@ -617,13 +617,14 @@ function _prod_check_functions() {
// Modules
$functions['modules'] = array(
'title' => 'Modules',
'description' => 'Checks if certain modules are on or off and if they\'re properly configured.',
'description' => "Checks if certain modules are on or off and if they're properly configured.",
'functions' => array(
'_prod_check_contact' => 'Contact',
'_prod_check_devel' => 'Devel',
'_prod_check_search_config' => 'Search config',
'_prod_check_update_status' => 'Update status',
'_prod_check_webform' => 'Webform',
'_prod_check_mimemail' => 'Mimemail',
'_prod_check_missing_module_files' => 'Active modules',
),
);
@@ -688,7 +689,7 @@ function _prod_check_error_reporting($caller = 'internal') {
'#description_ok' => prod_check_ok_title($title, $path),
'#description_nok' => t('Your !link settings are set to %setting1, they should be set to %setting2 on a producion environment!',
array(
'!link' => '<em>'.l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())).'</em>',
'!link' => '<em>' . l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())) . '</em>',
'%setting1' => $setting[$current],
'%setting2' => $setting[ERROR_REPORTING_HIDE],
)
@@ -723,7 +724,7 @@ function _prod_check_user_register($caller = 'internal') {
'#description_ok' => prod_check_ok_title($title, $path),
'#description_nok' => t('Your !link settings are set to %setting1. Are you sure this is what you want and did not mean to use %setting2? With improperly setup access rights, this can be dangerous...',
array(
'!link' => '<em>'.l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())).'</em>',
'!link' => '<em>' . l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())) . '</em>',
'%setting1' => $setting[$current],
'%setting2' => $setting[USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL],
)
@@ -811,30 +812,50 @@ function _prod_check_poormanscron($caller = 'internal') {
// --- SERVER ---
// APC check
function _prod_check_apc($caller = 'internal') {
function _prod_check_apc_opc($caller = 'internal') {
$check = array();
$desc_ok = $desc_nok = '';
$title = 'APC';
$path = 'admin/reports/status/apc';
$title = 'APC/OPcache';
$path = 'admin/reports/status/apc-opc';
if ($caller != 'internal') {
$path = PRODCHECK_BASEURL . $path;
}
if (!function_exists('apc_cache_info')) {
$cache = array();
if (!function_exists('apc_cache_info') && !function_exists('opcache_get_status')) {
$desc_nok = t('!link does not appear to be running.', prod_check_link_array($title, $path));
$val_nok = t('Disabled');
$error = TRUE;
}
else if ($cache = @apc_cache_info('opcode')) {
elseif (function_exists('apc_cache_info')) {
$cache = @apc_cache_info('opcode');
}
elseif (function_exists('opcache_get_status')) {
$opc_cache = @opcache_get_status();
if ($opc_cache && $opc_cache['opcache_enabled']) {
$cache['num_hits'] = $opc_cache['opcache_statistics']['hits'];
$cache['num_misses'] = $opc_cache['opcache_statistics']['misses'];
// TODO: Should we make the sum of these two or check separately?
$cache['expunges'] = $opc_cache['opcache_statistics']['oom_restarts'] + $opc_cache['opcache_statistics']['hash_restarts'];
}
else {
$desc_nok = t('!link does not appear to be running.', prod_check_link_array($title, $path));
$val_nok = t('Disabled');
$error = TRUE;
}
}
if (!empty($cache)) {
$apc_expunge = variable_get('prod_check_apc_expunge', 0);
$detailed_info = ': '.t('hits').': '.$cache['num_hits'].', '.t('misses').': '.$cache['num_misses'].', '.t('cache full count').': '.$cache['expunges'].'.';
$detailed_info = ': ' . t('hits') . ': ' . $cache['num_hits'] . ', ' . t('misses') . ': ' . $cache['num_misses'] . ', ' . t('cache full count') . ': ' . $cache['expunges'] . '.';
if ($cache['num_misses'] >= $cache['num_hits']) {
$desc_nok = t('!link not properly configured, too many misses', prod_check_link_array($title, $path)) . $detailed_info;
$val_nok = t('Not functioning properly.');
$error = TRUE;
}
else if ($cache['expunges'] > $apc_expunge) {
elseif ($cache['expunges'] > $apc_expunge) {
$desc_nok = t('!link not properly configured, cache size too small', prod_check_link_array($title, $path)) . $detailed_info;
$val_nok = t('Not functioning properly.');
$error = TRUE;
@@ -851,7 +872,7 @@ function _prod_check_apc($caller = 'internal') {
$error = TRUE;
}
$check['prod_check_apc'] = array(
$check['prod_check_apc_opc'] = array(
'#title' => t($title),
'#state' => !$error,
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_CRITICAL : PROD_CHECK_REQUIREMENT_ERROR,
@@ -997,9 +1018,9 @@ function _prod_check_page_cache($caller = 'internal') {
'#description_ok' => prod_check_ok_title($title, $path),
'#description_nok' => t('Your !link settings are disabled. You should at least set page caching to "Cache pages for anonymous users" on a production site! You should also consider using the !boost module or a more powerful system like !varnish!',
array(
'!link' => '<em>'.l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())).'</em>',
'!boost' => '<em>'.l(t('Boost'), 'http://drupal.org/project/boost', array('attributes' => array('title' => t('Boost')))).'</em>',
'!varnish' => '<em>'.l(t('Varnish'), 'http://drupal.org/project/steroids', array('attributes' => array('title' => t('Varnish')))).'</em>',
'!link' => '<em>' . l(t($title), $path, array('attributes' => array('title' => t($title)), 'query' => drupal_get_destination())) . '</em>',
'!boost' => '<em>' . l(t('Boost'), 'http://drupal.org/project/boost', array('attributes' => array('title' => t('Boost')))) . '</em>',
'!varnish' => '<em>' . l(t('Varnish'), 'http://drupal.org/project/steroids', array('attributes' => array('title' => t('Varnish')))) . '</em>',
)
),
'#nagios_key' => 'PCACHE',
@@ -1068,7 +1089,7 @@ function _prod_check_boost($caller = 'internal') {
$subtitle = 'text/html - Maximum Cache Lifetime';
$var = variable_get('boost_lifetime_max_text/html', 3600);
$check['prod_check_boost_cache_lifetime'] = array(
'#title' => t($title.$subtitle),
'#title' => t($title . $subtitle),
'#state' => $var <= 3600,
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_WARNING : PROD_CHECK_REQUIREMENT_WARNING,
'#value_ok' => t('Set to !seconds seconds.', array('!seconds' => $var)),
@@ -1083,7 +1104,7 @@ function _prod_check_boost($caller = 'internal') {
$subtitle = 'Remove old cache files on cron';
$var = variable_get('boost_expire_cron', BOOST_EXPIRE_CRON);
$check['prod_check_boost_expire_cron'] = array(
'#title' => t($title.$subtitle),
'#title' => t($title . $subtitle),
'#state' => $var,
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_WARNING : PROD_CHECK_REQUIREMENT_WARNING,
'#value_ok' => t('Enabled'),
@@ -1098,7 +1119,7 @@ function _prod_check_boost($caller = 'internal') {
$subtitle = 'Crawl on cron';
$var = module_exists('boost_crawler') && variable_get('boost_crawl_on_cron', FALSE);
$check['prod_check_boost_crawl_on_cron'] = array(
'#title' => t($title.$subtitle),
'#title' => t($title . $subtitle),
'#state' => $var,
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_WARNING : PROD_CHECK_REQUIREMENT_WARNING,
'#value_ok' => t('Enabled'),
@@ -1127,13 +1148,13 @@ function _prod_check_boost($caller = 'internal') {
}
$check['prod_check_boost_apache_nagios_page'] = array(
'#title' => t($title.$subtitle),
'#title' => t($title . $subtitle),
'#state' => !$var,
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_WARNING : PROD_CHECK_REQUIREMENT_WARNING,
'#value_ok' => t('Enabled'),
'#value_nok' => t('Not properly configured.'),
'#description_ok' => prod_check_ok_title($subtitle, $path),
'#description_nok' => t('The !link is being cached by Boost. '.$advise, prod_check_link_array($subtitle, $path)),
'#description_nok' => t('The !link is being cached by Boost. ' . $advise, prod_check_link_array($subtitle, $path)),
'#nagios_key' => 'BNAPA',
'#nagios_type' => 'state',
);
@@ -1143,7 +1164,7 @@ function _prod_check_boost($caller = 'internal') {
$subtitle = 'ETag';
$var = variable_get('boost_apache_etag', BOOST_APACHE_ETAG);
$check['prod_check_boost_apache_etag'] = array(
'#title' => t($title.$subtitle),
'#title' => t($title . $subtitle),
'#state' => $var >= 2,
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_WARNING : PROD_CHECK_REQUIREMENT_WARNING,
'#value_ok' => t('Enabled'),
@@ -1151,9 +1172,9 @@ function _prod_check_boost($caller = 'internal') {
'#description_ok' => prod_check_ok_title($subtitle, $path_htaccess),
'#description_nok' => t('Your !link settings are not ok! You should enable entity tags (!etag) in Boost so that user side caching and bandwith usage will be optimal! You do need to enable !mod for this to work.',
array(
'!link' => '<em>'.l(t($subtitle), $path_htaccess, array('attributes' => array('title' => t($subtitle)), 'query' => drupal_get_destination())).'</em>',
'!etag' => '<em>'.l(t('ETags'), 'http://en.wikipedia.org/wiki/HTTP_ETag', array('attributes' => array('title' => t('Etags')))).'</em>',
'!mod' => '<em>'.l(t('mod_headers'), 'http://httpd.apache.org/docs/2.0/mod/mod_headers.html', array('attributes' => array('title' => t('mod_headers')))).'</em>',
'!link' => '<em>' . l(t($subtitle), $path_htaccess, array('attributes' => array('title' => t($subtitle)), 'query' => drupal_get_destination())) . '</em>',
'!etag' => '<em>' . l(t('ETags'), 'http://en.wikipedia.org/wiki/HTTP_ETag', array('attributes' => array('title' => t('Etags')))) . '</em>',
'!mod' => '<em>' . l(t('mod_headers'), 'http://httpd.apache.org/docs/2.0/mod/mod_headers.html', array('attributes' => array('title' => t('mod_headers')))) . '</em>',
)
),
'#nagios_key' => 'BETAG',
@@ -1320,7 +1341,7 @@ function _prod_check_user_pass($caller = 'internal') {
// Be sure to omit the anonymous user with id 0.
$result = db_query('SELECT uid, name FROM {users} WHERE uid <> 0 AND status = 1 AND MD5(name) = pass');
foreach ($result as $row) {
$list .= l($row['name'], $path.'user/'.$row['uid'].'/edit', array('attributes' => array('title' => t('Edit user').' '.$row['name']), 'query' => drupal_get_destination())).', ';
$list .= l($row['name'], $path . 'user/' . $row['uid'] . '/edit', array('attributes' => array('title' => t('Edit user') . ' ' . $row['name']), 'query' => drupal_get_destination())) . ', ';
}
if (!empty($list)) {
$secure = FALSE;
@@ -1334,7 +1355,7 @@ function _prod_check_user_pass($caller = 'internal') {
'#value_ok' => t('Secure'),
'#value_nok' => t('Security risk!'),
'#description_ok' => t('No security risk found.'),
'#description_nok' => t('Some users have a password that is identical to their username! You should check the following users:' .' '.$list.'.'),
'#description_nok' => t('Some users have a password that is identical to their username! You should check the following users:' . ' ' . $list . '.'),
'#nagios_key' => 'USRBD',
'#nagios_type' => 'state',
);
@@ -1511,7 +1532,7 @@ function _prod_check_devel($caller = 'internal') {
$path = PRODCHECK_BASEURL . $path;
}
$checks['prod_check_'.$data['name']] = array(
$checks['prod_check_' . $data['name']] = array(
'#title' => t($title),
'#state' => !$data['error'],
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_CRITICAL : PROD_CHECK_REQUIREMENT_ERROR,
@@ -1646,6 +1667,37 @@ function _prod_check_webform($caller = 'internal') {
return prod_check_execute_check($check, $caller);
}
// Mimemail
function _prod_check_mimemail($caller = 'internal') {
if (!module_exists('mimemail')) {
return;
}
$check = array();
$title = 'Mimemail';
$path = 'admin/config/system/mimemail';
if ($caller != 'internal') {
$path = PRODCHECK_BASEURL . $path;
}
$mimemail_mail = variable_get('mimemail_mail', variable_get('site_mail', ini_get('sendmail_from')));
$arguments = array('!mimemail' => $title, '%mail' => $mimemail_mail);
$check['prod_check_mimemail'] = array(
'#title' => t($title),
'#state' => $mimemail_mail != '' && !preg_match('/' . preg_quote(variable_get('prod_check_sitemail', '')) . '/i', $mimemail_mail),
'#severity' => ($caller == 'nagios') ? NAGIOS_STATUS_CRITICAL : PROD_CHECK_REQUIREMENT_ERROR,
'#value_ok' => t('!mimemail default sender e-mail address OK: %mail', $arguments),
'#value_nok' => t('!mimemail default sender e-mail address set to %mail', $arguments),
'#description_ok' => prod_check_ok_title($title, $path),
'#description_nok' => t('The !link default from e-mail address should not be a development address on production sites!', prod_check_link_array($title, $path)),
'#nagios_key' => 'MIML',
'#nagios_type' => 'state',
);
return prod_check_execute_check($check, $caller);
}
// Active modules
function _prod_check_missing_module_files($caller = 'internal') {
$missing = $total = 0;
@@ -1707,7 +1759,7 @@ function _prod_check_googleanalytics($caller = 'internal') {
$value_nok = t('Disabled');
$msg_nok = t('You have not enabled the !link module. If you wish to track and optimise your site !link is absolutely necessary.', prod_check_link_array($title, 'http://drupal.org/project/google_analytics'));
}
else if (empty($ga_account) || $ga_account == 'UA-') {
elseif (empty($ga_account) || $ga_account == 'UA-') {
$error = TRUE;
$severity = ($caller == 'nagios') ? NAGIOS_STATUS_CRITICAL : PROD_CHECK_REQUIREMENT_ERROR;
$value_nok = t('Not properly configured.');
@@ -1757,6 +1809,10 @@ function _prod_check_metatag($caller = 'internal') {
}
function _prod_check_page_title($caller = 'internal') {
if (module_exists('metatag')) {
return;
}
$check = array();
$error = FALSE;
$pager = variable_get('page_title_pager_pattern', '');
@@ -1773,9 +1829,9 @@ function _prod_check_page_title($caller = 'internal') {
if (!module_exists('page_title')) {
$error = TRUE;
$value_nok = t('Disabled');
$msg_nok = t('You have not enabled the !link module. This module can help out with problems such as pages with paging being marked as duplicate content by search engines.', prod_check_link_array($title, 'http://drupal.org/project/page_title'));
$msg_nok = t('You have not enabled the !link (or equivalent) module. This module can help out with problems such as pages with paging being marked as duplicate content by search engines.', prod_check_link_array($title, 'http://drupal.org/project/page_title'));
}
else if (empty($pager)) {
elseif (empty($pager)) {
$error = TRUE;
$value_nok = t('Not properly configured.');
$msg_nok = t('You have not !link You should really do this if you want proper Google Indexing.', prod_check_link_array('set a pager suffix', $path));
@@ -4,8 +4,15 @@
* Build status page.
*/
function prod_monitor_status($id) {
$site = _prod_monitor_get_site($id, TRUE);
drupal_set_title(t('Production monitor status for') .' '. _prod_monitor_sanitize_url($site['url']));
$site = _prod_monitor_get_site($id, 'all');
if (!$site) {
// See https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_not_found/7
return MENU_NOT_FOUND;
}
drupal_set_title(t('Production monitor status for') . ' ' . _prod_monitor_sanitize_url($site['url']));
$functions = $site['settings']['functions'];
$nodata = t('No data recieved yet.');
@@ -25,24 +32,25 @@ function prod_monitor_status($id) {
// Display results of all checks.
foreach ($functions as $set => $data) {
if (isset($site['data'][$set])) {
$output .= '<h2>'.t($data['title']).'</h2>'."\n";
$output .= '<div class="description"><p><em>'.t($data['description']).'</em></p></div>'."\n";
$output .= '<h2>' . t($data['title']) . '</h2>' . "\n";
$output .= '<div class="description"><p><em>' . t($data['description']) . '</em></p></div>'."\n";
if (!empty($site['data'][$set])) {
$output .= theme('prod_monitor_status_report', array('requirements' => $site['data'][$set]));
}
else {
$output .= '<p>'.$nodata.'</p><p>&nbsp;</p>';
$output .= '<p>' . $nodata . '</p><p>&nbsp;</p>';
}
}
}
if (empty($output)) {
$output = '<p>'.$nodata.'</p><p>&nbsp;</p>';
$output = '<p>' . $nodata . '</p><p>&nbsp;</p>';
}
// TODO: do not use drupal_render but change this so that hook_page_alter can
// be used as well.
$output .= drupal_render(drupal_get_form('_prod_monitor_update_data_form', $id, $site));
$form = drupal_get_form('_prod_monitor_update_data_form', $id, $site);
$output .= drupal_render($form);
return $output;
}
@@ -51,30 +59,54 @@ function prod_monitor_status($id) {
* Helper function to provide general status block on status overview page
*/
function _prod_monitor_status_general($prod_mon, $modules) {
// TODO: Should we hide the rows for which no data is being retrieved?
$cron = t('Unknown');
if (isset($prod_mon['prod_check_cron_last'])) {
$cron = format_date($prod_mon['prod_check_cron_last'], 'large');
}
$updates = _prod_monitor_generate_updates_link($modules['id'], $modules['updates']);
$output = '<h2>'.t('Overall status').'</h2>'."\n";
$output = '<h2>' . t('Overall status') . '</h2>' . "\n";
$rows = array(
array(
array('data' => t('Drupal core version'), 'header' => TRUE),
$modules['projects']['drupal']['info']['version'],
),
array(
array('data' => t('Last cron run'), 'header' => TRUE),
$cron,
),
array(
array('data' => t('Update status'), 'header' => TRUE),
$updates,
),
);
$output .= theme('table', array('header' => array(), 'rows' => $rows));
if (isset($prod_mon['prod_check_cron_last'])) {
$rows[] = array(
array('data' => t('Last cron run'), 'header' => TRUE),
format_date($prod_mon['prod_check_cron_last'], 'large'),
);
}
// Add dbconnect check info if configured.
if (isset($prod_mon['prod_check_dbconnect'])) {
$dbconnect = $prod_mon['prod_check_dbconnect'];
$class = array();
$title = t('DB connection status');
if (stripos($dbconnect, '200') === FALSE) {
$class = array('error');
$title = '<strong>' . $title . '</strong>';
$dbconnect = '<strong>' . $dbconnect . '</strong>';
}
$rows[] = array(
'data' => array(
array(
'data' => $title, 'header' => TRUE,
'class' => $class,
),
array(
'data' => $dbconnect,
'class' => $class,
),
),
'class' => $class,
);
}
$rows[] = array(
array('data' => t('Update status'), 'header' => TRUE),
$updates,
);
$output .= theme('table', array('prod_monitor_id' => 'status_general', 'header' => array(), 'rows' => $rows));
return $output;
}
@@ -99,7 +131,7 @@ function _prod_monitor_generate_updates_link($id, $update_status) {
$title = t('Security risk!');
break;
}
$updates = array('data' => '<strong>'.l($title, 'admin/reports/prod-monitor/site/'.$id.'/view/updates', array('attributes' => array('title' => $title, 'class' => $class))).'</strong>', 'class' => $class);
$updates = array('data' => '<strong>' . l($title, 'admin/reports/prod-monitor/site/' . $id . '/view/updates', array('attributes' => array('title' => $title, 'class' => $class))) . '</strong>', 'class' => $class);
}
return $updates;
@@ -109,10 +141,10 @@ function _prod_monitor_generate_updates_link($id, $update_status) {
* Callback for performance page.
*/
function prod_monitor_performance($data) {
drupal_set_title(t('Performance logs for') .' '. _prod_monitor_get_url($data['id']));
drupal_set_title(t('Performance logs for') . ' ' . _prod_monitor_get_url($data['id']));
// TODO: add 'get stats now' button.
//$site = _prod_monitor_get_site($id, TRUE);
//$site = _prod_monitor_get_site($id, 'all');
return array(
'performance_data' => array(
@@ -130,7 +162,7 @@ function prod_monitor_updates($modules) {
$id = $modules['id'];
drupal_set_title(t('Module update status for') .' '. _prod_monitor_get_url($id));
drupal_set_title(t('Module update status for') . ' ' . _prod_monitor_get_url($id));
// Only show a report if the available updates have been fetched!
if (!empty($modules) && !empty($modules['projects']) && !empty($modules['available'])) {
@@ -149,7 +181,7 @@ function prod_monitor_updates($modules) {
'No information is available about potential new releases for currently installed modules and themes. To check for updates, you may need to !cron or you can !check. Please note that checking for available updates can take a long time, so please be patient.',
array(
'!cron' => l(t('run cron'), 'admin/reports/status/run-cron', array('attributes' => array('title' => t('run cron')), 'query' => $destination)),
'!check' => l(t('check manually'), 'admin/reports/prod-monitor/site/'.$id.'/update-check', array('attributes' => array('title' => t('check manually')))),
'!check' => l(t('check manually'), 'admin/reports/prod-monitor/site/' . $id . '/update-check', array('attributes' => array('title' => t('check manually')))),
)
)
)
@@ -179,7 +211,7 @@ function prod_monitor_updates_check($id) {
else {
drupal_set_message(t('No module data available: cannot check for updates!'), 'error');
}
drupal_goto('admin/reports/prod-monitor/site/'.$id.'/view/updates');
drupal_goto('admin/reports/prod-monitor/site/' . $id . '/view/updates');
}
/**
@@ -188,18 +220,27 @@ function prod_monitor_updates_check($id) {
function prod_monitor_overview_form($form, &$form_state, $edit = FALSE) {
drupal_set_title(t('Production monitor settings'));
$base = drupal_get_path('module', 'prod_monitor');
drupal_add_css($base.'/css/prod-monitor.css', 'file');
drupal_add_js($base.'/js/jquery.equalheights.js', 'file');
drupal_add_js($base.'/js/prod-monitor.js', 'file');
drupal_add_css($base . '/css/prod-monitor.css', 'file');
drupal_add_js($base . '/js/jquery.equalheights.js', 'file');
drupal_add_js($base . '/js/prod-monitor.js', 'file');
$form = array();
$collapsed = FALSE;
if (!$edit) {
// Button to initiate our fetch all batcher.
$form['fetch_all_submit'] = array(
'#weight' => -100,
'#type' => 'submit',
'#value' => t('Fetch all'),
'#submit' => array('prod_monitor_fetch_all_submit'),
'#limit_validation_errors' => array(),
);
// Add new site situation.
$sites = _prod_monitor_get_sites();
$api_key = $url = '';
$dbconnect_path = $api_key = $url = '';
$options = array();
$button = t('Get settings');
if (!empty($sites)) {
@@ -211,6 +252,7 @@ function prod_monitor_overview_form($form, &$form_state, $edit = FALSE) {
if (!empty($form_state['storage']['get_settings'])) {
// Second step of add new site situation.
$api_key = $form_state['values']['api_key'];
$dbconnect_path = $form_state['values']['dbconnect_path'];
$url = $form_state['values']['url'];
$button = t('Add site');
$collapsed = FALSE;
@@ -227,6 +269,7 @@ function prod_monitor_overview_form($form, &$form_state, $edit = FALSE) {
}
drupal_set_title(t('Production monitor settings for !url', array('!url' => _prod_monitor_sanitize_url($url))));
$api_key = $site['settings']['api_key'];
$dbconnect_path = $site['settings']['dbconnect_path'];
$options = $site['settings']['checks'];
if (isset($site['settings']['checks']['perf_data'])) {
$perf_enabled = $site['settings']['checks']['perf_data'];
@@ -255,7 +298,7 @@ function prod_monitor_overview_form($form, &$form_state, $edit = FALSE) {
$form['sites']['api_key'] = array(
'#type' => 'textfield',
'#title' => t('The website\'s API key'),
'#title' => t("The website's API key"),
'#default_value' => $api_key,
'#description' => t('Enter the API key you have configured for this site using the <em>Production check</em> module.'),
'#size' => 60,
@@ -263,6 +306,15 @@ function prod_monitor_overview_form($form, &$form_state, $edit = FALSE) {
'#required' => TRUE,
);
$form['sites']['dbconnect_path'] = array(
'#type' => 'textfield',
'#title' => t('DB connect check script'),
'#default_value' => $dbconnect_path,
'#description' => t('Enter the relative path, starting from the Drupal root, to the <em>prod_check.dbconnect.php</em> on the remote site. This wil usually be something like sites/all/modules/contrib/prod_check/prod_check.dbconnect.php . <strong>Leave empty if you do not want do enable this check!</strong>'),
'#size' => 60,
'#maxlength' => 512,
);
// Only show on second step of add form or when editing.
if (!empty($form_state['storage']['get_settings']) || $edit) {
// Get the settings from the remote site. We always do this when the form is
@@ -303,7 +355,7 @@ function prod_monitor_overview_form($form, &$form_state, $edit = FALSE) {
'#description' => t($data['description']),
'#options' => $data['functions'],
'#default_value' => array_keys($data['functions']),
'#prefix' => '<div class="prod-check-settings '.(($rest) ? 'odd' : 'even').'">',
'#prefix' => '<div class="prod-check-settings ' . (($rest) ? 'odd' : 'even') . '">',
'#suffix' => '</div>',
);
$i++;
@@ -398,8 +450,8 @@ function _prod_monitor_overview_form_table($sites) {
$view = t('View');
$flush = t('Flush');
if ($site_info['data']) {
$view = l(t('View'), 'admin/reports/prod-monitor/site/'.$id, array('attributes' => array('title' => t('View'))));
$flush = l(t('Flush'), 'admin/reports/prod-monitor/site/'.$id.'/flush', array('attributes' => array('title' => t('Flush'))));
$view = l(t('View'), 'admin/reports/prod-monitor/site/' . $id, array('attributes' => array('title' => t('View'))));
$flush = l(t('Flush'), 'admin/reports/prod-monitor/site/' . $id . '/flush', array('attributes' => array('title' => t('Flush'))));
}
$update_status = _prod_monitor_get_update_status($id);
@@ -407,7 +459,7 @@ function _prod_monitor_overview_form_table($sites) {
if (!empty($site_info['status'])) {
$title = t(ucwords($site_info['status']));
$status = array('data' => '<strong>'.l($title, 'admin/reports/prod-monitor/site/'.$id, array('attributes' => array('title' => $title, 'class' => $site_info['status']))).'</strong>', 'class' => array($site_info['status']));
$status = array('data' => '<strong>' . l($title, 'admin/reports/prod-monitor/site/' . $id, array('attributes' => array('title' => $title, 'class' => $site_info['status']))) . '</strong>', 'class' => array($site_info['status']));
}
else {
$status = '';
@@ -424,17 +476,17 @@ function _prod_monitor_overview_form_table($sites) {
(!$site_info['lastupdate']) ? t('Not yet updated.') : $site_info['lastupdate'],
/* Compose links. */
$view,
l(t('Edit'), 'admin/reports/prod-monitor/site/'.$id.'/edit', array('query' => $home, 'attributes' => array('title' => t('Edit')))),
l(t('Fetch data'), 'admin/reports/prod-monitor/site/'.$id.'/fetch', array('attributes' => array('title' => t('Fetch & View')))),
l(t('Edit'), 'admin/reports/prod-monitor/site/' . $id . '/edit', array('query' => $home, 'attributes' => array('title' => t('Edit')))),
l(t('Fetch data'), 'admin/reports/prod-monitor/site/' . $id . '/fetch', array('attributes' => array('title' => t('Fetch & View')))),
$flush,
l(t('Delete'), 'admin/reports/prod-monitor/site/'.$id.'/delete', array('attributes' => array('title' => t('Delete')))),
l(t('Delete'), 'admin/reports/prod-monitor/site/' . $id . '/delete', array('attributes' => array('title' => t('Delete')))),
),
'class' => array($site_info['status']),
);
$rows[] = $row;
}
return theme('table', array('header' => $headers, 'rows' => $rows));
return theme('table', array('prod_monitor_id' => 'overview_form', 'header' => $headers, 'rows' => $rows));
}
/**
@@ -501,6 +553,8 @@ function prod_monitor_overview_form_submit($form, &$form_state) {
$site->settings = serialize(
array(
'api_key' => $form_state['values']['api_key'],
// Trim spaces and / from left and right side.
'dbconnect_path' => trim($form_state['values']['dbconnect_path'], ' /'),
'functions' => $form_state['storage']['functions'],
'checks' => $checks,
)
@@ -511,9 +565,12 @@ function prod_monitor_overview_form_submit($form, &$form_state) {
if ($result) {
drupal_set_message(t('Website %url correctly saved.', array('%url' => $site->url)));
if ($form_state['values']['fetch']) {
$site_info = _prod_monitor_get_site($site->id, TRUE);
$site_info = _prod_monitor_get_site($site->id, 'all');
// First: all checks.
_prod_monitor_retrieve_data($site->id, $site_info, TRUE);
$form_state['redirect'] = 'admin/reports/prod-monitor/site/'.$site->id;
// MUST be second because of the status update!
_prod_monitor_db_connect_check($site->id, $site_info);
$form_state['redirect'] = 'admin/reports/prod-monitor/site/' . $site->id;
}
}
else {
@@ -523,13 +580,81 @@ function prod_monitor_overview_form_submit($form, &$form_state) {
}
}
/**
* Submit handler for the fetch all button.
*/
function prod_monitor_fetch_all_submit($form, &$form_state) {
_prod_monitor_fetch_all_data_batcher_create();
}
/**
* Function to create the batch process. Also used in Drush!
*/
function _prod_monitor_fetch_all_data_batcher_create($fetch_only = FALSE, $update_only = FALSE, $msg = TRUE) {
$title = t('Fetching all site data and checking for updates...');
if ($fetch_only) {
$title = t('Fetching all site data...');
}
if ($update_only) {
$title = t('Checking for updates...');
}
$batch = array(
'operations' => array(
array('prod_monitor_fetch_all_data_batcher', array($fetch_only, $update_only, $msg)),
),
'title' => $title,
'file' => drupal_get_path('module', 'prod_monitor') . '/includes/prod_monitor.admin.inc',
);
batch_set($batch);
}
/**
* Batch fetching of all site info.
*/
function prod_monitor_fetch_all_data_batcher($fetch_only, $update_only, $msg, &$context) {
$sandbox = &$context['sandbox'];
if (empty($context['sandbox'])) {
$sandbox['sites'] = array_keys(_prod_monitor_get_sites());
$sandbox['count'] = count($sandbox['sites']);
}
// Get site info.
$id = array_shift($sandbox['sites']);
$site_info = _prod_monitor_get_site($id, 'all');
if (!$update_only) {
// First: all checks.
_prod_monitor_retrieve_data($id, $site_info, $msg);
// MUST be second because of the status update!
_prod_monitor_db_connect_check($id, $site_info);
}
if (!$fetch_only) {
// Module update status.
$modules = prod_monitor_load($id);
if (!empty($modules) && !empty($modules['projects'])) {
module_load_include('inc', 'prod_monitor', 'includes/prod_monitor.update');
_prod_monitor_update_refresh($id, $modules['projects'], $modules['sitekey']);
_prod_monitor_calculate_project_data($id, $modules['projects'], $modules['available']);
}
}
$context['message'] = t('Updating data for %url', array('%url' => $site_info['url']));
$context['finished'] = empty($sandbox['sites']) ? 1 : (1 - count($sandbox['sites']) / $sandbox['count']);
}
/**
* Callback to fetch site data
*/
function prod_monitor_fetch_data($id) {
$site_info = _prod_monitor_get_site($id, TRUE);
$site_info = _prod_monitor_get_site($id, 'all');
// First: all checks.
_prod_monitor_retrieve_data($id, $site_info, TRUE);
drupal_goto('admin/reports/prod-monitor/site/'.$id);
// MUST be second because of the status update!
_prod_monitor_db_connect_check($id, $site_info);
drupal_goto('admin/reports/prod-monitor/site/' . $id);
}
/**
@@ -550,7 +675,7 @@ function prod_monitor_flush_form($form, &$form_state, $id) {
'#value' => $url,
);
return confirm_form($form, t('Are you sure you wish to delete all fetched data for %url?', array('%url' => $url)), 'admin/reports/prod-monitor', t('Note that the module update status data will not be flushed!').'<br />'.t('This action cannot be undone.'));
return confirm_form($form, t('Are you sure you wish to delete all fetched data for %url?', array('%url' => $url)), 'admin/reports/prod-monitor', t('Note that the module update status data will not be flushed!') . '<br />' . t('This action cannot be undone.'));
}
/**
@@ -634,6 +759,95 @@ function _prod_monitor_update_data_form($form, $form_state, $id, $site_info) {
}
function _prod_monitor_update_data_form_submit($form, &$form_state) {
// First: all checks.
_prod_monitor_retrieve_data($form_state['values']['site_id'], $form_state['values']['site_info'], TRUE);
// MUST be second because of the status update!
_prod_monitor_db_connect_check($form_state['values']['site_id'], $form_state['values']['site_info']);
}
/**
* Callback for module lookup form.
*
*/
function prod_monitor_module_lookup_form($form, &$form_state) {
$form = array();
// Show results.
if (isset($form_state['projects'])) {
$module = $form_state['values']['module'];
$rows = array();
foreach ($form_state['projects'] as $id => $project) {
$application = db_select('prod_monitor_sites', 'pms')->fields('pms', array('url'))->condition('id', $id)->execute()->fetchField();
$version = $project['info']['version'];
$rows[] = array(
$application,
$version,
l(t('View'), 'admin/reports/prod-monitor/site/' . $id),
);
}
$form['title'] = array(
'#theme' => 'html_tag',
'#tag' => 'h2',
'#value' => t('Applications where %module is used', array('%module' => $module)),
);
$form['table'] = array(
'#theme' => 'table',
'#rows' => $rows,
'#header' => array(t('Application'), t('Version'), t('View')),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Perform another lookup'),
);
}
// Show lookup form.
else {
$form['module'] = array(
'#type' => 'textfield',
'#title' => t('Module name'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Fetch Applications'),
);
}
return $form;
}
/**
* Submission handler for module lookup form
*/
function prod_monitor_module_lookup_form_submit(&$form, &$form_state) {
if (isset($form_state['values']['module'])) {
$projects = db_select('prod_monitor_site_modules', 'psm')
->fields('psm', array('id', 'projects'))
->condition('projects', '%' . db_like($form_state['values']['module']) . '%', 'LIKE')
->execute()->fetchAllAssoc('id');
$form_state['rebuild'] = TRUE;
if ($projects && !empty($projects)) {
foreach($projects as $project) {
$modules = unserialize($project->projects);
if (isset($modules[$form_state['values']['module']])) {
$form_state['projects'][$project->id] = $modules[$form_state['values']['module']];
}
}
}
if (!isset($form_state['projects'])) {
drupal_set_message(t('No projects found for :module', array(':module' => $form_state['values']['module'])));
}
}
else {
unset($form_state['projects']);
}
}
@@ -1,5 +1,20 @@
<?php
/**
* Implements hook_preprocess_prod_monitor_update_report().
*/
function prod_monitor_preprocess_prod_monitor_update_report(&$vars) {
if (is_array($vars['data'])) {
foreach (array_keys($vars['data']) as $module_id) {
// When ignoring a module, we'll give a reason.
if (isset($vars['data'][$module_id]['ignored'])) {
$vars['data'][$module_id]['reason'] = t('Being ignored');
}
}
}
}
/**
* Returns HTML for the project status report.
*
@@ -15,12 +30,12 @@ function theme_prod_monitor_update_report($variables) {
$data = $variables['data'];
if (!is_array($data)) {
$output = '<p>'. $data .'</p>';
$output = '<p>' . $data . '</p>';
return $output;
}
$output = '<div class="update checked">'. ($last ? t('Last checked: @time ago', array('@time' => format_interval(time() - $last))) : t('Last checked: never'));
$output .= ' <span class="check-manually">('. l(t('Check manually'), 'admin/reports/prod-monitor/site/'.$id.'/update-check') .')</span>';
$output .= ' <span class="check-manually">('. l(t('Check manually'), 'admin/reports/prod-monitor/site/' . $id . '/update-check') . ')</span>';
$output .= "</div>\n";
$header = array();
@@ -226,7 +241,7 @@ function theme_prod_monitor_update_report($variables) {
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'))));
$output .= theme('table', array('prod_monitor_id' => 'update_report', 'header' => $header, 'rows' => $rows[$type_name], 'attributes' => array('class' => array('update'))));
}
}
drupal_add_css(drupal_get_path('module', 'update') . '/update.css');
@@ -29,7 +29,7 @@ function _prod_monitor_update_refresh($id, $projects, $site_key) {
// As replacement for DRUPAL_CORE_COMPATIBILITY since prod_check and
// prod_monitor should be site independant.
$core = explode('.', $projects['drupal']['info']['version']);
$core = $core[0].'.x';
$core = $core[0] . '.x';
$max_fetch_attempts = UPDATE_MAX_FETCH_ATTEMPTS;
@@ -65,10 +65,10 @@ function _prod_monitor_update_refresh($id, $projects, $site_key) {
}
}
$modules->available = serialize($available);
watchdog('prod_monitor', 'Attempted to fetch information about all available new releases and updates for %link.', array('%link' => _prod_monitor_get_url($id)), WATCHDOG_NOTICE, l(t('view'), 'admin/reports/prod-monitor/site/'.$id.'/view/updates'));
watchdog('prod_monitor', 'Fetched information about all available new releases and updates for %link.', array('%link' => _prod_monitor_get_url($id)), WATCHDOG_NOTICE, l(t('view'), 'admin/reports/prod-monitor/site/' . $id . '/view/updates'));
}
else {
watchdog('prod_monitor', 'Unable to fetch any information about available new releases and updates for %link.', array('%link' => _prod_monitor_get_url($id)), WATCHDOG_ERROR, l(t('view'), 'admin/reports/prod-monitor/site/'.$id.'/view/updates'));
watchdog('prod_monitor', 'Unable to fetch any information about available new releases and updates for %link.', array('%link' => _prod_monitor_get_url($id)), WATCHDOG_ERROR, l(t('view'), 'admin/reports/prod-monitor/site/' . $id . '/view/updates'));
}
// Whether this worked or not, we did just (try to) check for updates.
$modules->lastupdate = time();
@@ -99,7 +99,7 @@ function _prod_monitor_update_refresh($id, $projects, $site_key) {
function _prod_monitor_update_build_fetch_url($project, $site_key = '', $core) {
$name = $project['name'];
$url = _prod_monitor_update_get_fetch_url_base($project);
$url .= '/'. $name .'/'. $core;
$url .= '/' . $name . '/' . $core;
// Only append a site_key and the version information if we have a site_key
// in the first place, and if this is not a disabled module or theme. We do
// not want to record usage statistics for disabled code.
@@ -169,6 +169,19 @@ function _prod_monitor_calculate_project_data($id, $projects, $available) {
}
}
// Handle the ignored modules.
if (($ignored = _prod_monitor_get_site_ignored($id))
&& !empty($ignored['updates'])) {
foreach ($ignored['updates'] as $project_name) {
if (isset($projects[$project_name])) {
$projects[$project_name]['ignored'] = TRUE;
$projects[$project_name]['status'] = UPDATE_UNKNOWN;
}
}
}
drupal_alter('prod_monitor_project_data', $id, $projects, $available);
// Check if we need to flag a security update warning.
// Prepare object to store generated data to DB.
$modules = new stdClass();
@@ -0,0 +1,41 @@
<?php
/**
* @file
* Documentation on api functions for prod_monitor.
*
* @ingroup prod_monitor
* @{
*/
/**
* Implements hook_prod_monitor_ignore().
*
* Allows modules to specify certain ignore directives, currently
* a list of modules whose update status should be ignored.
*
* @see _prod_monitor_get_site_ignored().
* @see _prod_monitor_calculate_project_data().
*/
function hook_prod_monitor_ignore($site_id) {
$ignore = array('updates' => array());
// Ignore this module (suppress warnings) because we cannot do anything
// about it's update status as it has been abandoned and we are not going
// to stop using it.
if ($site_id == 12) {
$ignore['updates'][] = 'node_embed';
}
return $ignore;
}
/**
* Implements hook_prod_monitor_project_data_alter().
*
* Allows modules to alter the data being calculated for a project.
*
* @see _prod_monitor_calculate_project_data().
*/
function hook_prod_monitor_project_data_alter($site_id, &$data, $available) {
}
@@ -15,14 +15,15 @@ function prod_monitor_drush_command() {
),
);
$items['prod-monitor-updates'] = array(
'callback' => '_drush_prod_monitor_updates',
'callback' => 'drush_prod_monitor_updates',
'description' => 'Display the update module status page',
'aliases' => array('pmon-up'),
'arguments' => array(
'id' => 'ID of the site to view module updates for.',
),
'options' => array(
'--check' => 'Check for module updates.'
'check' => 'Check for module updates.',
'security-only' => 'Only show modules that have security updates available.',
),
);
$items['prod-monitor-fetch'] = array(
@@ -58,20 +59,38 @@ function prod_monitor_drush_command() {
*/
function drush_prod_monitor_fetch() {
$args = func_get_args();
foreach($args as $arg) {
$site = _prod_monitor_get_site($arg);
if (!empty($site['url'])) {
$result = _prod_monitor_retrieve_data($arg, $site);
$site['url'] = _prod_monitor_sanitize_url(rtrim($site['url'], '/'));
if ($result === FALSE) {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('Unable to fetch data for').' '.$site['url'].'!');
}
else {
drush_print(dt('Sucessfully fetched data for').' '.$site['url'].'.');
}
// Fetch ALL.
if (empty($args)) {
if (!drush_confirm(dt('Do you really want to fetch the data for ALL remote sites?'))) {
drush_set_error('prod_monitor', dt('Aborting.'));
return;
}
else {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('No site found with ID').' '.$arg.'!');
module_load_include('inc', 'prod_monitor', 'includes/prod_monitor.admin');
// Batch process data fetching.
_prod_monitor_fetch_all_data_batcher_create(TRUE, FALSE, FALSE);
drush_backend_batch_process();
}
}
// Fetch one or more sites as requested.
else {
foreach($args as $arg) {
$site = _prod_monitor_get_site($arg);
if (!empty($site['url'])) {
$result = _prod_monitor_retrieve_data($arg, $site);
$site['url'] = _prod_monitor_sanitize_url(rtrim($site['url'], '/'));
if ($result === FALSE) {
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('Unable to fetch data for') . ' ' . $site['url'] . '!');
}
else {
_prod_monitor_db_connect_check($arg, $site);
drush_print(dt('Sucessfully fetched data for') . ' ' . $site['url'] . '.');
}
}
else {
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('No site found with ID') . ' ' . $arg . '!');
}
}
}
}
@@ -84,19 +103,19 @@ function drush_prod_monitor_flush() {
foreach ($args as $arg) {
$url = _prod_monitor_get_url($arg);
if (!empty($url)) {
if (!drush_confirm(dt('Do you really want to flush all data for').' '.$url.'?')) {
if (!drush_confirm(dt('Do you really want to flush all data for') . ' ' . $url . '?')) {
drush_die('Aborting.');
}
$result = _prod_monitor_flush_data($arg);
if ($result === FALSE) {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('Unable to flush data!'));
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('Unable to flush data!'));
}
else {
drush_print(dt('Stored data successfully flushed.'));
}
}
else {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('No site found with ID').' '.$arg.'!');
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('No site found with ID') . ' ' . $arg . '!');
}
}
}
@@ -109,19 +128,19 @@ function drush_prod_monitor_delsite() {
foreach ($args as $arg) {
$url = _prod_monitor_get_url($arg);
if (!empty($url)) {
if (!drush_confirm(dt("Do you really want to delete").' '.$url.' '.dt('and all its data?'))) {
if (!drush_confirm(dt("Do you really want to delete") . ' ' . $url . ' ' . dt('and all its data?'))) {
drush_die('Aborting.');
}
$result = _prod_monitor_delete_site($arg);
if ($result === FALSE) {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('Unable to delete') . $url .'!');
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('Unable to delete') . $url . '!');
}
else {
drush_print(dt('Website successfully deleted.'));
}
}
else {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('No site found with ID').' '.$arg.'!');
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('No site found with ID') . ' ' . $arg . '!');
}
}
}
@@ -135,7 +154,7 @@ function drush_prod_monitor_statusdetail() {
if (empty($args)) {
_drush_prod_monitor_overview();
}
else if (is_numeric($args[0])) {
elseif (is_numeric($args[0])) {
_drush_prod_monitor_detail($args[0]);
}
}
@@ -158,7 +177,7 @@ function _drush_prod_monitor_overview() {
dt('Last update'),
dt('Status'),
));
// TODO: check why the colour coding messes up the tabs for the table
// Worked around this by placing the status column last
foreach ($sites as $id => $site_info) {
@@ -168,10 +187,10 @@ function _drush_prod_monitor_overview() {
(!$site_info['data']) ? dt('Empty') : t('Stored'),
$site_info['added'],
(!$site_info['lastupdate']) ? dt('Not yet updated') : $site_info['lastupdate'],
"\033[".$severity[$site_info['status']].'m'.ucwords($site_info['status'])."\033[0m",
"\033[" . $severity[$site_info['status']] . 'm' . ucwords($site_info['status']) . "\033[0m",
);
}
drush_print("\033[1m".dt('Production Monitor status')."\033[0m\n", 1);
drush_print("\033[1m" . dt('Production Monitor status') . "\033[0m\n", 1);
if (count($rows) > 1) {
drush_print_table($rows, TRUE);
drush_print(dt('Use drush prod-monitor [id] to view the details of a specific site.'));
@@ -182,9 +201,9 @@ function _drush_prod_monitor_overview() {
}
function _drush_prod_monitor_detail($id) {
$site = _prod_monitor_get_site($id, TRUE);
$site = _prod_monitor_get_site($id, 'all');
if (!isset($site['url'])) {
drush_print("\033[1;31m".dt('Error:')." \033[0m".dt('No site found with ID').' '.$id.'!');
drush_print("\033[1;31m" . dt('Error:') . " \033[0m" . dt('No site found with ID') . ' ' . $id . '!');
return;
}
@@ -219,7 +238,7 @@ function _drush_prod_monitor_detail($id) {
$updates = $color . $title . "\033[0m";
// Construct block
$block[] = array("\033[1m".dt('Overall status')."\033[0m");
$block[] = array("\033[1m" . dt('Overall status') . "\033[0m");
$block[] = array(
dt('Drupal core version'),
$modules['projects']['drupal']['info']['version'],
@@ -254,12 +273,12 @@ function _drush_prod_monitor_detail($id) {
foreach ($functions as $set => $data) {
if (isset($site['data'][$set])) {
$rows[] = array('');
$rows[] = array("\033[1m".dt($data['title'])."\033[0m");
$rows[] = array("\033[1m" . dt($data['title']) . "\033[0m");
if (!empty($site['data'][$set])) {
foreach ($site['data'][$set] as $check => $result) {
$rows[] = array(
$result['title'],
"\033[".$severity[$result['severity']].'m'.strip_tags($result['value'])."\033[0m",
"\033[" . $severity[$result['severity']] . 'm' . strip_tags($result['value']) . "\033[0m",
);
if ($error < $result['severity']) {
$error = $result['severity'];
@@ -273,7 +292,7 @@ function _drush_prod_monitor_detail($id) {
}
// Actual printing.
drush_print("\033[1m".dt('Production Monitor status for').' '._prod_monitor_sanitize_url($url)."\033[0m", 1);
drush_print("\033[1m" . dt('Production Monitor status for') . ' ' . _prod_monitor_sanitize_url($url) . "\033[0m", 1);
if (!empty($block)) {
drush_print_table($block);
}
@@ -286,76 +305,109 @@ function _drush_prod_monitor_detail($id) {
if ($error > 0) {
// Would be cool if we could prefix the admin path with http://<host>/ so it
// will become a clickable link in some terminals. Any ideas?
drush_print("\033[1m".dt('Some errors were reported!')."\033[0m ".dt('Check the full status page on')." \033[1m".'admin/reports/prod-monitor/'.$id.'/view'."\033[0m ".dt('for details.'));
drush_print("\033[1m" . dt('Some errors were reported!') . "\033[0m " . dt('Check the full status page on') . " \033[1m" . 'admin/reports/prod-monitor/' . $id . '/view' . "\033[0m " . dt('for details.'));
}
}
/**
* Update status page callback.
*/
function _drush_prod_monitor_updates() {
function drush_prod_monitor_updates() {
$id = func_get_args();
if (empty($id)) {
drush_set_error('prod_monitor', dt('You must provide a site ID!'));
return;
}
$id = $id['0'];
// Get module info.
$modules = _prod_monitor_get_site_modules($id);
$url = _prod_monitor_get_url($id);
if (empty($modules)) {
if (empty($url)) {
drush_set_error('prod_monitor', dt('No site found with ID').' '. $id .'!');
// Fetch ALL.
if (empty($id)) {
if (!drush_confirm(dt('Do you really want to check ALL sites for module updates?'))) {
drush_set_error('prod_monitor', dt('Aborting.'));
return;
}
else {
drush_set_error('prod_monitor', dt('No module data found for') .' '. $url.'!');
return;
module_load_include('inc', 'prod_monitor', 'includes/prod_monitor.admin');
// Batch process update checking.
_prod_monitor_fetch_all_data_batcher_create(FALSE, TRUE, FALSE);
drush_backend_batch_process();
}
}
else if (empty($modules['available'])) {
drush_set_error('prod_monitor', dt('No update data found for') .' '. $url.'!');
// No data, ask for refresh.
_drush_prod_monitor_update_refresh($id, $modules);
}
// Fetch the site as requested.
else {
$id = $id['0'];
// Refresh if user asked for it.
if (drush_get_option('check')) {
_drush_prod_monitor_update_refresh($id, $modules);
}
$last = $modules['lastupdate'];
module_load_include('inc', 'prod_monitor', 'includes/prod_monitor.update');
$projects = _prod_monitor_calculate_project_data($id, $modules['projects'], $modules['available']);
// Cleanup.
unset($modules);
// Table headers.
$rows[] = array(dt('Name'), dt('Installed version'), dt('Proposed version'), dt('Status'));
// Process releases, notifying user of status and building a list of proposed updates
drush_include_engine('update_info', 'drupal', NULL, DRUSH_BASE_PATH . '/commands/pm/update_info');
drush_include(DRUSH_BASE_PATH . '/commands/pm', 'updatecode.pm');
$updateable = pm_project_filter($projects, $rows);
// Pipe preparation
if (drush_get_context('DRUSH_PIPE')) {
$pipe = "";
foreach($projects as $project){
$pipe .= $project['name']. " ";
$pipe .= $project['existing_version']. " ";
$pipe .= $project['candidate_version']. " ";
$pipe .= str_replace(' ', '-', pm_update_filter($project)). "\n";
// Get module info.
$modules = _prod_monitor_get_site_modules($id);
$url = _prod_monitor_get_url($id);
if (empty($modules)) {
if (empty($url)) {
drush_set_error('prod_monitor', dt('No site found with ID') . ' ' . $id . '!');
return;
}
else {
drush_set_error('prod_monitor', dt('No module data found for') . ' ' . $url . '!');
return;
}
}
elseif (empty($modules['available'])) {
drush_set_error('prod_monitor', dt('No update data found for') . ' ' . $url . '!');
// No data, ask for refresh.
_drush_prod_monitor_update_refresh($id, $modules);
}
drush_print_pipe($pipe);
// Automatically curtail update process if in pipe mode
$updateable = FALSE;
}
drush_print("\033[1m".dt('Module update status for').' '.$url."\033[0m", 1);
drush_print(dt('Update information last refreshed:') .' '. ($last ? format_date($last) : dt('Never'))."\n", 1);
drush_print_table($rows, TRUE);
// Refresh if user asked for it.
if (drush_get_option('check')) {
_drush_prod_monitor_update_refresh($id, $modules);
}
$security_only = drush_get_option('security-only');
$last = $modules['lastupdate'];
module_load_include('inc', 'prod_monitor', 'includes/prod_monitor.update');
$projects = _prod_monitor_calculate_project_data($id, $modules['projects'], $modules['available']);
// Cleanup.
unset($modules);
// Table headers.
$rows[] = array(dt('Name'), dt('Installed version'), dt('Proposed version'), dt('Status'));
// Process releases, notifying user of status and building a list of proposed updates
drush_include_engine('update_info', 'drupal', NULL, DRUSH_BASE_PATH . '/commands/pm/update_info');
drush_include(DRUSH_BASE_PATH . '/commands/pm', 'updatecode.pm');
foreach ($projects as $project) {
// Only show security updates if the user requested it.
if ($security_only && $project['status'] !== UPDATE_NOT_SECURE) {
continue;
}
// Add color to the status.
$color = "\033[0m";
switch ($project['status']) {
case UPDATE_CURRENT:
$color = "\033[1;32m";
break;
case UPDATE_NOT_CURRENT:
$color = "\033[1;33m";
break;
case UPDATE_NOT_SECURE:
$color = "\033[1;31m";
break;
}
// Translate status to readable name and fill 'candidate_version'.
$status = pm_update_filter($project);
// Generate row.
$rows[] = array(
$project['name'],
$project['existing_version'],
$project['candidate_version'],
$color . $status . "\033[0m",
);
}
drush_print("\033[1m" . dt('Module update status for') . ' ' . $url . "\033[0m", 1);
drush_print(dt('Update information last refreshed:') . ' ' . ($last ? format_date($last) : dt('Never')) . "\n", 1);
if (count($rows) > 1) {
drush_print_table($rows, TRUE);
}
else {
drush_print("\033[1m" . dt('No updates to show!') . "\033[0m", 1);
}
}
}
/**
@@ -375,7 +427,7 @@ function _drush_prod_monitor_update_refresh($id, &$modules) {
$modules['lastupdate'] = time();
}
else {
drush_set_error('prod_monitor', dt('Failed to refres update status information for') .' '. $url.'!');
drush_set_error('prod_monitor', dt('Failed to refres update status information for') . ' ' . $url . '!');
drush_die('Aborting.');
}
}
@@ -4,9 +4,9 @@ package = Monitoring
core = 7.x
configure = admin/reports/prod-monitor
; Information added by packaging script on 2013-11-25
version = "7.x-1.8"
; Information added by Drupal.org packaging script on 2015-08-04
version = "7.x-1.9"
core = "7.x"
project = "prod_check"
datestamp = "1385405033"
datestamp = "1438700931"
@@ -149,29 +149,6 @@ function prod_monitor_schema() {
);
}
/**
* Implementation of hook_requirements().
*/
function prod_monitor_requirements($phase) {
$requirements = array();
switch ($phase) {
case 'install':
if (module_exists('update')) {
$requirements['prod_monitor_update'] = array(
'title' => t('Production monitor'),
'value' => t('Update manager enabled.'),
'severity' => REQUIREMENT_ERROR,
'description' => t('You have enabled <em>Update manager</em>. You have to disable this module before enabling Production monitor!'),
);
}
break;
}
return $requirements;
}
/**
* Implementation of hook_uninstall().
*/
@@ -294,3 +271,25 @@ function prod_check_update_7103() {
)
);
}
/**
* Add new dbconnect_path setting to database to prevent warnings.
*/
function prod_check_update_7104() {
$table = 'prod_monitor_sites';
// Fetch all settings.
$result = db_select($table, 'psm')
->fields('psm', array('id', 'settings'))
->execute();
// Update all sites to add new setting.
foreach ($result as $site) {
$settings = unserialize($site->settings);
$settings['dbconnect_path'] = '';
$site->settings = serialize($settings);
// Write to DB.
drupal_write_record($table, $site, array('id'));
}
}
@@ -13,21 +13,24 @@ define('PROD_MONITOR_REQUIREMENT_WARNING', 1);
define('PROD_MONITOR_REQUIREMENT_ERROR', 2);
/**
* We do the same here for the update module constants: redefine them so that we
* do not need to run the update module entirely!
* We don't want to load the Update module just to be able to run Production
* Monitor, so we copy the constants from Update. But we need to check them all
* so that we don't get notices if Update is already running.
*/
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');
define('UPDATE_NOT_SECURE', 1);
define('UPDATE_REVOKED', 2);
define('UPDATE_NOT_SUPPORTED', 3);
define('UPDATE_NOT_CURRENT', 4);
define('UPDATE_CURRENT', 5);
define('UPDATE_NOT_CHECKED', -1);
define('UPDATE_UNKNOWN', -2);
define('UPDATE_NOT_FETCHED', -3);
define('UPDATE_FETCH_PENDING', -4);
define('UPDATE_MAX_FETCH_ATTEMPTS', 2);
define('UPDATE_MAX_FETCH_TIME', 5);
if (!module_exists('update')) {
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');
define('UPDATE_NOT_SECURE', 1);
define('UPDATE_REVOKED', 2);
define('UPDATE_NOT_SUPPORTED', 3);
define('UPDATE_NOT_CURRENT', 4);
define('UPDATE_CURRENT', 5);
define('UPDATE_NOT_CHECKED', -1);
define('UPDATE_UNKNOWN', -2);
define('UPDATE_NOT_FETCHED', -3);
define('UPDATE_FETCH_PENDING', -4);
define('UPDATE_MAX_FETCH_ATTEMPTS', 2);
define('UPDATE_MAX_FETCH_TIME', 5);
}
/**
* Implementation of hook_help().
@@ -36,24 +39,29 @@ function prod_monitor_help($path, $arg) {
$output = '';
switch ($path) {
case 'admin/help#prod_monitor':
$output .= '<p>'.t('Production monitor is a module that can connect to the <strong>Production check</strong> module using <strong>XMLRPC</strong> and an <strong>API key</strong>. It will retrieve all specified data from the remote site to create a satus page and monitoring facility in a central place.').'<br />';
$output .= t('You can add multiple sites and configure per site what data you wish (not) to monitor, allowing you to setup a central Drupal site that will monitor all of your sites that have the <em>Production check</em> module with <em>XMLRPC</em> enabled.').'<br />';
$output .= t('The <strong>data retrieval</strong> mechanism can be called <strong>manually</strong> and is integrated with the <strong>cron</strong>, so you get a fresh update of data each cron run.').'</p>';
$output .= '<p>' . t('Production monitor is a module that can connect to the <strong>Production check</strong> module using <strong>XMLRPC</strong> and an <strong>API key</strong>. It will retrieve all specified data from the remote site to create a satus page and monitoring facility in a central place.') . '<br />';
$output .= t('You can add multiple sites and configure per site what data you wish (not) to monitor, allowing you to setup a central Drupal site that will monitor all of your sites that have the <em>Production check</em> module with <em>XMLRPC</em> enabled.') . '<br />';
$output .= t('The <strong>data retrieval</strong> mechanism can be called <strong>manually</strong> and is integrated with the <strong>cron</strong>, so you get a fresh update of data each cron run.') . '</p>';
break;
case 'admin/reports/prod-monitor':
$output .= '<p><strong>'.t('Site overview table').'</strong><br />';
$output .= t('The overview table gives you an overview of what sites you have added together with their status. The status will be the highest error detected in the retrieved data set.').'<br />';
$output .= t('The per site functions <strong>View</strong>, <strong>Edit</strong>, <strong>Fetch data</strong>, <strong>Flush</strong> and <strong>Delete</strong> should be self explanatory.').'</p>';
$output .= '<p><strong>' . t('Site overview table') . '</strong><br />';
$output .= t('The overview table gives you an overview of what sites you have added together with their status. The status will be the highest error detected in the retrieved data set.') . '<br />';
$output .= t('The per site functions <strong>View</strong>, <strong>Edit</strong>, <strong>Fetch data</strong>, <strong>Flush</strong> and <strong>Delete</strong> should be self explanatory.') . '</p>';
// No break!
case 'admin/reports/prod-monitor/site/%/edit':
$output .= '<p><strong>'.t('Website URL & API key').'</strong><br />';
$output .= t('To add a site, enter it\'s <strong>full url</strong>, including the protocol, but omitting the <em>xmlrpc.php</em> part and the <strong>API key</strong> that you have configured for it using the <strong>Production check</strong> module. Now click the <strong>Get settings</strong> button.').'<br />';
$output .= t('All of the checks that the <em>Production check</em> module can perform are fetched from the remote site and presented as an array of checkboxes. Finally you can configure what exactly you wish to monitor for this site, then hit the <strong>Add site</strong> button.').'<br />';
$output .= t('Each time you edit a site, the settings are fetched from the remote server so that any new checks that might have been added to the <em>Production check</em> module there are always up to date in the monitoring section.').'<br />'; $output .= t('<strong>Fetch data immediately</strong> does exactly what it says and fetches all the configured data from the remote site and will direct you to the report page.').'</p>';
$output .= '<p><strong>' . t('Website URL & API key') . '</strong><br />';
$output .= t("To add a site, enter it's <strong>full url</strong>, including the protocol, but omitting the <em>xmlrpc.php</em> part and the <strong>API key</strong> that you have configured for it using the <strong>Production check</strong> module. Now click the <strong>Get settings</strong> button.") . '<br />';
$output .= t('All of the checks that the <em>Production check</em> module can perform are fetched from the remote site and presented as an array of checkboxes. Finally you can configure what exactly you wish to monitor for this site, then hit the <strong>Add site</strong> button.') . '<br />';
$output .= t('Each time you edit a site, the settings are fetched from the remote server so that any new checks that might have been added to the <em>Production check</em> module there are always up to date in the monitoring section.') . '<br />';
$output .= t('<strong>Fetch data immediately</strong> does exactly what it says and fetches all the configured data from the remote site and will direct you to the report page.') . '</p>';
break;
case 'admin/reports/prod-monitor/module-lookup':
$output .= '<p><strong>' . t('Module name') . '</strong><br />';
$output .= t("Enter (part of) the module's machine name to see what sites are using the module.") . '<br />';
break;
case 'admin/reports/prod-monitor/site/%':
case 'admin/reports/prod-monitor/site/%/view':
$output .= '<p>'.t('This is an overview of all checks performed by the <em>Production check</em> module and their status <strong>on the remote site</strong>. You can click the links inside the report to jump to the module\'s settings page, or to go to the project page of a module, in case you need to download it for installation.').'</p>';
$output .= '<p>' . t("This is an overview of all checks performed by the <em>Production check</em> module and their status <strong>on the remote site</strong>. You can click the links inside the report to jump to the module's settings page, or to go to the project page of a module, in case you need to download it for installation.") . '</p>';
break;
}
return $output;
@@ -89,6 +97,25 @@ function prod_monitor_menu() {
'file' => 'includes/prod_monitor.admin.inc',
);
// Default primary tab (callback for this is it's parent path).
$items['admin/reports/prod-monitor/overview'] = array(
'title' => 'Overview',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => 0,
);
$items['admin/reports/prod-monitor/module-lookup'] = array(
'title' => 'Module lookup',
'description' => 'Searches monitored applications for module versions.',
'page callback' => 'drupal_get_form',
'page arguments' => array('prod_monitor_module_lookup_form'),
'access callback' => 'user_access',
'access arguments' => array('access production monitor'),
'type' => MENU_LOCAL_TASK,
'file' => 'includes/prod_monitor.admin.inc',
'weight' => 1,
);
// This hook_menu() thing, still can't fully see the logic in it. However,
// this here is what I want to achieve. It would be nice to see the /view/ bit
// in the path dissapear, that would finish it entirely. I'll settle for this
@@ -330,8 +357,10 @@ function prod_monitor_cron() {
foreach ($sites as $id => $site_info) {
$elapsed = time() - $cron_start;
if ($elapsed < $time_limit) {
//TODO: add module status update check here.
// First: all checks.
_prod_monitor_retrieve_data($id, $site_info);
// MUST be second because of the status update!
_prod_monitor_db_connect_check($id, $site_info);
$process++;
}
else {
@@ -367,7 +396,7 @@ function _prod_monitor_retrieve_functions($url, $api_key, $msg = TRUE) {
'error'
);
}
else if ($msg) {
elseif ($msg) {
drupal_set_message(t('Settings form updated, please adjust your settings.'));
}
@@ -469,7 +498,7 @@ function _prod_monitor_retrieve_data($id, $site_info, $msg = FALSE) {
);
}
}
else if ($msg) {
elseif ($msg) {
drupal_set_message(t('Module data for %link successfully updated.', array('%link' => $site_info['url'])));
}
}
@@ -495,7 +524,7 @@ function _prod_monitor_retrieve_data($id, $site_info, $msg = FALSE) {
);
}
}
else if ($msg) {
elseif ($msg) {
drupal_set_message(t('Performance data for %link successfully updated.', array('%link' => $site_info['url'])));
}
}
@@ -504,6 +533,42 @@ function _prod_monitor_retrieve_data($id, $site_info, $msg = FALSE) {
}
}
/**
* Perform separate dbconnect check. We cannot incorporate this at the side of
* prod_check as this would make no sense at all when the DB is down.
*/
function _prod_monitor_db_connect_check($id, $site_info) {
// Execute only if setup properly.
if (empty($site_info['settings']['dbconnect_path'])) {
return;
}
// Do the check.
$dbconnect_path = rtrim($site_info['url'], '/') . '/' . $site_info['settings']['dbconnect_path'];
$response = drupal_http_request($dbconnect_path);
if ($response->code !== '200' && $response->data !== 'OK') {
// Update status to notify the user of the problem!
$site_info['status'] = PROD_MONITOR_REQUIREMENT_ERROR;
$response->data = 'NOK';
}
// ALWAYS get stored site data as it should have been updated right before
// calling this function!
$site_data = _prod_monitor_get_site($id, 'data');
// Add data to site and save.
$site_data['data']['prod_mon']['prod_check_dbconnect'] = $response->code . ' ' . $response->data;
// Store site data
$site = new stdClass();
$site->id = $id;
if (isset($site_info['status'])) {
$site->status = $site_info['status'];
}
$site->data = serialize($site_data['data']);
$site->lastupdate = REQUEST_TIME;
$result = drupal_write_record('prod_monitor_sites', $site, array('id'));
}
/**
* Helper function to get all sites.
*/
@@ -526,7 +591,7 @@ function _prod_monitor_get_sites($start_id = FALSE) {
if (!empty($row->data)) {
foreach ($row->data as $set => $checks) {
foreach ($checks as $check => $results) {
$status = ($results['severity'] > $status) ? $results['severity'] : $status;
$status = (isset($results['severity']) && $results['severity'] > $status) ? $results['severity'] : $status;
}
}
$data_status = TRUE;
@@ -561,21 +626,33 @@ function _prod_monitor_get_sites($start_id = FALSE) {
*
* @param $id
* int site id.
* @param $all
* Boolean whether or not to return all fields or just the url and settings.
* @param $type
* String the amount of data to be returned.
*/
function _prod_monitor_get_site($id, $all = FALSE) {
if (!$all) {
$site = db_query("SELECT url, settings FROM {prod_monitor_sites} WHERE id = :id", array(':id' => $id))->fetchAssoc();
}
else {
$site = db_query("SELECT * FROM {prod_monitor_sites} WHERE id = :id", array(':id' => $id))->fetchAssoc();
function _prod_monitor_get_site($id, $type = 'settings') {
switch ($type) {
case 'settings':
$site = db_query("SELECT url, settings FROM {prod_monitor_sites} WHERE id = :id", array(':id' => $id))->fetchAssoc();
break;
case 'all':
$site = db_query("SELECT * FROM {prod_monitor_sites} WHERE id = :id", array(':id' => $id))->fetchAssoc();
break;
case 'data':
$site = db_query("SELECT data FROM {prod_monitor_sites} WHERE id = :id", array(':id' => $id))->fetchAssoc();
break;
}
if (!empty($site)) {
$site['settings'] = unserialize($site['settings']);
if ($all) {
$site['data'] = unserialize($site['data']);
switch ($type) {
case 'all':
$site['data'] = unserialize($site['data']);
// No break!
case 'settings':
$site['settings'] = unserialize($site['settings']);
break;
case 'data':
$site['data'] = unserialize($site['data']);
break;
}
}
@@ -607,6 +684,25 @@ function _prod_monitor_get_site_modules($id, $exists = FALSE) {
return $modules;
}
/**
* Returns an array of ignored directives by site id.
*
* @param int $id The site id.
*
* @return array
* - updates array List of project names, whose update status we'll ignore.
*/
function _prod_monitor_get_site_ignored($id) {
$ignored = &drupal_static(__FUNCTION__, array());
if (!array_key_exists($id, $ignored)) {
$ignored[$id] = module_invoke_all('prod_monitor_ignore', $id) + array(
'updates' => array(),
);
}
return $ignored[$id];
}
/**
* Helper function to get the module status of a site by ID.
*
@@ -1,298 +1,298 @@
AT NULL Feldkirch NULL 6800 Pater Grimm Weg 20
AU NULL Melbourne NULL
AU NULL Sydney NULL
AU 04 NULL NORMANBY NULL 4059 30 Normanby Terrace
BD NULL Dhaka NULL 1205 23, Subal Das Road, Chowdhury Bazar, Lalbagh
BD NULL Dhaka NULL 1207 R-1,H-19,Kallaynpur,Mirpur,Dhaka
BD NULL Dhaka NULL 1207 World Bank Office Dhaka, Plot E 32, Agargaon, Sher-E-Bangla Nagar
BD NULL Dhaka NULL 1209 House# 66B, Flat# B2 Zigatola
BD NULL Dhaka NULL 1219 390 West Rampura Dhaka
BD NULL Dhaka NULL 1230 Uttara
BD 81 NULL Dhaka NULL 1000 Institute of Water and Flood Management
BD 81 NULL Dhaka NULL 1203 84/a maniknagar
BD 81 NULL Dhaka NULL 1205 Dhaka Bangladesh
BD 81 NULL Dhaka NULL 1207 BetterStories Limited 17 West Panthopath
BD 81 NULL Dhaka NULL 1216 Mirpur, Dhaka
BD 81 NULL Dhaka NULL 1230 830, Prembagan, Dhakshin Khan
BD 82 NULL khulna NULL 9203
BD NULL NULL Dhaka NULL 1000 Institute of Water and Flood Management
BD NULL NULL Dhaka NULL 1207 World Bank Office Dhaka, Plot E 32, Agargaon, Sher-E-Bangla Nagar
BE NULL Brussels NULL
BE NULL Watermael-Boitsfort NULL 1170 Avenue des Staphylins
BH NULL Manama NULL 00973 Manama Bahrain Manama Bahrain
BR NULL Porto Alegre NULL
BR NULL Recife NULL
BR RJ NULL Rio de Janeiro NULL
BW NULL Francistown NULL NULL
BW NULL NULL Francistown NULL NULL
CA NULL Montreal NULL
CA NULL Toronto NULL
CA BC NULL Vancouver NULL
CA ON NULL Kitchener NULL
CA ON NULL wterloo NULL n2l3g1 200 University Avenue West
CH NULL Geneva NULL 1202 15, chemin Louis-Dunant
CH 25 NULL Zurich NULL 8098 UBS Optimus Foundation Augustinerhof 1
DE NULL Berlin NULL
DE 05 NULL Frankfurt am Main NULL 60386 Johanna-Tesch-Platz 7
DK NULL Aarhus NULL
ES NULL Bilbao NULL
ET 44 NULL ADDIS ABABA NULL 11945 ADDIS ABABA,P.O.BOX 11945
FI NULL Espoo NULL 02130 Mahlarinne 3B
FI NULL Helsinki NULL 00580 Hermannin rantatie 2 A Hermannin rantatie 2 A
FI NULL Tampere NULL 33101 Tampere Univerity of Technology
FI 13 NULL Espoo NULL 02150 Aalto Venture Garage Betonimiehenkuja 3
GB NULL Exeter NULL
GB NULL London NULL
GB NULL London NULL N4 2DP 2 Myddleton Ave
GB NULL London NULL N7 0AH 104 St Georges Avenue
GB NULL London NULL SE16 3UL 25 Blue Anchor Lane
GB NULL London NULL SW18 5SP Flat 1 150 Merton road
GB NULL London NULL W1T 4BQ 13 Fitzroy Street
GB NULL Oxford NULL
GB NULL Southampton NULL
GB C3 NULL NULL cb244qg 32 market street swavesey
GB E7 NULL London NULL SE3 7TP
GB F3 NULL Wood Green NULL N22 5RU 6 Cedar House
GB H1 NULL London NULL SE11 5JD 47-49 Durham Street
GB H6 NULL London NULL SE8 4DD 8 Harton St Deptford
GB K2 NULL Oxford NULL OX2 6QY 3 The Villas, Rutherway
GH 05 NULL NSAWAM NULL NULL P.O.BOX 455
GH NULL NULL Accra NULL NULL
ID NULL Bandung NULL 40134 Jalan Sadang Hegar 1 No. 12 RT04 RW13 Sadang Serang
ID NULL Bekasi NULL 17411 Jl.Binadharma 1 No.62. Jatiwaringin
ID NULL Jakarta NULL
ID NULL Jakarta NULL 12440 Jl. H. Niin 7 Lebak Bulus, Cilandak
ID NULL Jakarta NULL 13330 Otista
ID NULL Jakarta selatan NULL 12000 jl. rawa jati timur 6 no. 10
ID NULL Jakarta Timur NULL Jl.Mulia No.15B Kel.Bidara Cina, Kec.Jatinegara, Jakarta Timur
ID NULL Pematang Siantar NULL 51511 Jl. Durian I 30
ID 04 NULL Bogor NULL 16165
ID 04 NULL jakarta NULL otista
ID 04 NULL Jakarta NULL 12520 Jl. Pertanian Raya III No.42 Jakarta Selatan Pasar Minggu
ID 04 NULL Jakarta NULL 13330 Jakarta
ID 04 NULL Jakarta NULL 13330 Jl Sensus IIC Bidaracina Jaktim
ID 04 NULL Jakarta NULL 13330 Jl. Bonasut 2 no.22
ID 04 NULL Jakarta NULL 13330 Otista 64c
ID 04 NULL jakarta NULL 13330 Otista jaktim
ID 04 NULL Jakarta Timur NULL 13330 Kebon Sayur I no. 1 RT 10/15
ID 04 NULL Jakarta Timur NULL 13460 Jl. Pondok Kopi Blok G4/5 RT. 005/08 Jakarta Timur
ID 04 NULL Jakarta Timur NULL 13810 Jl. Raya Pondok Gede Rt03 Rw08 no.35 , Lubang Buaya, Jakarta Timur Jl. Raya Pondok Gede Rt03 Rw08 no.35 , Lubang Buaya, Jakarta Timur
ID 07 NULL Brebes NULL 54321 Jl Kersem Blok D14 Perum Taman Indo Kaligangsa Wetan Brebes
ID 07 NULL Semarang NULL 50143 Puspowarno Tengah 2/2
ID 08 NULL Lumajang NULL 67373 Desa Tumpeng Kecamatan Candipuro Lumajang
ID 30 NULL Bandung NULL 55241 Jl Pelesiran No 55A/56
ID 30 NULL Bekasi NULL 17510 bekasi West Java Indonesia
ID 30 NULL Depok NULL 16245 Jalan juragan sinda 2 no 10
ID 30 NULL Depok NULL 16424 Jalan Margonda RayaJalan Kober Gang Mawar
ID 30 NULL Depok NULL 16424 Jl. Haji Yahya Nuih no.24, Pondok Cina
ID 30 NULL Depok NULL 16425 Kukusan Kelurahan
ID 30 NULL Depok NULL 16518 Jl. Salak No.1/C.88 Durenseribu Bojongsari
ID 30 NULL Depok NULL 16952 Jl. Merak No.34 -36 Rt.004/014 Jl. Merak No. 34 -36 Rt. 004/014
ID 36 NULL biak numfor NULL 98111 jl. s. mamberamo no 6782 biak numfor
IL NULL Tel Aviv NULL
IN NULL Bangalore NULL
IN NULL India NULL
IN NULL new delhi NULL 110003 55 lodi estate
IN 07 NULL NEW DELHI NULL 110018 15/11 A 1ST FLOOR TILAK NAGAR
IN 07 NULL New Delhu NULL 110075 B 54 Hilansh Apartments Plot No 1, Sector 10, Dwarka
IN 10 NULL Gurgaon NULL D- 201 Ivy Apartments Sushant Lok 1 Gurgaon Haryana
IN 13 NULL Trivandrum NULL 695010 TC 9/1615, SRMH Road, Sasthamangalam, Trivandrum
IN 16 NULL Mumbai NULL 400020 Bharat Mahal, Flat#55 Marine Drive
IN 16 NULL Mumbai NULL 400028 303,Shree Parvati Co-Op Housing Society, D.L.Vaidya Road,Dadar
IN 16 NULL Pune NULL
IN 16 NULL Pune NULL Infosys Campus Hinjewadi Phase 2
IN 16 NULL Pune NULL 400705 #22 Iris Garden Gokhale Road
IN 16 NULL PUNE NULL 411043
IN 16 NULL Pune NULL 411051
IN 16 NULL Pune NULL 411057 Infosys Ltd. Rajiv gandhi infostech park Hinjewadi phase 2
IN 16 NULL Pune NULL 412108 Pune Maharatshtra
IN 16 NULL Pune NULL 433011 502 utkarsh vihar golande state pune
IN 19 NULL Bangalore NULL 560080 Indian Institute for Human Settlements IIHS Bangalore City Campus, Sadashivanagar,
IN 19 NULL Bangalore NULL 560100 electronic city
IN 19 NULL Bhalki NULL 585411 bhalki,bidar ,karnataka karnataka
IN 24 NULL Jaipur NULL 302011 Institute of Health Management Research 1, Prabhu Dayal Marg
IR 26 NULL Tehran NULL 1118844454 Baharestan sq. mostafa khomeini str., javahery Ave., no. 11,
IT NULL Trento NULL
JM 08 NULL Kingston NULL Kgn 7 MOna Campus UWI
KE NULL Nairobi NULL
KE 05 NULL Nairobi NULL 30300 212,kapsabet
KH NULL NULL Phnom Penh NULL
LR NULL Monrovia NULL 00000
NG 11 NULL Abuja NULL 930001 17 Bechar street Wuse zone 2
PE 15 NULL Lima NULL 18 Lima Lima
PE 15 NULL Lima NULL Lima 18 123 Miraflores
PE NULL NULL Lima NULL 03 Calle Granada 104
PE NULL NULL Lima NULL 18 Lima Lima
PH NULL Manila NULL Globe Telepark 111 Valero Street
PH NULL Quezon Coty NULL 1109 86 Harvard Street, Cubao, Quezon City, Philippines 84 Harvard Street, Cubao, Quezon City,hilippines
PH 20 NULL Silang NULL 4118 370 Bayungan Kaong Silang Cavite
PH 57 NULL Kidapawan NULL 9400 Kidapawan City Kidapawan City
PH 66 NULL zamboanga NULL 7000 29-tripplet rd san jose 29-tripplet rd san jose
PH D9 NULL Pasig City NULL World Bank Office Manila, 20/F Taipan Place F. Ortigas Jr. Road, Ortigas Center
PK NULL Lahore NULL 54000 17-R Model Town Lahore
PK NULL Lahore NULL 54000 53- chamber lane road Lahore
PK NULL Lahore NULL 54000 85 E block Model Town
PK NULL Lahore NULL 54000 House no 227, street no 5, Imamia Colony Shahadra Lahore
PK NULL LAHORE NULL 54000 room no.6 khalid bim waleed hall, near New Anarkali, LAHORE room no.6 khalid bim waleed hall, near New Anarkali, LAHORE
PK NULL Lahore NULL pk097 LUMS, Lahore,
PK NULL Sheikhupura NULL 03935 D.H.Q.Hospital Sheikhupura House number 08. Room no 109 Khalid bin waleed haal, punjab University lahore old campus.
PK 02 NULL Quetta NULL 87000 Postal Address 87000, Kuchlak, Quetta, Balochistan. H#24 Peer Abul Khair road Quetta, Balochistan.
PK 02 NULL Quetta NULL 87300 block no-1 falt no. 7 New Crime Branch Abbas Ali Road Cantt
PK 02 NULL Quetta NULL 87300 Flat no. 3 Shafeen Centre Jinnah Town ,Near I.T university , Quetta
PK 02 NULL Quetta NULL 87300 H-no. C-220 Zarghoonabad Phase-2 , Nawa Killi ,Quetta
PK 04 NULL burewala NULL 60101 Fatima Fayyaz Hazrat Sakina hall girls hostel number 9 Punjab university Lahore Pakistan Sardar Wajid Azim Azeem abad Burewala dist Vehari Pakistan
PK 04 NULL Faisalabad NULL 38000 P 101/1, Green Town, Millat Road, Faisalabad
PK 04 NULL Islamabad NULL 44000 P.O Tarlai kalan chappar Islamabad
PK 04 NULL lahore NULL
PK 04 NULL Lahore NULL 54000
PK 04 NULL lahore NULL 54000 Street No.63 House 36/A Al-madad Pak Colony Ravi Road, Lahore. Street No.63 House 36/A Al-madad Pak Colony Ravi Road, Lahore.
PK 04 NULL Lahore NULL 54000 1149-1-D2 Green Town Lahore
PK 04 NULL Lahore NULL 54000 124, street# 2, karim block Allama Iqbal Town lahore. 124, street# 2, karim block Allama Iqbal Town lahore.
PK 04 NULL Lahore NULL 54000 150 A Qila Lachman Singh Ravi Road lahore
PK 04 NULL Lahore NULL 54000 166/1L DHA Lahore
PK 04 NULL Lahore NULL 54000 172 A2 Township Lahore
PK 04 NULL Lahore NULL 54000 183,S/Block, Model Town, Lhr
PK 04 NULL lahore NULL 54000 19- A block ,Eden Lane Villas Raiwind Road ,Lahore
PK 04 NULL lahore NULL 54000 3-c kaliyar road opposite kids lyceum, rustam park near mor samnabad
PK 04 NULL Lahore NULL 54000 31 Saeed Block, Canal Bank Scheme
PK 04 NULL Lahore NULL 54000 31c DHA Lahore
PK 04 NULL Lahore NULL 54000 387 E1 wapda town, Lahore
PK 04 NULL Lahore NULL 54000 45-D dha eme sector multan road,lahore
PK 04 NULL Lahore NULL 54000 5 Zafar Ali Road
PK 04 NULL Lahore NULL 54000 54-R PGECHS
PK 04 NULL lahore NULL 54000 566 E-1 johar town lahore 566 E-1 johar town lahore
PK 04 NULL Lahore NULL 54000 82/1 Z Block, Phase 3 DHA
PK 04 NULL Lahore NULL 54000 A-1 VRI Zarrar shaheed road lahore cantt A-1 VRI Zarrar shaheed road lahore cantt
PK 04 NULL lahore NULL 54000 e5/39D street 6 zaman colony cavalry ground ext
PK 04 NULL Lahore NULL 54000 Ho # 61, Block G3, Johar Town Lahore
PK 04 NULL LAhore NULL 54000 House #19-A street #5 Usman nagr Ghaziabad Lahore
PK 04 NULL lahore NULL 54000 House no 692 street no 67 sadar bazar
PK 04 NULL Lahore NULL 54000 Khosa Law Chamber 1 Turner Road
PK 04 NULL Lahore NULL 54000 Lahore,Pakistan Lahore,Pakistan
PK 04 NULL Lahore NULL 54000 room no 69, khalid bin waleed hall, anarkali
PK 04 NULL Lahore NULL 54000 Suite # 8, Al-Hafeez Suites, Gulberg II
PK 04 NULL Lahore NULL 54085 199 Shadman 2
PK 04 NULL Lahore NULL 54300 Mughalpura Lahore Pakistan
PK 04 NULL Lahore NULL 54660 SD 69 falcon complex gulberg III lahore
PK 04 NULL lahore NULL 54800 764-G4 johar town ,lahore
PK 04 NULL Rawalpindi NULL 44000 House 522, F-Block Sattellite Town, Rawalpindi
PK 04 NULL Rawalpindi NULL 46000 1950/c, Indusroad 2, Tariqabad, Rawalpindi Cantt
PK 04 NULL Rawalpindi NULL 46000 House 54-E Lane 9 Sector 4, AECHS Chaklala Rawalpindi
PK 04 NULL Rawalpindi NULL 46000 House B-1343, Sattellite town Rawalpindi
PK 04 NULL Rawalpindi NULL 46000 House CB-299F, Street 1, Lane 4 Peshawar Road Rawalpindi
PK 04 NULL Rawalpindi NULL 46300 House No 1518 Umer Block phase 8 BehriaTown
PK 04 NULL sialkot NULL 51310 The National Model School, Ismaiealabad, Pacca Garah Sialkot
PK 08 NULL Islamabad NULL CIomsats Institute of Information Technology Islamabad
PK 08 NULL Islamabad NULL 38700 COMSATS tarlai boys hostel Islamabad. COMSATS tarlai boys hostel Islamabad (Room 30)
PK 08 NULL Islamabad NULL 44000
PK 08 NULL Islamabad NULL 44000 House # 256, Street # 9, Shahzad Town, Islamabad.
PK 08 NULL Islamabad NULL 44000 Islamabad , Comsats University Islamabd ,Pakistan
PK 08 NULL Islamabad NULL 44000 World Bank Building Sector G 5
PK 08 NULL lahore NULL 54000 3c zafar ali road gulburg 5 3c zafar ali road gulburg 5
PK 08 NULL lahore NULL 54000 49-a bilal park, chaburgy 49-a bilal park, chaburgy
PK NULL NULL Lahore NULL 54000
PK NULL NULL Lahore NULL 54000 85 E block Model Town
SN 01 NULL NULL ouakam cité comico en face 217
SN 01 NULL Dakar NULL
SN 01 NULL Dakar NULL IDEV-ic Patte d'oie Builder's Villa B11
SN 01 NULL Dakar NULL liberte 6/ dakar
SN 01 NULL Dakar NULL ngor
SN 01 NULL Dakar NULL 4027 ZAC Mbao Cité Fadia
SN NULL NULL Dakar NULL IDEV-ic Patte d'oie Builder's Villa B11
TZ NULL Dar es Salaam NULL NULL
TZ NULL Dar es salaam NULL NULL 76021 Dar es salaam 1507 Morogoro
TZ NULL Dar es salaam NULL NULL dar es salaam nassoro.ahmedy@yahoo.com
TZ NULL DAR ES SALAAM NULL NULL dar es salaam UDSM
TZ NULL Dar es salaam NULL NULL NA
TZ NULL DAR ES SALAAM NULL NULL P O BOX 23409
TZ NULL dar es salaam NULL NULL p. o. box 104994
TZ NULL Dar es Salaam NULL NULL P.o. BOX 71415 Dar es Salaam
TZ NULL Dar es Salaam NULL NULL P.O.BOx 66675 DSM
TZ NULL Dar es salaam NULL NULL Tz Tz
TZ NULL dsm NULL NULL
TZ 02 NULL Bagamoyo NULL NULL PO.Box 393
TZ 02 NULL Dar es salaam NULL NULL 22548
TZ 03 NULL Dar-es-salaam NULL NULL Dodoma Municipal Kimara, Dar-es-salaa,
TZ 23 NULL Dar es Salaam NULL NULL
TZ 23 NULL dar es salaam NULL NULL 35074
TZ 23 NULL dar es salaam NULL NULL 67389
TZ 23 NULL Dar es Salaam NULL NULL COSTECH, Dar es Salaam, Tanzania
TZ 23 NULL Dar es salaam NULL NULL na
TZ 23 NULL dar es salaam NULL NULL p o box 60164
TZ 23 NULL dar es salaam NULL NULL P. O. Box 77588
TZ 23 NULL dar es salaam NULL NULL P.O BOX 78144
TZ 23 NULL Dar es Salaam NULL NULL P.O.BOX 78373
TZ 23 NULL Dar es salaam NULL NULL UDSM Dar es Salaam
TZ 23 NULL Dar es salaam NULL NULL udsm udsm
TZ 23 NULL Temeke NULL NULL P.O. Box 50127
TZ NULL NULL Dar es Salaam NULL NULL
TZ NULL NULL Dar es Salaam NULL NULL Kigoma
TZ NULL NULL Dar es Salaam NULL NULL Mwanza
UG NULL Kampala NULL NULL
UG NULL Kampala NULL NULL Kampala Uganda East Africa
US NULL London NULL SE1 8RT Capital Tower 91 Waterloo Road
US CA NULL Los Angeles NULL
US CA NULL Pleasanton NULL 94588 3412 Pickens Lane
US CA NULL Sacramento NULL
US CA NULL San Francisco NULL
US CA NULL seattle NULL 98113 1234 1st st
US CO NULL Denver NULL 80235 6666 West Quincy Ave
US CT NULL Greenwich NULL 06830 140 Milbank
US CT NULL Hartford NULL 06106 Center for Urban and Global Studies at Trinity College, 70 Vernon Street
US DC NULL Washington NULL
US DC NULL Washington NULL 20007 World Bank Headquarters 1818 H Street NW
US DC NULL Washington NULL 20010
US DC NULL Washington NULL 20036
US DC NULL Washington NULL 20405 1889 F St NW
US DC NULL Washington NULL 20433
US DC NULL Washington NULL 20433 1818 H Street NW
US DC NULL Washington NULL 20433 1818H St
US DC NULL Washington NULL 20433 1818 H Street NW
US DC NULL Washington DC NULL 20005 1424, K Street, NW Suite 600
US DC NULL Washington DC NULL 20010 1818 H Street, NW
US DC NULL Washington, DC NULL 20003 1818 H Street NW
US DE NULL Virgin Islands|Charlotte Amalie,Cruz Bay,Christiansted NULL Morocco|Tafraout,Rabat,Tangier,Tetouan,Casablanca,Marrakesh,Fez,Oujda,Meknes,Agadir United Arab Emirates|Garhoud,Dubai,Bur Dubai,Ras al Khaymah,Abu Dhabi,Ajman,Al Fujayrah,Sharjah
US FL NULL Falmouth NULL Falmouth Falmouth
US FL NULL Lilongwe NULL Lilongwe Lilongwe
US GA NULL Atlanta NULL
US GU NULL Herndon NULL 15642 Ht USA
US GU NULL Miami NULL Miami Miami
US MD NULL Gaithersburg NULL 20877 554 N Frederick Avenue Suite 216
US MD NULL Potomac NULL 20854 14 Sandalfoot Court
US MD NULL Silver Spring NULL 20901 9202 Whitney St.
US MI NULL Traverse City NULL 49685 PO Box 792
US ND NULL Pirassununga NULL Pirassununga Pirassununga
US NJ NULL Princeton NULL
US NY NULL Brooklyn NULL 11206-1980 25 Montrose Ave. Apt 304
US NY NULL Brooklyn NULL 11225 975 washington ave 2d
US NY NULL Brooklyn NULL 11217 150 4TH AVE APT 9E
US NY NULL New York NULL
US NY NULL New York NULL 10013 148 Lafayette St. PH
US NY NULL New York NULL 10017 UNICEF 3 UN Plaza
US NY NULL New York NULL 10019 25 Columbus Circle Suite 52E
US NY NULL New York NULL 10024 65 West 85th Street 3A
US NY NULL New York NULL 10027 606 W. 116th Street #22
US NY NULL New York NULL 10037
US NY NULL Rochester NULL
US NY NULL Scarsdale NULL 10583-1423 54 Walworth Avenue
US OR NULL Portland NULL
US PA NULL Philadelphia NULL
US PA NULL Philadelphia NULL
US PR NULL Colonel Hill NULL Colonel Hill Colonel Hill
US SD NULL Banjul NULL Banjul Banjul
US SD NULL London NULL London London
US TX NULL Aledo NULL 76008 1588 Hunterglenn Dr
US TX NULL Keller NULL 76248 810 Placid View Ct.
US WA NULL Seattle NULL
ZA NULL Cape Town NULL
ZA NULL Cape Town NULL 7945 Alexander Road Muizenberg
ZA NULL Pretoria NULL
ZA 11 NULL Cape Town NULL
ZA 11 NULL Cape Town NULL 7435 PostNet Suite #57, Private Bag X18 Milnerton
ZA 11 NULL Cape town NULL 7508 24 Solyet Court, Lansdowne Road Claremont
ZA 11 NULL Cape Town NULL 7701
ZA 11 NULL Cape Town NULL 7785 10 Nyamakazi Road Luzuko Park Phillipi East
ZA 11 NULL Cape Town NULL 7915 66 Albert Rd
ZA 11 NULL Cape Town NULL 8001 210 Long Street
ZM NULL Lusaka NULL
ZM 09 NULL LUSAKA NULL 10101 P.O. BOX FW 174
AT NULL Feldkirch NULL 6800 Pater Grimm Weg 20 NULL
AU NULL Melbourne NULL NULL
AU NULL Sydney NULL NULL
AU 4 NULL NORMANBY NULL 4059 30 Normanby Terrace NULL
BD NULL Dhaka NULL 1205 23, Subal Das Road, Chowdhury Bazar, Lalbagh NULL
BD NULL Dhaka NULL 1207 R-1,H-19,Kallaynpur,Mirpur,Dhaka NULL
BD NULL Dhaka NULL 1207 World Bank Office Dhaka, Plot E 32, Agargaon, Sher-E-Bangla Nagar NULL
BD NULL Dhaka NULL 1209 House# 66B, Flat# B2 Zigatola NULL
BD NULL Dhaka NULL 1219 390 West Rampura Dhaka NULL
BD NULL Dhaka NULL 1230 Uttara NULL
BD 81 NULL Dhaka NULL 1000 Institute of Water and Flood Management NULL
BD 81 NULL Dhaka NULL 1203 84/a maniknagar NULL
BD 81 NULL Dhaka NULL 1205 Dhaka Bangladesh NULL
BD 81 NULL Dhaka NULL 1207 BetterStories Limited 17 West Panthopath NULL
BD 81 NULL Dhaka NULL 1216 Mirpur, Dhaka NULL
BD 81 NULL Dhaka NULL 1230 830, Prembagan, Dhakshin Khan NULL
BD 82 NULL khulna NULL 9203 NULL
BD NULL NULL Dhaka NULL 1000 Institute of Water and Flood Management NULL
BD NULL NULL Dhaka NULL 1207 World Bank Office Dhaka, Plot E 32, Agargaon, Sher-E-Bangla Nagar NULL
BE NULL Brussels NULL NULL
BE NULL Watermael-Boitsfort NULL 1170 Avenue des Staphylins NULL
BH NULL Manama NULL 973 Manama Bahrain Manama Bahrain NULL
BR NULL Porto Alegre NULL NULL
BR NULL Recife NULL NULL
BR RJ NULL Rio de Janeiro NULL NULL
BW NULL Francistown NULL NULL NULL
BW NULL NULL Francistown NULL NULL NULL
CA NULL Montreal NULL NULL
CA NULL Toronto NULL NULL
CA BC NULL Vancouver NULL NULL
CA ON NULL Kitchener NULL NULL
CA ON NULL wterloo NULL n2l3g1 200 University Avenue West NULL
CH NULL Geneva NULL 1202 15, chemin Louis-Dunant NULL
CH 25 NULL Zurich NULL 8098 UBS Optimus Foundation Augustinerhof 1 NULL
DE NULL Berlin NULL NULL
DE 5 NULL Frankfurt am Main NULL 60386 Johanna-Tesch-Platz 7 NULL
DK NULL Aarhus NULL NULL
ES NULL Bilbao NULL NULL
ET 44 NULL ADDIS ABABA NULL 11945 ADDIS ABABA,P.O.BOX 11945 NULL
FI NULL Espoo NULL 2130 Mahlarinne 3B NULL
FI NULL Helsinki NULL 580 Hermannin rantatie 2 A Hermannin rantatie 2 A NULL
FI NULL Tampere NULL 33101 Tampere University of Technology NULL
FI 13 NULL Espoo NULL 2150 Aalto Venture Garage Betonimiehenkuja 3 NULL
GB NULL Exeter NULL NULL
GB NULL London NULL NULL
GB NULL London NULL N4 2DP 2 Myddleton Ave NULL
GB NULL London NULL N7 0AH 104 St Georges Avenue NULL
GB NULL London NULL SE16 3UL 25 Blue Anchor Lane NULL
GB NULL London NULL SW18 5SP Flat 1 150 Merton road NULL
GB NULL London NULL W1T 4BQ 13 Fitzroy Street NULL
GB NULL Oxford NULL NULL
GB NULL Southampton NULL NULL
GB C3 NULL NULL cb244qg 32 market street swavesey NULL
GB E7 NULL London NULL SE3 7TP NULL
GB F3 NULL Wood Green NULL N22 5RU 6 Cedar House NULL
GB H1 NULL London NULL SE11 5JD 47-49 Durham Street NULL
GB H6 NULL London NULL SE8 4DD 8 Harton St Deptford NULL
GB K2 NULL Oxford NULL OX2 6QY 3 The Villas, Rutherway NULL
GH 5 NULL NSAWAM NULL NULL P.O.BOX 455 NULL
GH NULL NULL Accra NULL NULL NULL
ID NULL Bandung NULL 40134 Jalan Sadang Hegar 1 No. 12 RT04 RW13 Sadang Serang NULL
ID NULL Bekasi NULL 17411 Jl.Binadharma 1 No.62. Jatiwaringin NULL
ID NULL Jakarta NULL NULL
ID NULL Jakarta NULL 12440 Jl. H. Niin 7 Lebak Bulus, Cilandak NULL
ID NULL Jakarta NULL 13330 Otista NULL
ID NULL Jakarta selatan NULL 12000 jl. rawa jati timur 6 no. 10 NULL
ID NULL Jakarta Timur NULL Jl.Mulia No.15B Kel.Bidara Cina, Kec.Jatinegara, Jakarta Timur NULL
ID NULL Pematang Siantar NULL 51511 Jl. Durian I 30 NULL
ID 4 NULL Bogor NULL 16165 NULL
ID 4 NULL jakarta NULL otista NULL
ID 4 NULL Jakarta NULL 12520 Jl. Pertanian Raya III No.42 Jakarta Selatan Pasar Minggu NULL
ID 4 NULL Jakarta NULL 13330 Jakarta NULL
ID 4 NULL Jakarta NULL 13330 Jl Sensus IIC Bidaracina Jaktim NULL
ID 4 NULL Jakarta NULL 13330 Jl. Bonasut 2 no.22 NULL
ID 4 NULL Jakarta NULL 13330 Otista 64c NULL
ID 4 NULL jakarta NULL 13330 Otista jaktim NULL
ID 4 NULL Jakarta Timur NULL 13330 Kebon Sayur I no. 1 RT 10/15 NULL
ID 4 NULL Jakarta Timur NULL 13460 Jl. Pondok Kopi Blok G4/5 RT. 005/08 Jakarta Timur NULL
ID 4 NULL Jakarta Timur NULL 13810 Jl. Raya Pondok Gede Rt03 Rw08 no.35 , Lubang Buaya, Jakarta Timur Jl. Raya Pondok Gede Rt03 Rw08 no.35 , Lubang Buaya, Jakarta Timur NULL
ID 7 NULL Brebes NULL 54321 Jl Kersem Blok D14 Perum Taman Indo Kaligangsa Wetan Brebes NULL
ID 7 NULL Semarang NULL 50143 Puspowarno Tengah 2/2 NULL
ID 8 NULL Lumajang NULL 67373 Desa Tumpeng Kecamatan Candipuro Lumajang NULL
ID 30 NULL Bandung NULL 55241 Jl Pelesiran No 55A/56 NULL
ID 30 NULL Bekasi NULL 17510 bekasi West Java Indonesia NULL
ID 30 NULL Depok NULL 16245 Jalan juragan sinda 2 no 10 NULL
ID 30 NULL Depok NULL 16424 Jalan Margonda RayaJalan Kober Gang Mawar NULL
ID 30 NULL Depok NULL 16424 Jl. Haji Yahya Nuih no.24, Pondok Cina NULL
ID 30 NULL Depok NULL 16425 Kukusan Kelurahan NULL
ID 30 NULL Depok NULL 16518 Jl. Salak No.1/C.88 Durenseribu Bojongsari NULL
ID 30 NULL Depok NULL 16952 Jl. Merak No.34 -36 Rt.004/014 Jl. Merak No. 34 -36 Rt. 004/014 NULL
ID 36 NULL biak numfor NULL 98111 jl. s. mamberamo no 6782 biak numfor NULL
IL NULL Tel Aviv NULL NULL
IN NULL Bangalore NULL NULL
IN NULL India NULL NULL
IN NULL new delhi NULL 110003 55 lodi estate NULL
IN 7 NULL NEW DELHI NULL 110018 15/11 A 1ST FLOOR TILAK NAGAR NULL
IN 7 NULL New Delhu NULL 110075 B 54 Hilansh Apartments Plot No 1, Sector 10, Dwarka NULL
IN 10 NULL Gurgaon NULL D- 201 Ivy Apartments Sushant Lok 1 Gurgaon Haryana NULL
IN 13 NULL Trivandrum NULL 695010 TC 9/1615, SRMH Road, Sasthamangalam, Trivandrum NULL
IN 16 NULL Mumbai NULL 400020 Bharat Mahal, Flat#55 Marine Drive NULL
IN 16 NULL Mumbai NULL 400028 303,Shree Parvati Co-Op Housing Society, D.L.Vaidya Road,Dadar NULL
IN 16 NULL Pune NULL NULL
IN 16 NULL Pune NULL Infosys Campus Hinjewadi Phase 2 NULL
IN 16 NULL Pune NULL 400705 #22 Iris Garden Gokhale Road NULL
IN 16 NULL PUNE NULL 411043 NULL
IN 16 NULL Pune NULL 411051 NULL
IN 16 NULL Pune NULL 411057 Infosys Ltd. Rajiv gandhi infostech park Hinjewadi phase 2 NULL
IN 16 NULL Pune NULL 412108 Pune Maharatshtra NULL
IN 16 NULL Pune NULL 433011 502 utkarsh vihar golande state pune NULL
IN 19 NULL Bangalore NULL 560080 Indian Institute for Human Settlements IIHS Bangalore City Campus, Sadashivanagar, NULL
IN 19 NULL Bangalore NULL 560100 electronic city NULL
IN 19 NULL Bhalki NULL 585411 bhalki,bidar ,karnataka karnataka NULL
IN 24 NULL Jaipur NULL 302011 Institute of Health Management Research 1, Prabhu Dayal Marg NULL
IR 26 NULL Tehran NULL 1118844454 Baharestan sq. mostafa khomeini str., javahery Ave., no. 11, NULL
IT NULL Trento NULL NULL
JM 8 NULL Kingston NULL Kgn 7 MOna Campus UWI NULL
KE NULL Nairobi NULL NULL
KE 5 NULL Nairobi NULL 30300 212,kapsabet NULL
KH NULL NULL Phnom Penh NULL NULL
LR NULL Monrovia NULL 0 NULL
NG 11 NULL Abuja NULL 930001 17 Bechar street Wuse zone 2 NULL
PE 15 NULL Lima NULL 18 Lima Lima NULL
PE 15 NULL Lima NULL Lima 18 123 Miraflores NULL
PE NULL NULL Lima NULL 3 Calle Granada 104 NULL
PE NULL NULL Lima NULL 18 Lima Lima NULL
PH NULL Manila NULL Globe Telepark 111 Valero Street NULL
PH NULL Quezon Coty NULL 1109 86 Harvard Street, Cubao, Quezon City, Philippines 84 Harvard Street, Cubao, Quezon City,hilippines NULL
PH 20 NULL Silang NULL 4118 370 Bayungan Kaong Silang Cavite NULL
PH 57 NULL Kidapawan NULL 9400 Kidapawan City Kidapawan City NULL
PH 66 NULL zamboanga NULL 7000 29-tripplet rd san jose 29-tripplet rd san jose NULL
PH D9 NULL Pasig City NULL World Bank Office Manila, 20/F Taipan Place F. Ortigas Jr. Road, Ortigas Center NULL
PK NULL Lahore NULL 54000 17-R Model Town Lahore NULL
PK NULL Lahore NULL 54000 53- chamber lane road Lahore NULL
PK NULL Lahore NULL 54000 85 E block Model Town NULL
PK NULL Lahore NULL 54000 House no 227, street no 5, Imamia Colony Shahadra Lahore NULL
PK NULL LAHORE NULL 54000 room no.6 khalid bim waleed hall, near New Anarkali, LAHORE room no.6 khalid bim waleed hall, near New Anarkali, LAHORE NULL
PK NULL Lahore NULL pk097 LUMS, Lahore, NULL
PK NULL Sheikhupura NULL 3935 D.H.Q.Hospital Sheikhupura House number 08. Room no 109 Khalid bin waleed haal, punjab University lahore old campus. NULL
PK 2 NULL Quetta NULL 87000 Postal Address 87000, Kuchlak, Quetta, Balochistan. H#24 Peer Abul Khair road Quetta, Balochistan. NULL
PK 2 NULL Quetta NULL 87300 block no-1 falt no. 7 New Crime Branch Abbas Ali Road Cantt NULL
PK 2 NULL Quetta NULL 87300 Flat no. 3 Shafeen Centre Jinnah Town ,Near I.T university , Quetta NULL
PK 2 NULL Quetta NULL 87300 H-no. C-220 Zarghoonabad Phase-2 , Nawa Killi ,Quetta NULL
PK 4 NULL burewala NULL 60101 Fatima Fayyaz Hazrat Sakina hall girls hostel number 9 Punjab university Lahore Pakistan Sardar Wajid Azim Azeem abad Burewala dist Vehari Pakistan NULL
PK 4 NULL Faisalabad NULL 38000 P 101/1, Green Town, Millat Road, Faisalabad NULL
PK 4 NULL Islamabad NULL 44000 P.O Tarlai kalan chappar Islamabad NULL
PK 4 NULL lahore NULL NULL
PK 4 NULL Lahore NULL 54000 NULL
PK 4 NULL lahore NULL 54000 Street No.63 House 36/A Al-madad Pak Colony Ravi Road, Lahore. Street No.63 House 36/A Al-madad Pak Colony Ravi Road, Lahore. NULL
PK 4 NULL Lahore NULL 54000 1149-1-D2 Green Town Lahore NULL
PK 4 NULL Lahore NULL 54000 124, street# 2, karim block Allama Iqbal Town lahore. 124, street# 2, karim block Allama Iqbal Town lahore. NULL
PK 4 NULL Lahore NULL 54000 150 A Qila Lachman Singh Ravi Road lahore NULL
PK 4 NULL Lahore NULL 54000 166/1L DHA Lahore NULL
PK 4 NULL Lahore NULL 54000 172 A2 Township Lahore NULL
PK 4 NULL Lahore NULL 54000 183,S/Block, Model Town, Lhr NULL
PK 4 NULL lahore NULL 54000 19- A block ,Eden Lane Villas Raiwind Road ,Lahore NULL
PK 4 NULL lahore NULL 54000 3-c kaliyar road opposite kids lyceum, rustam park near mor samnabad NULL
PK 4 NULL Lahore NULL 54000 31 Saeed Block, Canal Bank Scheme NULL
PK 4 NULL Lahore NULL 54000 31c DHA Lahore NULL
PK 4 NULL Lahore NULL 54000 387 E1 wapda town, Lahore NULL
PK 4 NULL Lahore NULL 54000 45-D dha eme sector multan road,lahore NULL
PK 4 NULL Lahore NULL 54000 5 Zafar Ali Road NULL
PK 4 NULL Lahore NULL 54000 54-R PGECHS NULL
PK 4 NULL lahore NULL 54000 566 E-1 johar town lahore 566 E-1 johar town lahore NULL
PK 4 NULL Lahore NULL 54000 82/1 Z Block, Phase 3 DHA NULL
PK 4 NULL Lahore NULL 54000 A-1 VRI Zarrar shaheed road lahore cantt A-1 VRI Zarrar shaheed road lahore cantt NULL
PK 4 NULL lahore NULL 54000 e5/39D street 6 zaman colony cavalry ground ext NULL
PK 4 NULL Lahore NULL 54000 Ho # 61, Block G3, Johar Town Lahore NULL
PK 4 NULL LAhore NULL 54000 House #19-A street #5 Usman nagr Ghaziabad Lahore NULL
PK 4 NULL lahore NULL 54000 House no 692 street no 67 sadar bazar NULL
PK 4 NULL Lahore NULL 54000 Khosa Law Chamber 1 Turner Road NULL
PK 4 NULL Lahore NULL 54000 Lahore,Pakistan Lahore,Pakistan NULL
PK 4 NULL Lahore NULL 54000 room no 69, khalid bin waleed hall, anarkali NULL
PK 4 NULL Lahore NULL 54000 Suite # 8, Al-Hafeez Suites, Gulberg II NULL
PK 4 NULL Lahore NULL 54085 199 Shadman 2 NULL
PK 4 NULL Lahore NULL 54300 Mughalpura Lahore Pakistan NULL
PK 4 NULL Lahore NULL 54660 SD 69 falcon complex gulberg III lahore NULL
PK 4 NULL lahore NULL 54800 764-G4 johar town ,lahore NULL
PK 4 NULL Rawalpindi NULL 44000 House 522, F-Block Sattellite Town, Rawalpindi NULL
PK 4 NULL Rawalpindi NULL 46000 1950/c, Indusroad 2, Tariqabad, Rawalpindi Cantt NULL
PK 4 NULL Rawalpindi NULL 46000 House 54-E Lane 9 Sector 4, AECHS Chaklala Rawalpindi NULL
PK 4 NULL Rawalpindi NULL 46000 House B-1343, Sattellite town Rawalpindi NULL
PK 4 NULL Rawalpindi NULL 46000 House CB-299F, Street 1, Lane 4 Peshawar Road Rawalpindi NULL
PK 4 NULL Rawalpindi NULL 46300 House No 1518 Umer Block phase 8 BehriaTown NULL
PK 4 NULL sialkot NULL 51310 The National Model School, Ismaiealabad, Pacca Garah Sialkot NULL
PK 8 NULL Islamabad NULL CIomsats Institute of Information Technology Islamabad NULL
PK 8 NULL Islamabad NULL 38700 COMSATS tarlai boys hostel Islamabad. COMSATS tarlai boys hostel Islamabad (Room 30) NULL
PK 8 NULL Islamabad NULL 44000 NULL
PK 8 NULL Islamabad NULL 44000 House # 256, Street # 9, Shahzad Town, Islamabad. NULL
PK 8 NULL Islamabad NULL 44000 Islamabad , Comsats University Islamabd ,Pakistan NULL
PK 8 NULL Islamabad NULL 44000 World Bank Building Sector G 5 NULL
PK 8 NULL lahore NULL 54000 3c zafar ali road gulburg 5 3c zafar ali road gulburg 5 NULL
PK 8 NULL lahore NULL 54000 49-a bilal park, chaburgy 49-a bilal park, chaburgy NULL
PK NULL NULL Lahore NULL 54000 NULL
PK NULL NULL Lahore NULL 54000 85 E block Model Town NULL
SN 1 NULL NULL ouakam cité comico en face 217 NULL
SN 1 NULL Dakar NULL NULL
SN 1 NULL Dakar NULL IDEV-ic Patte d'oie Builder's Villa B11 NULL
SN 1 NULL Dakar NULL liberte 6/ dakar NULL
SN 1 NULL Dakar NULL ngor NULL
SN 1 NULL Dakar NULL 4027 ZAC Mbao Cité Fadia NULL
SN NULL NULL Dakar NULL IDEV-ic Patte d'oie Builder's Villa B11 NULL
TZ NULL Dar es Salaam NULL NULL NULL
TZ NULL Dar es salaam NULL NULL 76021 Dar es salaam 1507 Morogoro NULL
TZ NULL Dar es salaam NULL NULL dar es salaam nassoro.ahmedy@yahoo.com NULL
TZ NULL DAR ES SALAAM NULL NULL dar es salaam UDSM NULL
TZ NULL Dar es salaam NULL NULL NA NULL
TZ NULL DAR ES SALAAM NULL NULL P O BOX 23409 NULL
TZ NULL dar es salaam NULL NULL p. o. box 104994 NULL
TZ NULL Dar es Salaam NULL NULL P.o. BOX 71415 Dar es Salaam NULL
TZ NULL Dar es Salaam NULL NULL P.O.BOx 66675 DSM NULL
TZ NULL Dar es salaam NULL NULL Tz Tz NULL
TZ NULL dsm NULL NULL NULL
TZ 2 NULL Bagamoyo NULL NULL PO.Box 393 NULL
TZ 2 NULL Dar es salaam NULL NULL 22548 NULL
TZ 3 NULL Dar-es-salaam NULL NULL Dodoma Municipal Kimara, Dar-es-salaa, NULL
TZ 23 NULL Dar es Salaam NULL NULL NULL
TZ 23 NULL dar es salaam NULL NULL 35074 NULL
TZ 23 NULL dar es salaam NULL NULL 67389 NULL
TZ 23 NULL Dar es Salaam NULL NULL COSTECH, Dar es Salaam, Tanzania NULL
TZ 23 NULL Dar es salaam NULL NULL na NULL
TZ 23 NULL dar es salaam NULL NULL p o box 60164 NULL
TZ 23 NULL dar es salaam NULL NULL P. O. Box 77588 NULL
TZ 23 NULL dar es salaam NULL NULL P.O BOX 78144 NULL
TZ 23 NULL Dar es Salaam NULL NULL P.O.BOX 78373 NULL
TZ 23 NULL Dar es salaam NULL NULL UDSM Dar es Salaam NULL
TZ 23 NULL Dar es salaam NULL NULL udsm udsm NULL
TZ 23 NULL Temeke NULL NULL P.O. Box 50127 NULL
TZ NULL NULL Dar es Salaam NULL NULL NULL
TZ NULL NULL Dar es Salaam NULL NULL Kigoma NULL
TZ NULL NULL Dar es Salaam NULL NULL Mwanza NULL
UG NULL Kampala NULL NULL NULL
UG NULL Kampala NULL NULL Kampala Uganda East Africa NULL
US NULL London NULL SE1 8RT Capital Tower 91 Waterloo Road NULL
US CA NULL Los Angeles NULL NULL
US CA NULL Pleasanton NULL 94588 3412 Pickens Lane NULL
US CA NULL Sacramento NULL NULL
US CA NULL San Francisco NULL NULL
US CA NULL seattle NULL 98113 1234 1st st NULL
US CO NULL Denver NULL 80235 6666 West Quincy Ave NULL
US CT NULL Greenwich NULL 6830 140 Milbank NULL
US CT NULL Hartford NULL 6106 Center for Urban and Global Studies at Trinity College, 70 Vernon Street NULL
US DC NULL Washington NULL NULL
US DC NULL Washington NULL 20007 World Bank Headquarters 1818 H Street NW NULL
US DC NULL Washington NULL 20010 NULL
US DC NULL Washington NULL 20036 NULL
US DC NULL Washington NULL 20405 1889 F St NW NULL
US DC NULL Washington NULL 20433 NULL
US DC NULL Washington NULL 20433 1818 H Street NW NULL
US DC NULL Washington NULL 20433 1818H St NULL
US DC NULL Washington NULL 20433 1818 H Street NW NULL
US DC NULL Washington DC NULL 20005 1424, K Street, NW Suite 600 NULL
US DC NULL Washington DC NULL 20010 1818 H Street, NW NULL
US DC NULL Washington, DC NULL 20003 1818 H Street NW NULL
US DE NULL Virgin Islands|Charlotte Amalie,Cruz Bay,Christiansted NULL Morocco|Tafraout,Rabat,Tangier,Tetouan,Casablanca,Marrakesh,Fez,Oujda,Meknes,Agadir United Arab Emirates|Garhoud,Dubai,Bur Dubai,Ras al Khaymah,Abu Dhabi,Ajman,Al Fujayrah,Sharjah NULL
US FL NULL Falmouth NULL Falmouth Falmouth NULL
US FL NULL Lilongwe NULL Lilongwe Lilongwe NULL
US GA NULL Atlanta NULL NULL
US GU NULL Herndon NULL 15642 Ht USA NULL
US GU NULL Miami NULL Miami Miami NULL
US MD NULL Gaithersburg NULL 20877 554 N Frederick Avenue Suite 216 NULL
US MD NULL Potomac NULL 20854 14 Sandalfoot Court NULL
US MD NULL Silver Spring NULL 20901 9202 Whitney St. NULL
US MI NULL Traverse City NULL 49685 PO Box 792 NULL
US ND NULL Pirassununga NULL Pirassununga Pirassununga NULL
US NJ NULL Princeton NULL NULL
US NY NULL Brooklyn NULL 11206-1980 25 Montrose Ave. Apt 304 NULL
US NY NULL Brooklyn NULL 11225 975 washington ave 2d NULL
US NY NULL Brooklyn NULL 11217 150 4TH AVE APT 9E NULL
US NY NULL New York NULL NULL
US NY NULL New York NULL 10013 148 Lafayette St. PH NULL
US NY NULL New York NULL 10017 UNICEF 3 UN Plaza NULL
US NY NULL New York NULL 10019 25 Columbus Circle Suite 52E NULL
US NY NULL New York NULL 10024 65 West 85th Street 3A NULL
US NY NULL New York NULL 10027 606 W. 116th Street #22 NULL
US NY NULL New York NULL 10037 NULL
US NY NULL Rochester NULL NULL
US NY NULL Scarsdale NULL 10583-1423 54 Walworth Avenue NULL
US OR NULL Portland NULL NULL
US PA NULL Philadelphia NULL NULL
US PA NULL Philadelphia NULL NULL
US PR NULL Colonel Hill NULL Colonel Hill Colonel Hill NULL
US SD NULL Banjul NULL Banjul Banjul NULL
US SD NULL London NULL London London NULL
US TX NULL Aledo NULL 76008 1588 Hunterglenn Dr NULL
US TX NULL Keller NULL 76248 810 Placid View Ct. NULL
US WA NULL Seattle NULL NULL
ZA NULL Cape Town NULL NULL
ZA NULL Cape Town NULL 7945 Alexander Road Muizenberg NULL
ZA NULL Pretoria NULL NULL
ZA 11 NULL Cape Town NULL NULL
ZA 11 NULL Cape Town NULL 7435 PostNet Suite #57, Private Bag X18 Milnerton NULL
ZA 11 NULL Cape town NULL 7508 24 Solyet Court, Lansdowne Road Claremont NULL
ZA 11 NULL Cape Town NULL 7701 NULL
ZA 11 NULL Cape Town NULL 7785 10 Nyamakazi Road Luzuko Park Phillipi East NULL
ZA 11 NULL Cape Town NULL 7915 66 Albert Rd NULL
ZA 11 NULL Cape Town NULL 8001 210 Long Street NULL
ZM NULL Lusaka NULL NULL
ZM 9 NULL LUSAKA NULL 10101 P.O. BOX FW 174 NULL
@@ -41,11 +41,11 @@ function addressfield_get_address_format($country_code) {
// postal code in 'used_fields'.
$countries_with_optional_postal_code = array(
'AC', 'AD', 'AL', 'AZ', 'BA', 'BB', 'BD', 'BG', 'BH', 'BM', 'BN', 'BT',
'CR', 'CY', 'CZ', 'DO', 'DZ', 'EC', 'EH', 'ET', 'FO', 'GE', 'GN', 'GT',
'CR', 'CY', 'DO', 'DZ', 'EC', 'EH', 'ET', 'FO', 'GE', 'GN', 'GT',
'GW', 'HR', 'HT', 'IL', 'IS', 'JO', 'KE', 'KG', 'KH', 'KW', 'LA',
'LA', 'LB', 'LK', 'LR', 'LS', 'MA', 'MC', 'MD', 'ME', 'MG', 'MK', 'MM',
'MT', 'MU', 'MV', 'NE', 'NP', 'OM', 'PK', 'PY', 'RO', 'RS', 'SA', 'SI',
'SK', 'SN', 'SZ', 'TA', 'TJ', 'TM', 'TN', 'VA', 'VC', 'VG', 'XK', 'ZM',
'SN', 'SZ', 'TA', 'TJ', 'TM', 'TN', 'VA', 'VC', 'VG', 'XK', 'ZM',
);
foreach ($countries_with_optional_postal_code as $code) {
$address_formats[$code] = array(
@@ -56,9 +56,9 @@ function addressfield_get_address_format($country_code) {
// These formats differ from the default only by the presence of the
// postal code in 'used_fields' and 'required_fields'.
$countries_with_required_postal_code = array(
'AT', 'AX', 'BE', 'BL', 'CH', 'DE', 'DK', 'FI', 'FK', 'FR', 'GF', 'GG',
'AT', 'AX', 'BE', 'BL', 'CH', 'CZ', 'DE', 'DK', 'FI', 'FK', 'FR', 'GF', 'GG',
'GL', 'GP', 'GR', 'GS', 'HU', 'IM', 'IO', 'JE', 'LI', 'LU', 'MF', 'MQ', 'NC',
'NL', 'NO', 'PL', 'PM', 'PN', 'PT', 'RE', 'SE', 'SH', 'SJ', 'TC', 'WF',
'NL', 'NO', 'PL', 'PM', 'PN', 'PT', 'RE', 'SE', 'SH', 'SJ', 'SK', 'TC', 'WF',
'YT',
);
foreach ($countries_with_required_postal_code as $code) {
@@ -114,7 +114,7 @@ function addressfield_get_address_format($country_code) {
'used_fields' => array('locality', 'administrative_area', 'postal_code'),
);
$address_formats['CL'] = array(
'used_fields' => array('locality', 'administrative_area', 'postal_code'),
'used_fields' => array('dependent_locality', 'locality', 'administrative_area', 'postal_code'),
'administrative_area_label' => t('State', array(), array('context' => 'Territory of a country')),
'render_administrative_area_value' => TRUE,
);
@@ -124,7 +124,7 @@ function addressfield_get_address_format($country_code) {
'dependent_locality_label' => t('District'),
);
$address_formats['CO'] = array(
'used_fields' => array('locality', 'administrative_area'),
'used_fields' => array('locality', 'administrative_area', 'postal_code'),
'administrative_area_label' => t('Department', array(), array('context' => 'Territory of a country')),
);
$address_formats['CV'] = array(
@@ -235,6 +235,7 @@ function addressfield_get_address_format($country_code) {
'used_fields' => array('dependent_locality', 'locality', 'administrative_area', 'postal_code'),
'required_fields' => array('locality', 'administrative_area', 'postal_code'),
'dependent_locality_label' => t('District'),
'render_administrative_area_value' => TRUE,
);
$address_formats['KY'] = array(
'used_fields' => array('administrative_area', 'postal_code'),
@@ -11,6 +11,29 @@
* NULL if not found.
*/
function addressfield_get_administrative_areas($country_code) {
// Maintain a static cache to avoid passing the administrative areas through
// t() more than once per request.
$administrative_areas = &drupal_static(__FUNCTION__, array());
if (empty($administrative_areas)) {
// Get the default administrative areas.
$administrative_areas = _addressfield_get_administrative_areas_defaults();
// Allow other modules to alter the administrative areas.
drupal_alter('addressfield_administrative_areas', $administrative_areas);
}
return isset($administrative_areas[$country_code]) ? $administrative_areas[$country_code] : NULL;
}
/**
* Provides the default administrative areas.
*/
function _addressfield_get_administrative_areas_defaults() {
// To avoid needless pollution of the strings list we only pass to t()
// those administrative areas that are in English (or a latin transcription),
// and belong to a country that either has multiple official languages (CA)
// or uses a non-latin script (AE, CN, JP, KR, UA, RU, etc).
// No translation is expected in other cases.
$administrative_areas = array();
$administrative_areas['AE'] = array(
'AZ' => t('Abu Dhabi'),
@@ -22,69 +45,69 @@ function addressfield_get_administrative_areas($country_code) {
'AJ' => t('Ajmān'),
);
$administrative_areas['AR'] = array(
'B' => t('Buenos Aires'),
'K' => t('Catamarca'),
'H' => t('Chaco'),
'U' => t('Chubut'),
'C' => t('Ciudad de Buenos Aires'),
'X' => t('Córdoba'),
'W' => t('Corrientes'),
'E' => t('Entre Ríos'),
'P' => t('Formosa'),
'Y' => t('Jujuy'),
'L' => t('La Pampa'),
'F' => t('La Rioja'),
'M' => t('Mendoza'),
'N' => t('Misiones'),
'Q' => t('Neuquén'),
'R' => t('Río Negro'),
'A' => t('Salta'),
'J' => t('San Juan'),
'D' => t('San Luis'),
'Z' => t('Santa Cruz'),
'S' => t('Santa Fe'),
'G' => t('Santiago del Estero'),
'V' => t('Tierra del Fuego'),
'T' => t('Tucumán'),
'B' => 'Buenos Aires',
'K' => 'Catamarca',
'H' => 'Chaco',
'U' => 'Chubut',
'C' => 'Ciudad de Buenos Aires',
'X' => 'Córdoba',
'W' => 'Corrientes',
'E' => 'Entre Ríos',
'P' => 'Formosa',
'Y' => 'Jujuy',
'L' => 'La Pampa',
'F' => 'La Rioja',
'M' => 'Mendoza',
'N' => 'Misiones',
'Q' => 'Neuquén',
'R' => 'Río Negro',
'A' => 'Salta',
'J' => 'San Juan',
'D' => 'San Luis',
'Z' => 'Santa Cruz',
'S' => 'Santa Fe',
'G' => 'Santiago del Estero',
'V' => 'Tierra del Fuego',
'T' => 'Tucumán',
);
$administrative_areas['AU'] = array(
'ACT' => t('Australian Capital Territory'),
'NSW' => t('New South Wales'),
'NT' => t('Northern Territory'),
'QLD' => t('Queensland'),
'SA' => t('South Australia'),
'TAS' => t('Tasmania'),
'VIC' => t('Victoria'),
'WA' => t('Western Australia'),
'ACT' => 'Australian Capital Territory',
'NSW' => 'New South Wales',
'NT' => 'Northern Territory',
'QLD' => 'Queensland',
'SA' => 'South Australia',
'TAS' => 'Tasmania',
'VIC' => 'Victoria',
'WA' => 'Western Australia',
);
$administrative_areas['BR'] = array(
'AC' => t('Acre'),
'AL' => t('Alagoas'),
'AM' => t('Amazonas'),
'AP' => t('Amapá'),
'BA' => t('Bahia'),
'CE' => t('Ceará'),
'DF' => t('Distrito Federal'),
'ES' => t('Espírito Santo'),
'GO' => t('Goiás'),
'MA' => t('Maranhão'),
'MG' => t('Minas Gerais'),
'MS' => t('Mato Grosso do Sul'),
'MT' => t('Mato Grosso'),
'PA' => t('Pará'),
'PB' => t('Paraíba'),
'PE' => t('Pernambuco'),
'PI' => t('Piauí'),
'PR' => t('Paraná'),
'RJ' => t('Rio de Janeiro'),
'RN' => t('Rio Grande do Norte'),
'RO' => t('Rondônia'),
'RR' => t('Roraima'),
'RS' => t('Rio Grande do Sul'),
'SC' => t('Santa Catarina'),
'SE' => t('Sergipe'),
'SP' => t('São Paulo'),
'TO' => t('Tocantins'),
'AC' => 'Acre',
'AL' => 'Alagoas',
'AM' => 'Amazonas',
'AP' => 'Amapá',
'BA' => 'Bahia',
'CE' => 'Ceará',
'DF' => 'Distrito Federal',
'ES' => 'Espírito Santo',
'GO' => 'Goiás',
'MA' => 'Maranhão',
'MG' => 'Minas Gerais',
'MS' => 'Mato Grosso do Sul',
'MT' => 'Mato Grosso',
'PA' => 'Pará',
'PB' => 'Paraíba',
'PE' => 'Pernambuco',
'PI' => 'Piauí',
'PR' => 'Paraná',
'RJ' => 'Rio de Janeiro',
'RN' => 'Rio Grande do Norte',
'RO' => 'Rondônia',
'RR' => 'Roraima',
'RS' => 'Rio Grande do Sul',
'SC' => 'Santa Catarina',
'SE' => 'Sergipe',
'SP' => 'São Paulo',
'TO' => 'Tocantins',
);
$administrative_areas['CA'] = array(
'AB' => t('Alberta'),
@@ -102,21 +125,21 @@ function addressfield_get_administrative_areas($country_code) {
'YT' => t('Yukon Territory'),
);
$administrative_areas['CL'] = array(
'AI' => t('Aysén del General Carlos Ibáñez del Campo'),
'AN' => t('Antofagasta'),
'AR' => t('Araucanía'),
'AP' => t('Arica y Parinacota'),
'AT' => t('Atacama'),
'BI' => t('Biobío'),
'CO' => t('Coquimbo'),
'LI' => t('Libertador General Bernardo O\'Higgins'),
'LL' => t('Los Lagos'),
'LR' => t('Los Ríos'),
'MA' => t('Magallanes y de la Antártica Chilena'),
'ML' => t('Maule'),
'RM' => t('Metropolitana de Santiago'),
'TA' => t('Tarapacá'),
'VS' => t('Valparaíso'),
'AI' => 'Aysén del General Carlos Ibáñez del Campo',
'AN' => 'Antofagasta',
'AR' => 'Araucanía',
'AP' => 'Arica y Parinacota',
'AT' => 'Atacama',
'BI' => 'Biobío',
'CO' => 'Coquimbo',
'LI' => 'Libertador General Bernardo O\'Higgins',
'LL' => 'Los Lagos',
'LR' => 'Los Ríos',
'MA' => 'Magallanes y de la Antártica Chilena',
'ML' => 'Maule',
'RM' => 'Metropolitana de Santiago',
'TA' => 'Tarapacá',
'VS' => 'Valparaíso',
);
$administrative_areas['CN'] = array(
'34' => t('Anhui Sheng'),
@@ -155,55 +178,55 @@ function addressfield_get_administrative_areas($country_code) {
'33' => t('Zhejiang Sheng'),
);
$administrative_areas['CO'] = array(
'AMA' => t('Amazonas'),
'ANT' => t('Antioquia'),
'ARA' => t('Arauca'),
'ATL' => t('Atlántico'),
'BOL' => t('Bolívar'),
'BOY' => t('Boyacá'),
'CAL' => t('Caldas'),
'CAQ' => t('Caquetá'),
'CAS' => t('Casanare'),
'CAU' => t('Cauca'),
'CES' => t('Cesar'),
'COR' => t('Córdoba'),
'CUN' => t('Cundinamarca'),
'CHO' => t('Chocó'),
'GUA' => t('Guainía'),
'GUV' => t('Guaviare'),
'HUI' => t('Huila'),
'LAG' => t('La Guajira'),
'MAG' => t('Magdalena'),
'MET' => t('Meta'),
'NAR' => t('Nariño'),
'NSA' => t('Norte de Santander'),
'PUT' => t('Putumayo'),
'QUI' => t('Quindío'),
'RIS' => t('Risaralda'),
'SAP' => t('San Andrés, Providencia y Santa Catalina'),
'SAN' => t('Santander'),
'SUC' => t('Sucre'),
'TOL' => t('Tolima'),
'VAC' => t('Valle del Cauca'),
'VAU' => t('Vaupés'),
'VID' => t('Vichada'),
'AMA' => 'Amazonas',
'ANT' => 'Antioquia',
'ARA' => 'Arauca',
'ATL' => 'Atlántico',
'BOL' => 'Bolívar',
'BOY' => 'Boyacá',
'CAL' => 'Caldas',
'CAQ' => 'Caquetá',
'CAS' => 'Casanare',
'CAU' => 'Cauca',
'CES' => 'Cesar',
'COR' => 'Córdoba',
'CUN' => 'Cundinamarca',
'CHO' => 'Chocó',
'GUA' => 'Guainía',
'GUV' => 'Guaviare',
'HUI' => 'Huila',
'LAG' => 'La Guajira',
'MAG' => 'Magdalena',
'MET' => 'Meta',
'NAR' => 'Nariño',
'NSA' => 'Norte de Santander',
'PUT' => 'Putumayo',
'QUI' => 'Quindío',
'RIS' => 'Risaralda',
'SAP' => 'San Andrés, Providencia y Santa Catalina',
'SAN' => 'Santander',
'SUC' => 'Sucre',
'TOL' => 'Tolima',
'VAC' => 'Valle del Cauca',
'VAU' => 'Vaupés',
'VID' => 'Vichada',
);
$administrative_areas['EE'] = array(
'37' => t('Harjumaa'),
'39' => t('Hiiumaa'),
'44' => t('Ida-Virumaa'),
'49' => t('Jõgevamaa'),
'51' => t('Järvamaa'),
'57' => t('Läänemaa'),
'59' => t('Lääne-Virumaa'),
'65' => t('Põlvamaa'),
'67' => t('Pärnumaa'),
'70' => t('Raplamaa'),
'74' => t('Saaremaa'),
'78' => t('Tartumaa'),
'82' => t('Valgamaa'),
'84' => t('Viljandimaa'),
'86' => t('Võrumaa'),
'37' => 'Harjumaa',
'39' => 'Hiiumaa',
'44' => 'Ida-Virumaa',
'49' => 'Jõgevamaa',
'51' => 'Järvamaa',
'57' => 'Läänemaa',
'59' => 'Lääne-Virumaa',
'65' => 'Põlvamaa',
'67' => 'Pärnumaa',
'70' => 'Raplamaa',
'74' => 'Saaremaa',
'78' => 'Tartumaa',
'82' => 'Valgamaa',
'84' => 'Viljandimaa',
'86' => 'Võrumaa',
);
$administrative_areas['EG'] = array(
'ALX' => t('Alexandria'),
@@ -235,58 +258,58 @@ function addressfield_get_administrative_areas($country_code) {
'LX' => t('Luxor'),
);
$administrative_areas['ES'] = array(
'C' => t("A Coruña"),
'VI' => t('Alava'),
'AB' => t('Albacete'),
'A' => t('Alicante'),
'AL' => t("Almería"),
'O' => t('Asturias'),
'AV' => t("Ávila"),
'BA' => t('Badajoz'),
'PM' => t('Baleares'),
'B' => t('Barcelona'),
'BU' => t('Burgos'),
'CC' => t("Cáceres"),
'CA' => t("Cádiz"),
'S' => t('Cantabria'),
'CS' => t("Castellón"),
'CE' => t('Ceuta'),
'CR' => t('Ciudad Real'),
'CO' => t("Córdoba"),
'CU' => t('Cuenca'),
'GI' => t('Gerona'),
'GR' => t('Granada'),
'GU' => t('Guadalajara'),
'SS' => t("Guipúzcoa"),
'H' => t('Huelva'),
'HU' => t('Huesca'),
'J' => t("Jaén"),
'LO' => t('La Rioja'),
'GC' => t('Las Palmas'),
'LE' => t("León"),
'L' => t("Lérida"),
'LU' => t('Lugo'),
'M' => t('Madrid'),
'MA' => t("Málaga"),
'ML' => t('Melilla'),
'MU' => t('Murcia'),
'NA' => t('Navarra'),
'OR' => t('Ourense'),
'P' => t('Palencia'),
'PO' => t('Pontevedra'),
'SA' => t('Salamanca'),
'TF' => t('Santa Cruz de Tenerife'),
'SG' => t('Segovia'),
'SE' => t('Sevilla'),
'SO' => t('Soria'),
'T' => t('Tarragona'),
'TE' => t('Teruel'),
'TO' => t('Toledo'),
'V' => t('Valencia'),
'VA' => t('Valladolid'),
'BI' => t('Vizcaya'),
'ZA' => t('Zamora'),
'Z' => t('Zaragoza'),
'C' => "A Coruña",
'VI' => 'Alava',
'AB' => 'Albacete',
'A' => 'Alicante',
'AL' => "Almería",
'O' => 'Asturias',
'AV' => "Ávila",
'BA' => 'Badajoz',
'PM' => 'Baleares',
'B' => 'Barcelona',
'BU' => 'Burgos',
'CC' => "Cáceres",
'CA' => "Cádiz",
'S' => 'Cantabria',
'CS' => "Castellón",
'CE' => 'Ceuta',
'CR' => 'Ciudad Real',
'CO' => "Córdoba",
'CU' => 'Cuenca',
'GI' => 'Girona',
'GR' => 'Granada',
'GU' => 'Guadalajara',
'SS' => "Guipúzcoa",
'H' => 'Huelva',
'HU' => 'Huesca',
'J' => "Jaén",
'LO' => 'La Rioja',
'GC' => 'Las Palmas',
'LE' => "León",
'L' => "Lleida",
'LU' => 'Lugo',
'M' => 'Madrid',
'MA' => "Málaga",
'ML' => 'Melilla',
'MU' => 'Murcia',
'NA' => 'Navarra',
'OR' => 'Ourense',
'P' => 'Palencia',
'PO' => 'Pontevedra',
'SA' => 'Salamanca',
'TF' => 'Santa Cruz de Tenerife',
'SG' => 'Segovia',
'SE' => 'Sevilla',
'SO' => 'Soria',
'T' => 'Tarragona',
'TE' => 'Teruel',
'TO' => 'Toledo',
'V' => 'Valencia',
'VA' => 'Valladolid',
'BI' => 'Vizcaya',
'ZA' => 'Zamora',
'Z' => 'Zaragoza',
);
$administrative_areas['HK'] = array(
// HK subdivisions have no ISO codes assigned.
@@ -330,57 +353,57 @@ function addressfield_get_administrative_areas($country_code) {
'SU' => t('Sumatera Utara'),
);
$administrative_areas['IE'] = array(
'CW' => t('Co Carlow'),
'CN' => t('Co Cavan'),
'CE' => t('Co Clare'),
'CO' => t('Co Cork'),
'DL' => t('Co Donegal'),
'D' => t('Co Dublin'),
'D1' => t('Dublin 1'),
'D2' => t('Dublin 2'),
'D3' => t('Dublin 3'),
'D4' => t('Dublin 4'),
'D5' => t('Dublin 5'),
'D6' => t('Dublin 6'),
'D6W' => t('Dublin 6w'),
'D7' => t('Dublin 7'),
'D8' => t('Dublin 8'),
'D9' => t('Dublin 9'),
'D10' => t('Dublin 10'),
'D11' => t('Dublin 11'),
'D12' => t('Dublin 12'),
'D13' => t('Dublin 13'),
'D14' => t('Dublin 14'),
'D15' => t('Dublin 15'),
'D16' => t('Dublin 16'),
'D17' => t('Dublin 17'),
'D18' => t('Dublin 18'),
'D19' => t('Dublin 19'),
'D20' => t('Dublin 20'),
'D21' => t('Dublin 21'),
'D22' => t('Dublin 22'),
'D23' => t('Dublin 23'),
'D24' => t('Dublin 24'),
'G' => t('Co Galway'),
'KY' => t('Co Kerry'),
'KE' => t('Co Kildare'),
'KK' => t('Co Kilkenny'),
'LS' => t('Co Laois'),
'LM' => t('Co Leitrim'),
'LK' => t('Co Limerick'),
'LD' => t('Co Longford'),
'LH' => t('Co Louth'),
'MO' => t('Co Mayo'),
'MH' => t('Co Meath'),
'MN' => t('Co Monaghan'),
'OY' => t('Co Offaly'),
'RN' => t('Co Roscommon'),
'SO' => t('Co Sligo'),
'TA' => t('Co Tipperary'),
'WD' => t('Co Waterford'),
'WH' => t('Co Westmeath'),
'WX' => t('Co Wexford'),
'WW' => t('Co Wicklow'),
'CW' => 'Co Carlow',
'CN' => 'Co Cavan',
'CE' => 'Co Clare',
'CO' => 'Co Cork',
'DL' => 'Co Donegal',
'D' => 'Co Dublin',
'D1' => 'Dublin 1',
'D2' => 'Dublin 2',
'D3' => 'Dublin 3',
'D4' => 'Dublin 4',
'D5' => 'Dublin 5',
'D6' => 'Dublin 6',
'D6W' => 'Dublin 6w',
'D7' => 'Dublin 7',
'D8' => 'Dublin 8',
'D9' => 'Dublin 9',
'D10' => 'Dublin 10',
'D11' => 'Dublin 11',
'D12' => 'Dublin 12',
'D13' => 'Dublin 13',
'D14' => 'Dublin 14',
'D15' => 'Dublin 15',
'D16' => 'Dublin 16',
'D17' => 'Dublin 17',
'D18' => 'Dublin 18',
'D19' => 'Dublin 19',
'D20' => 'Dublin 20',
'D21' => 'Dublin 21',
'D22' => 'Dublin 22',
'D23' => 'Dublin 23',
'D24' => 'Dublin 24',
'G' => 'Co Galway',
'KY' => 'Co Kerry',
'KE' => 'Co Kildare',
'KK' => 'Co Kilkenny',
'LS' => 'Co Laois',
'LM' => 'Co Leitrim',
'LK' => 'Co Limerick',
'LD' => 'Co Longford',
'LH' => 'Co Louth',
'MO' => 'Co Mayo',
'MH' => 'Co Meath',
'MN' => 'Co Monaghan',
'OY' => 'Co Offaly',
'RN' => 'Co Roscommon',
'SO' => 'Co Sligo',
'TA' => 'Co Tipperary',
'WD' => 'Co Waterford',
'WH' => 'Co Westmeath',
'WX' => 'Co Wexford',
'WW' => 'Co Wicklow',
);
$administrative_areas['IN'] = array(
'AP' => t('Andhra Pradesh'),
@@ -388,8 +411,6 @@ function addressfield_get_administrative_areas($country_code) {
'AS' => t('Assam'),
'BR' => t('Bihar'),
'CT' => t('Chhattisgarh'),
'DD' => t('Daman & Diu'),
'DN' => t('Dadra & Nagar Haveli'),
'GA' => t('Goa'),
'GJ' => t('Gujarat'),
'HP' => t('Himachal Pradesh'),
@@ -424,116 +445,116 @@ function addressfield_get_administrative_areas($country_code) {
'PY' => t('Puducherry'),
);
$administrative_areas['IT'] = array(
'AG' => t('Agrigento'),
'AL' => t('Alessandria'),
'AN' => t('Ancona'),
'AO' => t('Aosta'),
'AP' => t('Ascoli Piceno'),
'AQ' => t("L'Aquila"),
'AR' => t('Arezzo'),
'AT' => t('Asti'),
'AV' => t('Avellino'),
'BA' => t('Bari'),
'BG' => t('Bergamo'),
'BI' => t('Biella'),
'BL' => t('Belluno'),
'BN' => t('Benevento'),
'BO' => t('Bologna'),
'BR' => t('Brindisi'),
'BS' => t('Brescia'),
'BT' => t('Barletta-Andria-Trani'),
'BZ' => t('Bolzano/Bozen'),
'CA' => t('Cagliari'),
'CB' => t('Campobasso'),
'CE' => t('Caserta'),
'CH' => t('Chieti'),
'CI' => t('Carbonia-Iglesias'),
'CL' => t('Caltanissetta'),
'CN' => t('Cuneo'),
'CO' => t('Como'),
'CR' => t('Cremona'),
'CS' => t('Cosenza'),
'CT' => t('Catania'),
'CZ' => t('Catanzaro'),
'EN' => t('Enna'),
'FC' => t('Forlì-Cesena'),
'FE' => t('Ferrara'),
'FG' => t('Foggia'),
'FI' => t('Firenze'),
'FM' => t('Fermo'),
'FR' => t('Frosinone'),
'GE' => t('Genova'),
'GO' => t('Gorizia'),
'GR' => t('Grosseto'),
'IM' => t('Imperia'),
'IS' => t('Isernia'),
'KR' => t('Crotone'),
'LC' => t('Lecco'),
'LE' => t('Lecce'),
'LI' => t('Livorno'),
'LO' => t('Lodi'),
'LT' => t('Latina'),
'LU' => t('Lucca'),
'MB' => t('Monza e Brianza'),
'MC' => t('Macerata'),
'ME' => t('Messina'),
'MI' => t('Milano'),
'MN' => t('Mantova'),
'MO' => t('Modena'),
'MS' => t('Massa-Carrara'),
'MT' => t('Matera'),
'NA' => t('Napoli'),
'NO' => t('Novara'),
'NU' => t('Nuoro'),
'OG' => t('Ogliastra'),
'OR' => t('Oristano'),
'OT' => t('Olbia-Tempio'),
'PA' => t('Palermo'),
'PC' => t('Piacenza'),
'PD' => t('Padova'),
'PE' => t('Pescara'),
'PG' => t('Perugia'),
'PI' => t('Pisa'),
'PN' => t('Pordenone'),
'PO' => t('Prato'),
'PR' => t('Parma'),
'PT' => t('Pistoia'),
'PU' => t('Pesaro e Urbino'),
'PV' => t('Pavia'),
'PZ' => t('Potenza'),
'RA' => t('Ravenna'),
'RC' => t('Reggio Calabria'),
'RE' => t('Reggio Emilia'),
'RG' => t('Ragusa'),
'RI' => t('Rieti'),
'RM' => t('Roma'),
'RN' => t('Rimini'),
'RO' => t('Rovigo'),
'SA' => t('Salerno'),
'SI' => t('Siena'),
'SO' => t('Sondrio'),
'SP' => t('La Spezia'),
'SR' => t('Siracusa'),
'SS' => t('Sassari'),
'SV' => t('Savona'),
'TA' => t('Taranto'),
'TE' => t('Teramo'),
'TN' => t('Trento'),
'TO' => t('Torino'),
'TP' => t('Trapani'),
'TR' => t('Terni'),
'TS' => t('Trieste'),
'TV' => t('Treviso'),
'UD' => t('Udine'),
'VA' => t('Varese'),
'VB' => t('Verbano-Cusio-Ossola'),
'VC' => t('Vercelli'),
'VE' => t('Venezia'),
'VI' => t('Vicenza'),
'VR' => t('Verona'),
'VS' => t('Medio Campidano'),
'VT' => t('Viterbo'),
'VV' => t('Vibo Valentia'),
'AG' => 'Agrigento',
'AL' => 'Alessandria',
'AN' => 'Ancona',
'AO' => 'Aosta',
'AP' => 'Ascoli Piceno',
'AQ' => "L'Aquila",
'AR' => 'Arezzo',
'AT' => 'Asti',
'AV' => 'Avellino',
'BA' => 'Bari',
'BG' => 'Bergamo',
'BI' => 'Biella',
'BL' => 'Belluno',
'BN' => 'Benevento',
'BO' => 'Bologna',
'BR' => 'Brindisi',
'BS' => 'Brescia',
'BT' => 'Barletta-Andria-Trani',
'BZ' => 'Bolzano/Bozen',
'CA' => 'Cagliari',
'CB' => 'Campobasso',
'CE' => 'Caserta',
'CH' => 'Chieti',
'CI' => 'Carbonia-Iglesias',
'CL' => 'Caltanissetta',
'CN' => 'Cuneo',
'CO' => 'Como',
'CR' => 'Cremona',
'CS' => 'Cosenza',
'CT' => 'Catania',
'CZ' => 'Catanzaro',
'EN' => 'Enna',
'FC' => 'Forlì-Cesena',
'FE' => 'Ferrara',
'FG' => 'Foggia',
'FI' => 'Firenze',
'FM' => 'Fermo',
'FR' => 'Frosinone',
'GE' => 'Genova',
'GO' => 'Gorizia',
'GR' => 'Grosseto',
'IM' => 'Imperia',
'IS' => 'Isernia',
'KR' => 'Crotone',
'LC' => 'Lecco',
'LE' => 'Lecce',
'LI' => 'Livorno',
'LO' => 'Lodi',
'LT' => 'Latina',
'LU' => 'Lucca',
'MB' => 'Monza e Brianza',
'MC' => 'Macerata',
'ME' => 'Messina',
'MI' => 'Milano',
'MN' => 'Mantova',
'MO' => 'Modena',
'MS' => 'Massa-Carrara',
'MT' => 'Matera',
'NA' => 'Napoli',
'NO' => 'Novara',
'NU' => 'Nuoro',
'OG' => 'Ogliastra',
'OR' => 'Oristano',
'OT' => 'Olbia-Tempio',
'PA' => 'Palermo',
'PC' => 'Piacenza',
'PD' => 'Padova',
'PE' => 'Pescara',
'PG' => 'Perugia',
'PI' => 'Pisa',
'PN' => 'Pordenone',
'PO' => 'Prato',
'PR' => 'Parma',
'PT' => 'Pistoia',
'PU' => 'Pesaro e Urbino',
'PV' => 'Pavia',
'PZ' => 'Potenza',
'RA' => 'Ravenna',
'RC' => 'Reggio Calabria',
'RE' => 'Reggio Emilia',
'RG' => 'Ragusa',
'RI' => 'Rieti',
'RM' => 'Roma',
'RN' => 'Rimini',
'RO' => 'Rovigo',
'SA' => 'Salerno',
'SI' => 'Siena',
'SO' => 'Sondrio',
'SP' => 'La Spezia',
'SR' => 'Siracusa',
'SS' => 'Sassari',
'SV' => 'Savona',
'TA' => 'Taranto',
'TE' => 'Teramo',
'TN' => 'Trento',
'TO' => 'Torino',
'TP' => 'Trapani',
'TR' => 'Terni',
'TS' => 'Trieste',
'TV' => 'Treviso',
'UD' => 'Udine',
'VA' => 'Varese',
'VB' => 'Verbano-Cusio-Ossola',
'VC' => 'Vercelli',
'VE' => 'Venezia',
'VI' => 'Vicenza',
'VR' => 'Verona',
'VS' => 'Medio Campidano',
'VT' => 'Viterbo',
'VV' => 'Vibo Valentia',
);
$administrative_areas['JM'] = array(
'13' => 'Clarendon',
@@ -638,38 +659,38 @@ function addressfield_get_administrative_areas($country_code) {
'ZHA' => t('Zhambyl region'),
);
$administrative_areas['MX'] = array(
'AGU' => t('Aguascalientes'),
'BCN' => t('Baja California'),
'BCS' => t('Baja California Sur'),
'CAM' => t('Campeche'),
'COA' => t('Coahuila'),
'COL' => t('Colima'),
'CHP' => t('Chiapas'),
'CHH' => t('Chihuahua'),
'DIF' => t('Distrito Federal'),
'DUG' => t('Durango'),
'MEX' => t('Estado de México'),
'GUA' => t('Guanajuato'),
'GRO' => t('Guerrero'),
'HID' => t('Hidalgo'),
'JAL' => t('Jalisco'),
'MIC' => t('Michoacán'),
'MOR' => t('Morelos'),
'NAY' => t('Nayarit'),
'NLE' => t('Nuevo León'),
'OAX' => t('Oaxaca'),
'PUE' => t('Puebla'),
'QUE' => t('Queretaro'),
'ROO' => t('Quintana Roo'),
'SLP' => t('San Luis Potosí'),
'SIN' => t('Sinaloa'),
'SON' => t('Sonora'),
'TAB' => t('Tabasco'),
'TAM' => t('Tamaulipas'),
'TLA' => t('Tlaxcala'),
'VER' => t('Veracruz'),
'YUC' => t('Yucatán'),
'ZAC' => t('Zacatecas'),
'AGU' => 'Aguascalientes',
'BCN' => 'Baja California',
'BCS' => 'Baja California Sur',
'CAM' => 'Campeche',
'COA' => 'Coahuila',
'COL' => 'Colima',
'CHP' => 'Chiapas',
'CHH' => 'Chihuahua',
'DIF' => 'Distrito Federal',
'DUG' => 'Durango',
'MEX' => 'Estado de México',
'GUA' => 'Guanajuato',
'GRO' => 'Guerrero',
'HID' => 'Hidalgo',
'JAL' => 'Jalisco',
'MIC' => 'Michoacán',
'MOR' => 'Morelos',
'NAY' => 'Nayarit',
'NLE' => 'Nuevo León',
'OAX' => 'Oaxaca',
'PUE' => 'Puebla',
'QUE' => 'Queretaro',
'ROO' => 'Quintana Roo',
'SLP' => 'San Luis Potosí',
'SIN' => 'Sinaloa',
'SON' => 'Sonora',
'TAB' => 'Tabasco',
'TAM' => 'Tamaulipas',
'TLA' => 'Tlaxcala',
'VER' => 'Veracruz',
'YUC' => 'Yucatán',
'ZAC' => 'Zacatecas',
);
$administrative_areas['MY'] = array(
'01' => t('Johor'),
@@ -690,31 +711,31 @@ function addressfield_get_administrative_areas($country_code) {
'11' => t('Terengganu'),
);
$administrative_areas['PE'] = array(
'AMA' => t('Amazonas'),
'ANC' => t('Ancash'),
'APU' => t('Apurimac'),
'ARE' => t('Arequipa'),
'AYA' => t('Ayacucho'),
'CAJ' => t('Cajamarca'),
'CAL' => t('Callao'),
'CUS' => t('Cusco'),
'HUV' => t('Huancavelica'),
'HUC' => t('Huanuco'),
'ICA' => t('Ica'),
'JUN' => t('Junin'),
'LAL' => t('La Libertad'),
'LAM' => t('Lambayeque'),
'LIM' => t('Lima'),
'LOR' => t('Loreto'),
'MDD' => t('Madre de Dios'),
'MOQ' => t('Moquegua'),
'PAS' => t('Pasco'),
'PIU' => t('Piura'),
'PUN' => t('Puno'),
'SAM' => t('San Martin'),
'TAC' => t('Tacna'),
'TUM' => t('Tumbes'),
'UCA' => t('Ucayali'),
'AMA' => 'Amazonas',
'ANC' => 'Ancash',
'APU' => 'Apurimac',
'ARE' => 'Arequipa',
'AYA' => 'Ayacucho',
'CAJ' => 'Cajamarca',
'CAL' => 'Callao',
'CUS' => 'Cusco',
'HUV' => 'Huancavelica',
'HUC' => 'Huanuco',
'ICA' => 'Ica',
'JUN' => 'Junin',
'LAL' => 'La Libertad',
'LAM' => 'Lambayeque',
'LIM' => 'Lima',
'LOR' => 'Loreto',
'MDD' => 'Madre de Dios',
'MOQ' => 'Moquegua',
'PAS' => 'Pasco',
'PIU' => 'Piura',
'PUN' => 'Puno',
'SAM' => 'San Martin',
'TAC' => 'Tacna',
'TUM' => 'Tumbes',
'UCA' => 'Ucayali',
);
$administrative_areas['RU'] = array(
'MOW' => t('Moskva'),
@@ -918,7 +939,6 @@ function addressfield_get_administrative_areas($country_code) {
'21' => t('Zakarpats\'ka oblast'),
'23' => t('Zaporiz\'ka oblast'),
'26' => t('Ivano-Frankivs\'ka oblast'),
'30' => t('Kyiv city'),
'30' => t('Kiev Oblast'),
'35' => t('Kirovohrads\'ka oblast'),
'09' => t('Luhans\'ka oblast'),
@@ -1003,35 +1023,32 @@ function addressfield_get_administrative_areas($country_code) {
'VI' => t('Virgin Islands'),
);
$administrative_areas['VE'] = array(
'Z' => t('Amazonas'),
'B' => t('Anzoátegui'),
'C' => t('Apure'),
'D' => t('Aragua'),
'E' => t('Barinas'),
'F' => t('Bolívar'),
'G' => t('Carabobo'),
'H' => t('Cojedes'),
'Y' => t('Delta Amacuro'),
'W' => t('Dependencias Federales'),
'A' => t('Distrito Federal'),
'I' => t('Falcón'),
'J' => t('Guárico'),
'K' => t('Lara'),
'L' => t('Mérida'),
'M' => t('Miranda'),
'N' => t('Monagas'),
'O' => t('Nueva Esparta'),
'P' => t('Portuguesa'),
'R' => t('Sucre'),
'S' => t('Táchira'),
'T' => t('Trujillo'),
'X' => t('Vargas'),
'U' => t('Yaracuy'),
'V' => t('Zulia'),
'Z' => 'Amazonas',
'B' => 'Anzoátegui',
'C' => 'Apure',
'D' => 'Aragua',
'E' => 'Barinas',
'F' => 'Bolívar',
'G' => 'Carabobo',
'H' => 'Cojedes',
'Y' => 'Delta Amacuro',
'W' => 'Dependencias Federales',
'A' => 'Distrito Federal',
'I' => 'Falcón',
'J' => 'Guárico',
'K' => 'Lara',
'L' => 'Mérida',
'M' => 'Miranda',
'N' => 'Monagas',
'O' => 'Nueva Esparta',
'P' => 'Portuguesa',
'R' => 'Sucre',
'S' => 'Táchira',
'T' => 'Trujillo',
'X' => 'Vargas',
'U' => 'Yaracuy',
'V' => 'Zulia',
);
// Allow other modules to alter the administrative areas.
drupal_alter('addressfield_administrative_areas', $administrative_areas);
return isset($administrative_areas[$country_code]) ? $administrative_areas[$country_code] : null;
return $administrative_areas;
}
@@ -43,7 +43,6 @@ function _addressfield_sample_addresses() {
$fields = array();
if ($handle = @fopen("$filepath/addresses.txt",'r')) {
if (is_resource($handle)) {
$addresses = array();
while (($buffer = fgets($handle)) !== false) {
list($country, $administrative_area, $sub_administrative_area, $locality, $dependent_locality, $postal_code, $thoroughfare, $premise, $sub_premise) = explode("\t", $buffer);
$fields[] = array(
@@ -6,10 +6,10 @@
*/
/**
* Implements hook_feeds_node_processor_targets_alter().
* Implements hook_feeds_processor_targets_alter().
*/
function addressfield_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
function addressfield_feeds_processor_targets_alter(&$targets, $entity_type, $bundle) {
foreach (field_info_instances($entity_type, $bundle) as $name => $instance) {
$info = field_info_field($name);
if ($info['type'] == 'addressfield') {
foreach ($info['columns'] as $sub_field => $schema_info) {
@@ -34,7 +34,7 @@ function addressfield_feeds_processor_targets_alter(&$targets, $entity_type, $bu
* An entity object, for instance a node object.
* @param $target
* A string identifying the target on the node.
* @param $value
* @param $values
* The value to populate the target with.
*/
function addressfield_set_target($source, $entity, $target, $values) {
@@ -6,12 +6,13 @@ package = Fields
dependencies[] = ctools
files[] = addressfield.migrate.inc
files[] = views/addressfield_views_handler_field_administrative_area.inc
files[] = views/addressfield_views_handler_field_country.inc
files[] = views/addressfield_views_handler_filter_country.inc
; Information added by Drupal.org packaging script on 2015-04-23
version = "7.x-1.1"
; Information added by Drupal.org packaging script on 2015-10-07
version = "7.x-1.2"
core = "7.x"
project = "addressfield"
datestamp = "1429819382"
datestamp = "1444254070"
@@ -152,7 +152,7 @@ class MigrateAddressFieldHandler extends MigrateFieldHandler {
if ($value) {
if (isset($field_info['columns'][$column_key])) {
// Store the data in a seperate column.
// Store the data in a separate column.
$result[$column_key] = $value;
}
else {
@@ -534,7 +534,9 @@ function addressfield_field_widget_form(&$form, &$form_state, $field, $instance,
// $form_state['values'] is empty because of #limit_validation_errors, so
// $form_state['input'] needs to be used instead.
$parents = array_merge($element['#field_parents'], array($element['#field_name'], $langcode, $delta));
$input_address = drupal_array_get_nested_value($form_state['input'], $parents);
if (!empty($form_state['input'])) {
$input_address = drupal_array_get_nested_value($form_state['input'], $parents);
}
if (!empty($input_address)) {
$address = $input_address;
}
@@ -728,8 +730,6 @@ function addressfield_field_formatter_settings_summary($field, $instance, $view_
$display = $instance['display'][$view_mode];
$settings = $display['settings'];
$summary = '';
if ($settings['use_widget_handlers']) {
return t('Use widget configuration');
}
@@ -7,9 +7,9 @@ hidden = TRUE
dependencies[] = ctools
dependencies[] = addressfield
; Information added by Drupal.org packaging script on 2015-04-23
version = "7.x-1.1"
; Information added by Drupal.org packaging script on 2015-10-07
version = "7.x-1.2"
core = "7.x"
project = "addressfield"
datestamp = "1429819382"
datestamp = "1444254070"
@@ -3552,8 +3552,6 @@ function addressfield_form_ch_postal_code_validation($element, &$form_state, &$f
if (!empty($element['#value']) && (isset($data[$element['#value']]))) {
// Get the base #parents for this address form.
$base_parents = array_slice($element['#parents'], 0, -1);
$base_array_parents = array_slice($element['#array_parents'], 0, -2);
$city = $data[$element['#value']];
// Set the new values in the form.
@@ -7,7 +7,7 @@
*/
$plugin = array(
'title' => t('Make all fields optional (Not recommended)'),
'title' => t('Make all fields optional (No validation - unsuitable for postal purposes)'),
'format callback' => 'addressfield_format_address_optional',
'type' => 'address',
'weight' => 100,
@@ -83,7 +83,7 @@ function addressfield_format_address_generate(&$format, $address, $context = arr
'#tag' => 'div',
'#attributes' => array(
'class' => array('dependent-locality'),
'autocomplete' => '"address-level3',
'autocomplete' => 'address-level3',
),
// Most formats place this field in its own row.
'#suffix' => $clearfix,
@@ -97,7 +97,7 @@ function addressfield_format_address_generate(&$format, $address, $context = arr
'#prefix' => ' ',
'#attributes' => array(
'class' => array('locality'),
'autocomplete' => '"address-level2',
'autocomplete' => 'address-level2',
),
);
$format['locality_block']['administrative_area'] = array(
@@ -20,7 +20,7 @@ $plugin = array(
function addressfield_format_organisation_generate(&$format, $address) {
$format['organisation_block'] = array(
'#type' => 'addressfield_container',
'#attributes' => array('class' => array('addressfield-container-inline', 'name-block')),
'#attributes' => array('class' => array('addressfield-container-inline', 'organisation-block')),
'#weight' => -50,
// The addressfield is considered empty without a country, hide all fields
// until one is selected.
@@ -26,7 +26,7 @@ function addressfield_field_views_data($field) {
// Only expose these components as Views field handlers.
$implemented = array(
'country' => 'addressfield_views_handler_field_country',
'administrative_area' => 'views_handler_field',
'administrative_area' => 'addressfield_views_handler_field_administrative_area',
'sub_administrative_area' => 'views_handler_field',
'dependent_locality' => 'views_handler_field',
'locality' => 'views_handler_field',
@@ -0,0 +1,48 @@
<?php
/**
* Defines a field handler that can display the administrative area name
* instead of the code.
*/
class addressfield_views_handler_field_administrative_area extends views_handler_field {
function query() {
parent::query();
$this->country_alias = $this->query->add_field($this->table_alias, $this->definition['field_name'] . '_country');
}
function option_definition() {
$options = parent::option_definition();
$options['display_name'] = array('default' => TRUE);
return $options;
}
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$form['display_name'] = array(
'#type' => 'checkbox',
'#title' => t('Display the name of administrative area instead of the code.'),
'#default_value' => $this->options['display_name'],
);
}
function get_value($values, $field = NULL) {
$value = parent::get_value($values, $field);
// If we have a value for the field, look for the administrative area name in the
// Address Field options list array if specified.
if (!empty($value) && !empty($this->options['display_name'])) {
module_load_include('inc', 'addressfield', 'addressfield.administrative_areas');
$country = $values->{$this->country_alias};
$areas = addressfield_get_administrative_areas($country);
if (!empty($areas[$value])) {
$value = $areas[$value];
}
}
return $value;
}
}
@@ -0,0 +1,4 @@
*.patch
*.diff
.idea/
.idea/*
@@ -15,8 +15,14 @@ function date_devel_generate($entity, $field, $instance, $bundle) {
$entity_field = array();
if (isset($instance['widget']['settings']['year_range'])) {
$split = explode(':', $instance['widget']['settings']['year_range']);
$back = str_replace('-', '', $split[0]);
$forward = str_replace('+', '', $split[1]);
// Determine how much to go back and forward depending on whether a relative
// number of years (with - or + sign) or an absolute year is given.
$back = strpos($split[0], '-') === 0
? str_replace('-', '', $split[0])
: date_format(date_now(), 'Y') - $split[0];
$forward = strpos($split[1], '+') === 0
? str_replace('+', '', $split[1])
: $split[1] - date_format(date_now(), 'Y');
}
else {
$back = 2;
@@ -61,9 +67,11 @@ function date_devel_generate($entity, $field, $instance, $bundle) {
case 'date':
$format = DATE_FORMAT_ISO;
break;
case 'datestamp':
$format = DATE_FORMAT_UNIX;
break;
case 'datetime':
$format = DATE_FORMAT_DATETIME;
break;
@@ -19,6 +19,7 @@ function date_field_formatter_info() {
'multiple_from' => '',
'multiple_to' => '',
'fromto' => 'both',
'show_remaining_days' => FALSE,
),
),
'format_interval' => array(
@@ -48,6 +49,7 @@ function date_field_formatter_settings_form($field, $instance, $view_mode, $form
case 'format_interval':
$form = date_interval_formatter_settings_form($field, $instance, $view_mode, $form, $form_state);
break;
default:
$form = date_default_formatter_settings_form($field, $instance, $view_mode, $form, $form_state);
break;
@@ -72,6 +74,7 @@ function date_field_formatter_settings_summary($field, $instance, $view_mode) {
case 'format_interval':
$summary = date_interval_formatter_settings_summary($field, $instance, $view_mode);
break;
default:
$summary = date_default_formatter_settings_summary($field, $instance, $view_mode);
break;
@@ -169,11 +172,16 @@ function date_field_formatter_view($entity_type, $entity, $field, $instance, $la
$element[$delta] = array('#markup' => $item['value']);
}
else {
$element[$delta] = array('#markup' => t('!start-date to !end-date', array('!start-date' => $item['value'], '!end-date' => $item['value2'])));
$element[$delta] = array(
'#markup' => t('!start-date to !end-date', array(
'!start-date' => $item['value'],
'!end-date' => $item['value2']
)));
}
}
}
break;
case 'format_interval':
foreach ($items as $delta => $item) {
if (!empty($entity->date_id) && !in_array($delta, $selected_deltas)) {
@@ -188,6 +196,7 @@ function date_field_formatter_view($entity_type, $entity, $field, $instance, $la
}
}
break;
default:
foreach ($items as $delta => $item) {
if (!empty($entity->date_id) && !in_array($delta, $selected_deltas)) {
@@ -198,6 +207,7 @@ function date_field_formatter_view($entity_type, $entity, $field, $instance, $la
$variables['item'] = $item;
$variables['dates'] = date_formatter_process($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display);
$variables['attributes'] = !empty($rdf_mapping) ? rdf_rdfa_attributes($rdf_mapping, $item['value']) : array();
$variables['show_remaining_days'] = $display['settings']['show_remaining_days'];
$output = theme('date_display_combination', $variables);
if (!empty($output)) {
$element[$delta] = array('#markup' => $output);
@@ -231,10 +241,11 @@ function date_field_is_empty($item, $field) {
* Implements hook_field_info().
*/
function date_field_info() {
$granularity = array('year', 'month', 'day', 'hour', 'minute');
$settings = array(
'settings' => array(
'todate' => '',
'granularity' => drupal_map_assoc(array('year', 'month', 'day', 'hour', 'minute')),
'granularity' => drupal_map_assoc($granularity),
'tz_handling' => 'site',
'timezone_db' => 'UTC',
),
@@ -250,26 +261,26 @@ function date_field_info() {
);
return array(
'datetime' => array(
'label' => 'Date',
'label' => t('Date'),
'description' => t('Store a date in the database as a datetime field, recommended for complete dates and times that may need timezone conversion.'),
'default_widget' => 'date_select',
'default_formatter' => 'date_default',
'default_token_formatter' => 'date_plain',
) + $settings,
) + $settings,
'date' => array(
'label' => 'Date (ISO format)',
'label' => t('Date (ISO format)'),
'description' => t('Store a date in the database as an ISO date, recommended for historical or partial dates.'),
'default_widget' => 'date_select',
'default_formatter' => 'date_default',
'default_token_formatter' => 'date_plain',
) + $settings,
) + $settings,
'datestamp' => array(
'label' => 'Date (Unix timestamp)',
'label' => t('Date (Unix timestamp)'),
'description' => t('Store a date in the database as a timestamp, deprecated format to support legacy data.'),
'default_widget' => 'date_select',
'default_formatter' => 'date_default',
'default_token_formatter' => 'date_plain',
) + $settings,
) + $settings,
);
}
@@ -294,18 +305,18 @@ function date_field_widget_info() {
$info = array(
'date_select' => array(
'label' => t('Select list'),
'label' => t('Select list'),
'field types' => array('date', 'datestamp', 'datetime'),
) + $settings,
'date_text' => array(
'label' => t('Text field'),
'label' => t('Text field'),
'field types' => array('date', 'datestamp', 'datetime'),
) + $settings,
) + $settings,
);
if (module_exists('date_popup')) {
$info['date_popup'] = array(
'label' => t('Pop-up calendar'),
'label' => t('Pop-up calendar'),
'field types' => array('date', 'datestamp', 'datetime'),
) + $settings;
}
@@ -11,10 +11,12 @@ files[] = tests/date_field.test
files[] = tests/date_migrate.test
files[] = tests/date_validation.test
files[] = tests/date_timezone.test
files[] = tests/date_views_pager.test
files[] = tests/date_views_popup.test
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -19,6 +19,7 @@ function date_field_schema($field) {
'views' => TRUE,
);
break;
case 'datetime':
$db_columns['value'] = array(
'type' => 'datetime',
@@ -31,6 +32,7 @@ function date_field_schema($field) {
'views' => TRUE,
);
break;
default:
$db_columns['value'] = array(
'type' => 'varchar',
@@ -66,7 +68,12 @@ function date_field_schema($field) {
'views' => FALSE,
);
if (!empty($field['settings']['todate'])) {
$db_columns['offset2'] = array('type' => 'int', 'not null' => FALSE, 'sortable' => TRUE, 'views' => FALSE);
$db_columns['offset2'] = array(
'type' => 'int',
'not null' => FALSE,
'sortable' => TRUE,
'views' => FALSE
);
}
}
if (isset($field['settings']['repeat']) && $field['settings']['repeat'] == 1) {
@@ -88,8 +95,9 @@ function date_update_last_removed() {
}
/**
* Get rid of the individual formatters for each format type,
* these are now settings in the default formatter.
* Get rid of the individual formatters for each format type.
*
* These are now settings in the default formatter.
*/
function date_update_7000() {
$instances = field_info_instances();
@@ -115,8 +123,9 @@ function date_update_7000() {
}
/**
* Get rid of the separate widgets for repeating dates. The code now handles
* repeating dates correctly using the regular widgets.
* Get rid of the separate widgets for repeating dates.
*
* The code now handles repeating dates correctly using the regular widgets.
*/
function date_update_7001() {
$query = db_select('field_config_instance', 'fci', array('fetch' => PDO::FETCH_ASSOC));
@@ -127,7 +136,11 @@ function date_update_7001() {
foreach ($results as $record) {
$instance = unserialize($record['data']);
if (in_array($instance['widget']['type'], array('date_popup_repeat', 'date_text_repeat', 'date_select_repeat'))) {
if (in_array($instance['widget']['type'], array(
'date_popup_repeat',
'date_text_repeat',
'date_select_repeat'
))) {
$instance['widget']['type'] = str_replace('_repeat', '', $instance['widget']['type']);
db_update('field_config_instance')
->fields(array(
@@ -191,4 +204,3 @@ function date_update_7004() {
field_cache_clear();
drupal_set_message(t('Date text widgets have been updated to use an increment of 1.'));
}
@@ -27,7 +27,7 @@ Drupal.date.EndDateHandler = function (widget) {
this.$widget = $(widget);
this.$start = this.$widget.find('.form-type-date-select[class$=value]');
this.$end = this.$widget.find('.form-type-date-select[class$=value2]');
if (this.$end.length == 0) {
if (this.$end.length === 0) {
return;
}
this.initializeSelects();
@@ -68,7 +68,7 @@ Drupal.date.EndDateHandler.prototype.endDateIsBlank = function () {
var id;
for (id in this.selects) {
if (this.selects.hasOwnProperty(id)) {
if (this.selects[id].end.val() != '') {
if (this.selects[id].end.val() !== '') {
return false;
}
}
@@ -40,7 +40,7 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
* @return array
* An array of the defined variables in this scope.
*/
static function arguments($timezone = 'UTC', $timezone_db = 'UTC', $rrule = NULL, $language = NULL) {
public static function arguments($timezone = 'UTC', $timezone_db = 'UTC', $rrule = NULL, $language = NULL) {
return get_defined_vars();
}
@@ -129,6 +129,7 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
// timestamp for 'now'.
if (empty($from)) {
$return[$language][$delta]['value'] = NULL;
$return[$language][$delta]['timezone'] = NULL;
if (!empty($field_info['settings']['todate'])) {
$return[$language][$delta]['value2'] = NULL;
}
@@ -151,6 +152,7 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
case 'datestamp':
// Already done.
break;
case 'datetime':
// YYYY-MM-DD HH:MM:SS.
$from = format_date($from, 'custom', 'Y-m-d H:i:s', $timezone);
@@ -158,6 +160,7 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
$to = format_date($to, 'custom', 'Y-m-d H:i:s', $timezone);
}
break;
case 'date':
// ISO date: YYYY-MM-DDTHH:MM:SS.
$from = format_date($from, 'custom', 'Y-m-d\TH:i:s', $timezone);
@@ -165,6 +168,7 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
$to = format_date($to, 'custom', 'Y-m-d\TH:i:s', $timezone);
}
break;
default:
break;
}
@@ -173,12 +177,17 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
// created.
if (function_exists('date_repeat_build_dates') && !empty($field_info['settings']['repeat']) && $rrule) {
include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'date_api') . '/date_api_ical.inc';
$item = array('value' => $from, 'value2' => $to, 'timezone' => $timezone);
$item = array(
'value' => $from,
'value2' => $to,
'timezone' => $timezone,
);
// Can be de-uglified when http://drupal.org/node/1159404 is committed.
$return[$language] = date_repeat_build_dates(NULL, date_ical_parse_rrule($field_info, $rrule), $field_info, $item);
}
else {
$return[$language][$delta]['value'] = $from;
$return[$language][$delta]['timezone'] = $timezone;
if (!empty($to)) {
$return[$language][$delta]['value2'] = $to;
}
@@ -190,6 +199,9 @@ class DateMigrateFieldHandler extends MigrateFieldHandler {
return $return;
}
/**
* {@inheritdoc}
*/
public function fields($migration = NULL) {
return array(
'timezone' => t('Timezone'),
@@ -1,8 +1,10 @@
<?php
/**
* @file
* Defines date/time field types.
*/
module_load_include('theme', 'date', 'date');
module_load_include('inc', 'date', 'date.field');
module_load_include('inc', 'date', 'date_elements');
@@ -15,6 +17,7 @@ function date_get_entity_bundle($entity_type, $entity) {
case 'field_collection_item':
$bundle = $entity->field_name;
break;
default:
$bundle = field_extract_bundle($entity_type, $entity);
break;
@@ -40,13 +43,20 @@ function date_default_format($type) {
* Wrapper function around each of the widget types for creating a date object.
*/
function date_input_date($field, $instance, $element, $input) {
// Trim extra spacing off user input of text fields.
if (isset($input['date'])) {
$input['date'] = trim($input['date']);
}
switch ($instance['widget']['type']) {
case 'date_text':
$function = 'date_text_input_date';
break;
case 'date_popup':
$function = 'date_popup_input_date';
break;
default:
$function = 'date_select_input_date';
}
@@ -66,6 +76,7 @@ function date_theme() {
);
$themes = array(
'date_combo' => $base + array('render element' => 'element'),
'date_form_element' => $base + array('render element' => 'element'),
'date_text_parts' => $base + array('render element' => 'element'),
'date' => $base + array('render element' => 'element'),
'date_display_single' => $base + array(
@@ -97,7 +108,13 @@ function date_theme() {
'add_rdf' => NULL,
'microdata' => NULL,
'add_microdata' => NULL,
)),
),
),
'date_display_remaining' => $base + array(
'variables' => array(
'remaining_days' => NULL,
),
),
'date_display_combination' => $base + array(
'variables' => array(
'entity_type' => NULL,
@@ -130,7 +147,7 @@ function date_theme() {
'attributes' => array(),
'rdf_mapping' => NULL,
'add_rdf' => NULL,
),
),
),
);
@@ -209,8 +226,10 @@ function date_formatter_process($formatter, $entity_type, $entity, $field, $inst
$settings = $display['settings'];
$field_name = $field['field_name'];
$format = date_formatter_format($formatter, $settings, $granularity, $langcode);
$timezone = isset($item['timezone']) ? $item['timezone'] : '';
$timezone = date_get_timezone($field['settings']['tz_handling'], $timezone);
if (!isset($field['settings']['tz_handling']) || $field['settings']['tz_handling'] !== 'utc') {
$timezone = isset($item['timezone']) ? $item['timezone'] : '';
$timezone = date_get_timezone($field['settings']['tz_handling'], $timezone);
}
$timezone_db = date_get_timezone_db($field['settings']['tz_handling']);
$db_format = date_type_format($field['type']);
$process = date_process_values($field);
@@ -246,10 +265,10 @@ function date_formatter_process($formatter, $entity_type, $entity, $field, $inst
$dates[$processed]['formatted_iso'] = date_format_date($date, 'custom', 'c');
if (is_object($date)) {
if ($format == 'format_interval') {
$dates[$processed]['interval'] = date_format_interval($date);
$dates[$processed]['interval'] = date_format_interval($date);
}
elseif ($format == 'format_calendar_day') {
$dates[$processed]['calendar_day'] = date_format_calendar_day($date);
$dates[$processed]['calendar_day'] = date_format_calendar_day($date);
}
elseif ($format == 'U' || $format == 'r' || $format == 'c') {
$dates[$processed]['formatted'] = date_format_date($date, 'custom', $format);
@@ -258,10 +277,11 @@ function date_formatter_process($formatter, $entity_type, $entity, $field, $inst
$dates[$processed]['formatted_timezone'] = '';
}
elseif (!empty($format)) {
$dates[$processed]['formatted'] = date_format_date($date, 'custom', $format);
$dates[$processed]['formatted_date'] = date_format_date($date, 'custom', date_limit_format($format, array('year', 'month', 'day')));
$dates[$processed]['formatted_time'] = date_format_date($date, 'custom', date_limit_format($format, array('hour', 'minute', 'second')));
$dates[$processed]['formatted_timezone'] = date_format_date($date, 'custom', date_limit_format($format, array('timezone')));
$formats = _get_custom_date_format($date, $format);
$dates[$processed]['formatted'] = $formats['formatted'];
$dates[$processed]['formatted_date'] = $formats['date'];
$dates[$processed]['formatted_time'] = $formats['time'];
$dates[$processed]['formatted_timezone'] = $formats['zone'];
}
}
}
@@ -288,6 +308,30 @@ function date_formatter_process($formatter, $entity_type, $entity, $field, $inst
return $dates;
}
/**
* Get a custom date format.
*/
function _get_custom_date_format($date, $format) {
$custom = array();
$custom['granularities'] = array(
'date' => array('year', 'month', 'day'),
'time' => array('hour', 'minute', 'second'),
'zone' => array('timezone'),
);
$custom['limits'] = array(
'date' => date_limit_format($format, $custom['granularities']['date']),
'time' => date_limit_format($format, $custom['granularities']['time']),
'zone' => date_limit_format($format, $custom['granularities']['zone']),
);
return array(
'formatted' => date_format_date($date, 'custom', $format),
'date' => date_format_date($date, 'custom', $custom['limits']['date']),
'time' => date_format_date($date, 'custom', $custom['limits']['time']),
'zone' => date_format_date($date, 'custom', $custom['limits']['zone']),
);
}
/**
* Retrieves the granularity for a field.
*
@@ -301,14 +345,14 @@ function date_formatter_process($formatter, $entity_type, $entity, $field, $inst
*/
function date_granularity($field) {
if (!is_array($field) || !is_array($field['settings']['granularity'])) {
$field['settings']['granularity'] = drupal_map_assoc(array('year', 'month', 'day'));
$granularity = drupal_map_assoc(array('year', 'month', 'day'));
$field['settings']['granularity'] = $granularity;
}
return array_values(array_filter($field['settings']['granularity']));
}
/**
* Helper function to create an array of the date values in a
* field that need to be processed.
* Helper function to create an array of the date values in a field that need to be processed.
*/
function date_process_values($field) {
return $field['settings']['todate'] ? array('value', 'value2') : array('value');
@@ -394,10 +438,10 @@ function date_formatter_format($formatter, $settings, $granularity = array(), $l
switch ($formatter) {
case 'format_interval':
return 'format_interval';
break;
case 'date_plain':
return 'date_plain';
break;
default:
$format = date_format_type_format($format_type, $langcode);
break;
@@ -410,6 +454,7 @@ function date_formatter_format($formatter, $settings, $granularity = array(), $l
/**
* Helper function to get the right format for a format type.
*
* Checks for locale-based format first.
*/
function date_format_type_format($format_type, $langcode = NULL) {
@@ -432,27 +477,30 @@ function date_format_type_format($format_type, $langcode = NULL) {
case 'short':
$default = 'm/d/Y - H:i';
break;
case 'long':
$default = 'l, F j, Y - H:i';
break;
// If it's not one of the core date types and isn't stored in the
// database, we'll fall back on using the same default format as the
// 'medium' type.
case 'medium':
default:
// @todo: If a non-core module provides a date type and does not
// variable_set() a default for it, the default assumed here may
// not be correct (since the default format used by 'medium' may
// not even be one of the allowed formats for the date type in
// question). To fix this properly, we should really call
// system_get_date_formats($format_type) and take the first
// format from that list as the default. However, this function
// is called often (on many different page requests), so calling
// system_get_date_formats() from here would be a performance hit
// since that function writes several records to the database
// during each page request that calls it.
// variable_set() a default for it, the default assumed here may
// not be correct (since the default format used by 'medium' may
// not even be one of the allowed formats for the date type in
// question). To fix this properly, we should really call
// system_get_date_formats($format_type) and take the first
// format from that list as the default. However, this function
// is called often (on many different page requests), so calling
// system_get_date_formats() from here would be a performance hit
// since that function writes several records to the database
// during each page request that calls it.
$default = 'D, m/d/Y - H:i';
break;
}
$format = variable_get('date_format_' . $format_type, $default);
}
@@ -506,7 +554,7 @@ function date_prepare_entity($formatter, $entity_type, $entity, $field, $instanc
elseif ((!empty($max_count) && is_numeric($max_count) && $count >= $max_count) ||
(!empty($value['value']) && $value['value'] < $start) ||
(!empty($value['value2']) && $value['value2'] > $end)) {
unset($entity->{$field_name}[$langcode][$delta]);
unset($entity->{$field_name}[$langcode][$delta]);
}
else {
$count++;
@@ -647,7 +695,7 @@ function date_entity_metadata_field_setter(&$entity, $name, $value, $langcode, $
}
/**
* Auto creation callback for fields which contain two date values in one
* Auto creation callback for fields which contain two date values in one.
*/
function date_entity_metadata_struct_create($name, $property_info) {
return array(
@@ -658,10 +706,10 @@ function date_entity_metadata_struct_create($name, $property_info) {
/**
* Callback for setting an individual field value if a to-date may be there too.
*
* Based on entity_property_verbatim_set().
*
* The passed in unix timestamp (UTC) is converted to the right value and
* format dependent on the field.
* The passed in unix timestamp (UTC) is converted to the right value and format dependent on the field.
*
* $name is either 'value' or 'value2'.
*/
@@ -683,9 +731,9 @@ function date_entity_metadata_struct_setter(&$item, $name, $value, $langcode, $t
}
/**
* Duplicate functionality of what is now date_all_day_field() in
* the Date All Day module. Copy left here to avoid breaking other
* modules that use this function.
* Duplicate functionality of what is now date_all_day_field() in the Date All Day module.
*
* Copy left here to avoid breaking other modules that use this function.
*
* DEPRECATED!, will be removed at some time in the future.
*/
@@ -759,7 +807,7 @@ function date_field_widget_properties_alter(&$widget, $context) {
$entity = $context['entity'];
$info = entity_get_info($entity_type);
$id = $info['entity keys']['id'];
$widget['is_new']= FALSE;
$widget['is_new'] = FALSE;
if (empty($entity->$id)) {
$widget['is_new'] = TRUE;
}
@@ -77,6 +77,7 @@ function theme_date_display_combination($variables) {
$microdata = $variables['microdata'];
$add_microdata = $variables['add_microdata'];
$precision = date_granularity_precision($field['settings']['granularity']);
$show_remaining_days = $variables['show_remaining_days'];
$output = '';
@@ -121,10 +122,12 @@ function theme_date_display_combination($variables) {
$date1 = $dates['value']['formatted'];
$date2 = $date1;
break;
case 'value2':
$date2 = $dates['value2']['formatted'];
$date1 = $date2;
break;
default:
$date1 = $dates['value']['formatted'];
$date2 = $dates['value2']['formatted'];
@@ -151,6 +154,20 @@ function theme_date_display_combination($variables) {
$has_time_string = FALSE;
}
// Check remaining days.
$show_remaining_days = '';
if (!empty($variables['show_remaining_days'])) {
$remaining_days = floor((strtotime($variables['dates']['value']['formatted_iso'])
- strtotime('now')) / (24 * 3600));
// Show remaining days only for future events.
if ($remaining_days >= 0) {
$show_remaining_days = theme('date_display_remaining', array(
'remaining_days' => $remaining_days,
));
}
}
// No date values, display nothing.
if (empty($date1) && empty($date2)) {
$output .= '';
@@ -167,6 +184,7 @@ function theme_date_display_combination($variables) {
'microdata' => $microdata,
'add_microdata' => $add_microdata,
'dates' => $dates,
'show_remaining_days' => $show_remaining_days,
));
}
// Same day, different times, don't repeat the date but show both Start and
@@ -186,6 +204,7 @@ function theme_date_display_combination($variables) {
'microdata' => $microdata,
'add_microdata' => $add_microdata,
'dates' => $dates,
'show_remaining_days' => $show_remaining_days,
));
$replaced = str_replace($time1, $time, $date1);
$output .= theme('date_display_single', array(
@@ -209,6 +228,7 @@ function theme_date_display_combination($variables) {
'microdata' => $microdata,
'add_microdata' => $add_microdata,
'dates' => $dates,
'show_remaining_days' => $show_remaining_days,
));
}
@@ -236,12 +256,12 @@ function template_preprocess_date_display_single(&$variables) {
// Because the Entity API integration for Date has a variable data
// structure depending on whether there is an end value, the attributes
// could be attached to the field or to the value property.
if(!empty($variables['microdata']['#attributes']['itemprop'])) {
if (!empty($variables['microdata']['#attributes']['itemprop'])) {
$variables['microdata']['value']['#attributes'] = $variables['microdata']['#attributes'];
}
// Add the machine readable time using the content attribute.
if(!empty($variables['microdata']['value']['#attributes'])) {
if (!empty($variables['microdata']['value']['#attributes'])) {
$variables['microdata']['value']['#attributes']['content'] = $variables['dates']['value']['formatted_iso'];
}
else {
@@ -257,6 +277,7 @@ function theme_date_display_single($variables) {
$date = $variables['date'];
$timezone = $variables['timezone'];
$attributes = $variables['attributes'];
$show_remaining_days = isset($variables['show_remaining_days']) ? $variables['show_remaining_days'] : '';
// Wrap the result with the attributes.
$output = '<span class="date-display-single"' . drupal_attributes($attributes) . '>' . $date . $timezone . '</span>';
@@ -265,7 +286,8 @@ function theme_date_display_single($variables) {
$output .= '<meta' . drupal_attributes($variables['microdata']['value']['#attributes']) . '/>';
}
return $output;
// Add remaining message and return.
return $output . $show_remaining_days;
}
/**
@@ -314,6 +336,7 @@ function theme_date_display_range($variables) {
$timezone = $variables['timezone'];
$attributes_start = $variables['attributes_start'];
$attributes_end = $variables['attributes_end'];
$show_remaining_days = $variables['show_remaining_days'];
$start_date = '<span class="date-display-start"' . drupal_attributes($attributes_start) . '>' . $date1 . '</span>';
$end_date = '<span class="date-display-end"' . drupal_attributes($attributes_end) . '>' . $date2 . $timezone . '</span>';
@@ -326,10 +349,13 @@ function theme_date_display_range($variables) {
}
// Wrap the result with the attributes.
return t('!start-date to !end-date', array(
$output = '<div class="date-display-range">' . t('!start-date to !end-date', array(
'!start-date' => $start_date,
'!end-date' => $end_date,
));
)) . '</div>';
// Add remaining message and return.
return $output . $show_remaining_days;
}
/**
@@ -375,7 +401,7 @@ function theme_date_combo($variables) {
'#title' => field_filter_xss(t($element['#title'])) . ' ' . ($element['#delta'] > 0 ? intval($element['#delta'] + 1) : ''),
'#value' => '',
'#description' => !empty($element['#fieldset_description']) ? $element['#fieldset_description'] : '',
'#attributes' => array(),
'#attributes' => array('class' => array('date-combo')),
'#children' => $element['#children'],
);
// Add marker to required date fields.
@@ -396,7 +422,11 @@ function theme_date_text_parts($variables) {
$rows[] = drupal_render($element[$key]);
}
else {
$rows[] = array($part, drupal_render($element[$key][0]), drupal_render($element[$key][1]));
$rows[] = array(
$part,
drupal_render($element[$key][0]),
drupal_render($element[$key][1]),
);
}
}
if ($element['year']['#type'] == 'hidden') {
@@ -408,4 +438,49 @@ function theme_date_text_parts($variables) {
}
}
/**
* Render a date combo as a form element.
*/
function theme_date_form_element($variables) {
$element = &$variables['element'];
// Detect whether element is multiline.
$count = preg_match_all('`<(?:div|span)\b[^>]* class="[^"]*\b(?:date-no-float|date-clear)\b`', $element['#children'], $matches, PREG_OFFSET_CAPTURE);
$multiline = FALSE;
if ($count > 1) {
$multiline = TRUE;
}
elseif ($count) {
$before = substr($element['#children'], 0, $matches[0][0][1]);
if (preg_match('`<(?:div|span)\b[^>]* class="[^"]*\bdate-float\b`', $before)) {
$multiline = TRUE;
}
}
// Detect if there is more than one subfield.
$count = count(explode('<label', $element['#children'])) - 1;
if ($count == 1) {
$element['#title_display'] = 'none';
}
// Wrap children with a div and add an extra class if element is multiline.
$element['#children'] = '<div class="date-form-element-content'. ($multiline ? ' date-form-element-content-multiline' : '') .'">'. $element['#children'] .'</div>';
return theme('form_element', $variables);
}
/**
* Returns HTML for remaining message.
*/
function theme_date_display_remaining($variables) {
$remaining_days = $variables['remaining_days'];
$output = '';
$show_remaining_text = t('The upcoming date less then 1 day.');
if ($remaining_days) {
$show_remaining_text = format_plural($remaining_days, 'To event remaining 1 day', 'To event remaining @count days');
}
return '<div class="date-display-remaining"><span class="date-display-remaining">' . $show_remaining_text . '</span></div>';
}
/** @} End of addtogroup themeable */
@@ -74,6 +74,12 @@ function date_default_formatter_settings_form($field, $instance, $view_mode, $fo
'#description' => t('Identify specific start and/or end dates in the format YYYY-MM-DDTHH:MM:SS, or leave blank for all available dates.'),
);
$form['show_remaining_days'] = array(
'#title' => t('Show remaining days'),
'#type' => 'checkbox',
'#default_value' => $settings['show_remaining_days'],
'#weight' => 0,
);
return $form;
}
@@ -127,9 +133,11 @@ function date_default_formatter_settings_summary($field, $instance, $view_mode)
case 'date_plain':
$format = t('Plain');
break;
case 'format_interval':
$format = t('Interval');
break;
default:
if (!empty($format_types[$settings['format_type']])) {
$format = $format_types[$settings['format_type']];
@@ -148,7 +156,9 @@ function date_default_formatter_settings_summary($field, $instance, $view_mode)
'value' => t('Display Start date only'),
'value2' => t('Display End date only'),
);
$summary[] = $options[$settings['fromto']];
if (isset($options[$settings['fromto']])) {
$summary[] = $options[$settings['fromto']];
}
}
if (array_key_exists('multiple_number', $settings) && !empty($field['cardinality'])) {
@@ -159,6 +169,10 @@ function date_default_formatter_settings_summary($field, $instance, $view_mode)
));
}
if (array_key_exists('show_remaining_days', $settings)) {
$summary[] = t('Show remaining days: @value', array('@value' => ($settings['show_remaining_days'] ? 'yes' : 'no')));
}
return $summary;
}
@@ -191,7 +205,11 @@ function _date_field_instance_settings_form($field, $instance) {
'#type' => 'select',
'#title' => t('Default date'),
'#default_value' => $settings['default_value'],
'#options' => array('blank' => t('No default value'), 'now' => t('Now'), 'strtotime' => t('Relative')),
'#options' => array(
'blank' => t('No default value'),
'now' => t('Now'),
'strtotime' => t('Relative'),
),
'#weight' => 1,
'#fieldset' => 'default_values',
);
@@ -204,8 +222,11 @@ function _date_field_instance_settings_form($field, $instance) {
'#default_value' => $settings['default_value_code'],
'#states' => array(
'visible' => array(
':input[name="instance[settings][default_value]"]' => array('value' => 'strtotime')),
':input[name="instance[settings][default_value]"]' => array(
'value' => 'strtotime',
),
),
),
'#weight' => 1.1,
'#fieldset' => 'default_values',
);
@@ -213,7 +234,12 @@ function _date_field_instance_settings_form($field, $instance) {
'#type' => !empty($field['settings']['todate']) ? 'select' : 'hidden',
'#title' => t('Default end date'),
'#default_value' => $settings['default_value2'],
'#options' => array('same' => t('Same as Default date'), 'blank' => t('No default value'), 'now' => t('Now'), 'strtotime' => t('Relative')),
'#options' => array(
'same' => t('Same as Default date'),
'blank' => t('No default value'),
'now' => t('Now'),
'strtotime' => t('Relative'),
),
'#weight' => 2,
'#fieldset' => 'default_values',
);
@@ -224,8 +250,11 @@ function _date_field_instance_settings_form($field, $instance) {
'#default_value' => $settings['default_value_code2'],
'#states' => array(
'visible' => array(
':input[name="instance[settings][default_value2]"]' => array('value' => 'strtotime')),
':input[name="instance[settings][default_value2]"]' => array(
'value' => 'strtotime',
),
),
),
'#weight' => 2.1,
'#fieldset' => 'default_values',
);
@@ -284,6 +313,7 @@ function _date_field_widget_settings_form($field, $instance) {
$formats = drupal_map_assoc($formats);
}
$now = date_example_date();
$options['site-wide'] = t('Short date format: @date', array('@date' => date_format_date($now, 'short')));
foreach ($formats as $f) {
$options[$f] = date_format_date($now, 'custom', $f);
}
@@ -369,11 +399,18 @@ function _date_field_widget_settings_form($field, $instance) {
'#weight' => 9,
);
if (in_array($widget['type'], array('date_select'))) {
$options = array('above' => t('Above'), 'within' => t('Within'), 'none' => t('None'));
$options = array(
'above' => t('Above'),
'within' => t('Within'),
'none' => t('None'),
);
$description = t("The location of date part labels, like 'Year', 'Month', or 'Day' . 'Above' displays the label as titles above each date part. 'Within' inserts the label as the first option in the select list and in blank textfields. 'None' doesn't visually label any of the date parts. Theme functions like 'date_part_label_year' and 'date_part_label_month' control label text.");
}
else {
$options = array('above' => t('Above'), 'none' => t('None'));
$options = array(
'above' => t('Above'),
'none' => t('None'),
);
$description = t("The location of date part labels, like 'Year', 'Month', or 'Day' . 'Above' displays the label as titles above each date part. 'None' doesn't visually label any of the date parts. Theme functions like 'date_part_label_year' and 'date_part_label_month' control label text.");
}
$form['advanced']['label_position'] = array(
@@ -403,6 +440,13 @@ function _date_field_widget_settings_form($field, $instance) {
}
}
$form['advanced']['no_fieldset'] = array(
'#type' => 'checkbox',
'#title' => t('Render as a regular field'),
'#default_value' => !empty($settings['no_fieldset']),
'#description' => t('Whether to render this field as a regular field instead of a fieldset. The date field elements are wrapped in a fieldset by default, and may not display well without it.'),
);
$context = array(
'field' => $field,
'instance' => $instance,
@@ -470,7 +514,9 @@ function _date_field_settings_form($field, $instance, $has_data) {
'#title' => t('Date attributes to collect'),
'#default_value' => $granularity,
'#options' => $options,
'#attributes' => array('class' => array('container-inline')),
'#attributes' => array(
'class' => array('container-inline'),
),
'#description' => $description,
'year' => $checkbox_year,
);
@@ -528,7 +574,9 @@ function _date_field_settings_form($field, $instance, $has_data) {
'#weight' => 11,
'#states' => array(
'visible' => array(
'input[name="field[settings][cache_enabled]"]' => array('checked' => TRUE),
'input[name="field[settings][cache_enabled]"]' => array(
'checked' => TRUE,
),
),
),
);
@@ -600,7 +648,7 @@ function date_timezone_handling_options() {
'site' => t("Site's time zone"),
'date' => t("Date's time zone"),
'user' => t("User's time zone"),
'utc' => 'UTC',
'utc' => 'UTC',
'none' => t('No time zone conversion'),
);
}
@@ -5,9 +5,9 @@ dependencies[] = date
package = Date/Time
core = 7.x
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -31,11 +31,11 @@ function date_all_day_theme() {
'format' => NULL,
'entity_type' => NULL,
'entity' => NULL,
'view' => NULL
)
'view' => NULL,
),
),
'date_all_day_label' => array(
'variables' => array()
'variables' => array(),
),
);
@@ -91,14 +91,29 @@ function date_all_day_date_formatter_dates_alter(&$dates, $context) {
/**
* Adjust start/end date format to account for 'all day' .
*
* @param array $field, the field definition for this date field.
* @param string $which, which value to return, 'date1' or 'date2' .
* @param object $date1, a date/time object for the 'start' date.
* @param object $date2, a date/time object for the 'end' date.
* @param string $format
* @param object $entity, the node this date comes from (may be incomplete, always contains nid).
* @param object $view, the view this node comes from, if applicable.
* @return formatted date.
* @params array $field
* The field definition for this date field.
*
* @params string $which
* Which value to return, 'date1' or 'date2'.
*
* @params object $date1
* A date/time object for the 'start' date.
*
* @params object $date2
* A date/time object for the 'end' date.
*
* @params string $format
* A date/time format
*
* @params object $entity
* The node this date comes from (may be incomplete, always contains nid).
*
* @params object $view
* The view this node comes from, if applicable.
*
* @return string
* Formatted date.
*/
function theme_date_all_day($vars) {
$field = $vars['field'];
@@ -135,23 +150,32 @@ function theme_date_all_day($vars) {
}
return trim(date_format_date($$which, 'custom', $format) . $suffix);
}
/**
* Theme the way an 'all day' label will look.
*/
function theme_date_all_day_label() {
return '(' . t('All day', array(), array('context' => 'datetime')) .')';
return '(' . t('All day', array(), array('context' => 'datetime')) . ')';
}
/**
* Determine if a Start/End date combination qualify as 'All day'.
*
* @param array $field, the field definition for this date field.
* @param object $date1, a date/time object for the 'Start' date.
* @param object $date2, a date/time object for the 'End' date.
* @return TRUE or FALSE.
* @param array $field
* The field definition for this date field.
*
* @param array $instance
* The field instance for this date field.
*
* @param object $date1
* A date/time object for the 'Start' date.
*
* @param object $date2
* A date/time object for the 'End' date.
*
* @return bool
* TRUE or FALSE.
*/
function date_all_day_field($field, $instance, $date1, $date2 = NULL) {
if (empty($date1) || !is_object($date1)) {
@@ -167,7 +191,6 @@ function date_all_day_field($field, $instance, $date1, $date2 = NULL) {
$granularity = date_granularity_precision($field['settings']['granularity']);
$increment = isset($instance['widget']['settings']['increment']) ? $instance['widget']['settings']['increment'] : 1;
return date_is_all_day(date_format($date1, DATE_FORMAT_DATETIME), date_format($date2, DATE_FORMAT_DATETIME), $granularity, $increment);
}
/**
@@ -222,7 +245,8 @@ function date_all_day_date_combo_process_alter(&$element, &$form_state, $context
function date_all_day_date_text_process_alter(&$element, &$form_state, $context) {
$all_day_id = !empty($element['#date_all_day_id']) ? $element['#date_all_day_id'] : '';
if ($all_day_id != '') {
// All Day handling on text dates works only if the user leaves the time out of the input value.
// All Day handling on text dates works only
// if the user leaves the time out of the input value.
// There is no element to hide or show.
}
}
@@ -234,10 +258,11 @@ function date_all_day_date_text_process_alter(&$element, &$form_state, $context)
*/
function date_all_day_date_select_process_alter(&$element, &$form_state, $context) {
// Hide or show this element in reaction to the all_day status for this element.
// Hide or show this element in reaction
// to the all_day status for this element.
$all_day_id = !empty($element['#date_all_day_id']) ? $element['#date_all_day_id'] : '';
if ($all_day_id != '') {
foreach(array('hour', 'minute', 'second', 'ampm') as $field) {
foreach (array('hour', 'minute', 'second', 'ampm') as $field) {
if (array_key_exists($field, $element)) {
$element[$field]['#states'] = array(
'visible' => array(
@@ -255,7 +280,8 @@ function date_all_day_date_select_process_alter(&$element, &$form_state, $contex
*/
function date_all_day_date_popup_process_alter(&$element, &$form_state, $context) {
// Hide or show this element in reaction to the all_day status for this element.
// Hide or show this element in reaction to
// the all_day status for this element.
$all_day_id = !empty($element['#date_all_day_id']) ? $element['#date_all_day_id'] : '';
if ($all_day_id != '' && array_key_exists('time', $element)) {
$element['time']['#states'] = array(
@@ -272,7 +298,8 @@ function date_all_day_date_popup_process_alter(&$element, &$form_state, $context
* of the date_select validation gets fired.
*/
function date_all_day_date_text_pre_validate_alter(&$element, &$form_state, &$input) {
// Let Date module massage the format for all day values so they will pass validation.
// Let Date module massage the format for all day
// values so they will pass validation.
// The All day flag, if used, actually exists on the parent element.
date_all_day_value($element, $form_state);
}
@@ -284,7 +311,8 @@ function date_all_day_date_text_pre_validate_alter(&$element, &$form_state, &$in
* of the date_select validation gets fired.
*/
function date_all_day_date_select_pre_validate_alter(&$element, &$form_state, &$input) {
// Let Date module massage the format for all day values so they will pass validation.
// Let Date module massage the format for all
// day values so they will pass validation.
// The All day flag, if used, actually exists on the parent element.
date_all_day_value($element, $form_state);
}
@@ -296,13 +324,16 @@ function date_all_day_date_select_pre_validate_alter(&$element, &$form_state, &$
* of the date_popup validation gets fired.
*/
function date_all_day_date_popup_pre_validate_alter(&$element, &$form_state, &$input) {
// Let Date module massage the format for all day values so they will pass validation.
// Let Date module massage the format for all
// day values so they will pass validation.
// The All day flag, if used, actually exists on the parent element.
date_all_day_value($element, $form_state);
}
/**
* A helper function to check if the all day flag is set on the parent of an
* A helper function date_all_day_value().
*
* To check if the all day flag is set on the parent of an
* element, and adjust the date_format accordingly so the missing time will
* not cause validation errors.
*/
@@ -332,7 +363,8 @@ function date_all_day_date_combo_pre_validate_alter(&$element, &$form_state, $co
$field = $context['field'];
// If we have an all day flag on this date and the time is empty,
// change the format to match the input value so we don't get validation errors.
// change the format to match the input value
// so we don't get validation errors.
$element['#date_is_all_day'] = TRUE;
$element['value']['#date_format'] = date_part_format('date', $element['value']['#date_format']);
if (!empty($field['settings']['todate'])) {
@@ -344,29 +376,29 @@ function date_all_day_date_combo_pre_validate_alter(&$element, &$form_state, $co
/**
* Implements hook_date_combo_validate_date_start_alter().
*
* This hook lets us alter the local date objects created by the date_combo validation
* before they are converted back to the database timezone and stored.
* This hook lets us alter the local date objects
* created by the date_combo validation before they are
* converted back to the database timezone and stored.
*/
function date_all_day_date_combo_validate_date_start_alter(&$date, &$form_state, $context) {
// If this is an 'All day' value, set the time to midnight.
if (!empty($context['element']['#date_is_all_day'])) {
$date->setTime(0, 0, 0);
}
// If this is an 'All day' value, set the time to midnight.
if (!empty($context['element']['#date_is_all_day'])) {
$date->setTime(0, 0, 0);
}
}
/**
* Implements hook_date_combo_validate_date_end_alter().
*
* This hook lets us alter the local date objects created by the date_combo validation
* before they are converted back to the database timezone and stored.
* This hook lets us alter the local date objects
* created by the date_combo validation before
* they are converted back to the database timezone and stored.
*/
function date_all_day_date_combo_validate_date_end_alter(&$date, &$form_state, $context) {
// If this is an 'All day' value, set the time to midnight.
if (!empty($context['element']['#date_is_all_day'])) {
$date->setTime(0, 0, 0);
}
// If this is an 'All day' value, set the time to midnight.
if (!empty($context['element']['#date_is_all_day'])) {
$date->setTime(0, 0, 0);
}
}
/**
@@ -15,9 +15,11 @@
.container-inline-date > .form-item {
display: inline-block;
margin-right: 0.5em; /* LTR */
margin-bottom: 10px;
vertical-align: top;
}
fieldset.date-combo .container-inline-date > .form-item {
margin-bottom: 10px;
}
.container-inline-date .form-item .form-item {
float: left; /* LTR */
}
@@ -52,9 +54,11 @@
/* The exposed Views form doesn't need some of these styles */
.container-inline-date .date-padding {
padding: 10px;
float: left;
}
fieldset.date-combo .container-inline-date .date-padding {
padding: 10px;
}
.views-exposed-form .container-inline-date .date-padding {
padding: 0;
}
@@ -116,7 +120,7 @@ span.date-display-end {
}
/* Add space between the date and time portions of the date_select widget. */
.form-type-date-select .form-type-select[class$=hour] {
.form-type-date-select .form-type-select[class*=hour] {
margin-left: .75em; /* LTR */
}
@@ -173,6 +177,10 @@ div.date-calendar-day span.year {
padding: 2px;
}
.date-form-element-content-multiline {
padding: 10px;
border: 1px solid #CCC;
}
/* Admin styling */
.form-item.form-item-instance-widget-settings-input-format-custom,
.form-item.form-item-field-settings-enddate-required {
@@ -10,112 +10,112 @@
*/
function _date_timezone_replacement($old) {
$replace = array(
'Brazil/Acre' => 'America/Rio_Branco',
'Brazil/DeNoronha' => 'America/Noronha',
'Brazil/East' => 'America/Recife',
'Brazil/West' => 'America/Manaus',
'Canada/Atlantic' => 'America/Halifax',
'Canada/Central' => 'America/Winnipeg',
'Canada/East-Saskatchewan' => 'America/Regina',
'Canada/Eastern' => 'America/Toronto',
'Canada/Mountain' => 'America/Edmonton',
'Canada/Newfoundland' => 'America/St_Johns',
'Canada/Pacific' => 'America/Vancouver',
'Canada/Saskatchewan' => 'America/Regina',
'Canada/Yukon' => 'America/Whitehorse',
'CET' => 'Europe/Berlin',
'Chile/Continental' => 'America/Santiago',
'Chile/EasterIsland' => 'Pacific/Easter',
'CST6CDT' => 'America/Chicago',
'Cuba' => 'America/Havana',
'EET' => 'Europe/Bucharest',
'Egypt' => 'Africa/Cairo',
'Eire' => 'Europe/Belfast',
'EST' => 'America/New_York',
'EST5EDT' => 'America/New_York',
'GB' => 'Europe/London',
'GB-Eire' => 'Europe/Belfast',
'Etc/GMT' => 'UTC',
'Etc/GMT+0' => 'UTC',
'Etc/GMT+1' => 'UTC',
'Etc/GMT+10' => 'UTC',
'Etc/GMT+11' => 'UTC',
'Etc/GMT+12' => 'UTC',
'Etc/GMT+2' => 'UTC',
'Etc/GMT+3' => 'UTC',
'Etc/GMT+4' => 'UTC',
'Etc/GMT+5' => 'UTC',
'Etc/GMT+6' => 'UTC',
'Etc/GMT+7' => 'UTC',
'Etc/GMT+8' => 'UTC',
'Etc/GMT+9' => 'UTC',
'Etc/GMT-0' => 'UTC',
'Etc/GMT-1' => 'UTC',
'Etc/GMT-10' => 'UTC',
'Etc/GMT-11' => 'UTC',
'Etc/GMT-12' => 'UTC',
'Etc/GMT-13' => 'UTC',
'Etc/GMT-14' => 'UTC',
'Etc/GMT-2' => 'UTC',
'Etc/GMT-3' => 'UTC',
'Etc/GMT-4' => 'UTC',
'Etc/GMT-5' => 'UTC',
'Etc/GMT-6' => 'UTC',
'Etc/GMT-7' => 'UTC',
'Etc/GMT-8' => 'UTC',
'Etc/GMT-9' => 'UTC',
'Etc/GMT0' => 'UTC',
'Etc/Greenwich' => 'UTC',
'Etc/UCT' => 'UTC',
'Etc/Universal' => 'UTC',
'Etc/UTC' => 'UTC',
'Etc/Zulu' => 'UTC',
'Factory' => 'UTC',
'GMT' => 'UTC',
'GMT+0' => 'UTC',
'GMT-0' => 'UTC',
'GMT0' => 'UTC',
'Hongkong' => 'Asia/Hong_Kong',
'HST' => 'Pacific/Honolulu',
'Iceland' => 'Atlantic/Reykjavik',
'Iran' => 'Asia/Tehran',
'Israel' => 'Asia/Tel_Aviv',
'Jamaica' => 'America/Jamaica',
'Japan' => 'Asia/Tokyo',
'Kwajalein' => 'Pacific/Kwajalein',
'Libya' => 'Africa/Tunis',
'MET' => 'Europe/Budapest',
'Mexico/BajaNorte' => 'America/Tijuana',
'Mexico/BajaSur' => 'America/Mazatlan',
'Mexico/General' => 'America/Mexico_City',
'MST' => 'America/Boise',
'MST7MDT' => 'America/Boise',
'Navajo' => 'America/Phoenix',
'NZ' => 'Pacific/Auckland',
'NZ-CHAT' => 'Pacific/Chatham',
'Poland' => 'Europe/Warsaw',
'Portugal' => 'Europe/Lisbon',
'PRC' => 'Asia/Chongqing',
'PST8PDT' => 'America/Los_Angeles',
'ROC' => 'Asia/Taipei',
'ROK' => 'Asia/Seoul',
'Singapore' => 'Asia/Singapore',
'Turkey' => 'Europe/Istanbul',
'US/Alaska' => 'America/Anchorage',
'US/Aleutian' => 'America/Adak',
'US/Arizona' => 'America/Phoenix',
'US/Central' => 'America/Chicago',
'US/East-Indiana' => 'America/Indianapolis',
'US/Eastern' => 'America/New_York',
'US/Hawaii' => 'Pacific/Honolulu',
'US/Indiana-Starke' => 'America/Indiana/Knox',
'US/Michigan' => 'America/Detroit',
'US/Mountain' => 'America/Boise',
'US/Pacific' => 'America/Los_Angeles',
'US/Pacific-New' => 'America/Los_Angeles',
'US/Samoa' => 'Pacific/Samoa',
'W-SU' => 'Europe/Moscow',
'WET' => 'Europe/Paris',
'Brazil/Acre' => 'America/Rio_Branco',
'Brazil/DeNoronha' => 'America/Noronha',
'Brazil/East' => 'America/Recife',
'Brazil/West' => 'America/Manaus',
'Canada/Atlantic' => 'America/Halifax',
'Canada/Central' => 'America/Winnipeg',
'Canada/East-Saskatchewan' => 'America/Regina',
'Canada/Eastern' => 'America/Toronto',
'Canada/Mountain' => 'America/Edmonton',
'Canada/Newfoundland' => 'America/St_Johns',
'Canada/Pacific' => 'America/Vancouver',
'Canada/Saskatchewan' => 'America/Regina',
'Canada/Yukon' => 'America/Whitehorse',
'CET' => 'Europe/Berlin',
'Chile/Continental' => 'America/Santiago',
'Chile/EasterIsland' => 'Pacific/Easter',
'CST6CDT' => 'America/Chicago',
'Cuba' => 'America/Havana',
'EET' => 'Europe/Bucharest',
'Egypt' => 'Africa/Cairo',
'Eire' => 'Europe/Belfast',
'EST' => 'America/New_York',
'EST5EDT' => 'America/New_York',
'GB' => 'Europe/London',
'GB-Eire' => 'Europe/Belfast',
'Etc/GMT' => 'UTC',
'Etc/GMT+0' => 'UTC',
'Etc/GMT+1' => 'UTC',
'Etc/GMT+10' => 'UTC',
'Etc/GMT+11' => 'UTC',
'Etc/GMT+12' => 'UTC',
'Etc/GMT+2' => 'UTC',
'Etc/GMT+3' => 'UTC',
'Etc/GMT+4' => 'UTC',
'Etc/GMT+5' => 'UTC',
'Etc/GMT+6' => 'UTC',
'Etc/GMT+7' => 'UTC',
'Etc/GMT+8' => 'UTC',
'Etc/GMT+9' => 'UTC',
'Etc/GMT-0' => 'UTC',
'Etc/GMT-1' => 'UTC',
'Etc/GMT-10' => 'UTC',
'Etc/GMT-11' => 'UTC',
'Etc/GMT-12' => 'UTC',
'Etc/GMT-13' => 'UTC',
'Etc/GMT-14' => 'UTC',
'Etc/GMT-2' => 'UTC',
'Etc/GMT-3' => 'UTC',
'Etc/GMT-4' => 'UTC',
'Etc/GMT-5' => 'UTC',
'Etc/GMT-6' => 'UTC',
'Etc/GMT-7' => 'UTC',
'Etc/GMT-8' => 'UTC',
'Etc/GMT-9' => 'UTC',
'Etc/GMT0' => 'UTC',
'Etc/Greenwich' => 'UTC',
'Etc/UCT' => 'UTC',
'Etc/Universal' => 'UTC',
'Etc/UTC' => 'UTC',
'Etc/Zulu' => 'UTC',
'Factory' => 'UTC',
'GMT' => 'UTC',
'GMT+0' => 'UTC',
'GMT-0' => 'UTC',
'GMT0' => 'UTC',
'Hongkong' => 'Asia/Hong_Kong',
'HST' => 'Pacific/Honolulu',
'Iceland' => 'Atlantic/Reykjavik',
'Iran' => 'Asia/Tehran',
'Israel' => 'Asia/Tel_Aviv',
'Jamaica' => 'America/Jamaica',
'Japan' => 'Asia/Tokyo',
'Kwajalein' => 'Pacific/Kwajalein',
'Libya' => 'Africa/Tunis',
'MET' => 'Europe/Budapest',
'Mexico/BajaNorte' => 'America/Tijuana',
'Mexico/BajaSur' => 'America/Mazatlan',
'Mexico/General' => 'America/Mexico_City',
'MST' => 'America/Boise',
'MST7MDT' => 'America/Boise',
'Navajo' => 'America/Phoenix',
'NZ' => 'Pacific/Auckland',
'NZ-CHAT' => 'Pacific/Chatham',
'Poland' => 'Europe/Warsaw',
'Portugal' => 'Europe/Lisbon',
'PRC' => 'Asia/Chongqing',
'PST8PDT' => 'America/Los_Angeles',
'ROC' => 'Asia/Taipei',
'ROK' => 'Asia/Seoul',
'Singapore' => 'Asia/Singapore',
'Turkey' => 'Europe/Istanbul',
'US/Alaska' => 'America/Anchorage',
'US/Aleutian' => 'America/Adak',
'US/Arizona' => 'America/Phoenix',
'US/Central' => 'America/Chicago',
'US/East-Indiana' => 'America/Indianapolis',
'US/Eastern' => 'America/New_York',
'US/Hawaii' => 'Pacific/Honolulu',
'US/Indiana-Starke' => 'America/Indiana/Knox',
'US/Michigan' => 'America/Detroit',
'US/Mountain' => 'America/Boise',
'US/Pacific' => 'America/Los_Angeles',
'US/Pacific-New' => 'America/Los_Angeles',
'US/Samoa' => 'Pacific/Samoa',
'W-SU' => 'Europe/Moscow',
'WET' => 'Europe/Paris',
);
if (array_key_exists($old, $replace)) {
return $replace[$old];
@@ -9,9 +9,9 @@ stylesheets[all][] = date.css
files[] = date_api.module
files[] = date_api_sql.inc
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -96,7 +96,7 @@ function date_api_uninstall() {
'date_php_min_year',
'date_db_tz_support',
'date_api_use_iso8601',
);
);
foreach ($variables as $variable) {
variable_del($variable);
}
@@ -118,8 +118,9 @@ function date_api_update_last_removed() {
}
/**
* Move old date format data to new date format tables, and delete the old
* tables. Insert only values that don't already exist in the new tables, in
* Move old date format to new date format tables,and delete the old tables.
*
* Insert only values that don't already exist in the new tables, in
* case new version of those custom values have already been created.
*/
function date_api_update_7000() {
@@ -59,16 +59,16 @@ function date_help($path, $arg) {
}
if (module_exists('date_tools')) {
$output .= '<h3>Date Tools</h3>' . t('Dates and calendars can be complicated to set up. The !date_wizard makes it easy to create a simple date content type and with a date field. ', array('!date_wizard' => l(t('Date wizard'), 'admin/config/date/tools/date_wizard')));
$output .= '<h3>Date Tools</h3>' . t('Dates and calendars can be complicated to set up. The !date_wizard makes it easy to create a simple date content type and with a date field.', array('!date_wizard' => l(t('Date wizard'), 'admin/config/date/tools/date_wizard')));
}
else {
$output .= '<h3>Date Tools</h3>' . t('Dates and calendars can be complicated to set up. If you enable the Date Tools module, it provides a Date Wizard that makes it easy to create a simple date content type with a date field. ');
$output .= '<h3>Date Tools</h3>' . t('Dates and calendars can be complicated to set up. If you enable the Date Tools module, it provides a Date Wizard that makes it easy to create a simple date content type with a date field.');
}
$output .= '<h2>More Information</h2><p>' . t('Complete documentation for the Date and Date API modules is available at <a href="@link">http://drupal.org/node/92460</a>.', array('@link' => 'http://drupal.org/node/262062')) . '</p>';
return $output;
break;
}
}
@@ -101,7 +101,7 @@ function date_api_status() {
$value = variable_get('date_format_medium');
if (isset($value)) {
$now = date_now();
$success_messages[] = $t('The medium date format type has been set to to @value. You may find it helpful to add new format types like Date, Time, Month, or Year, with appropriate formats, at <a href="@regional_date_time">Date and time</a> settings.', array('@value' => $now->format($value), '@regional_date_time' => url('admin/config/regional/date-time')));
$success_messages[] = $t('The medium date format type has been set to @value. You may find it helpful to add new format types like Date, Time, Month, or Year, with appropriate formats, at <a href="@regional_date_time">Date and time</a> settings.', array('@value' => $now->format($value), '@regional_date_time' => url('admin/config/regional/date-time')));
}
else {
$error_messages[] = $t('The Date API requires that you set up the <a href="@regional_date_time">system date formats</a> to function correctly.', array('@regional_date_time' => url('admin/config/regional/date-time')));
@@ -143,7 +143,15 @@ function date_api_menu() {
class DateObject extends DateTime {
public $granularity = array();
public $errors = array();
protected static $allgranularity = array('year', 'month', 'day', 'hour', 'minute', 'second', 'timezone');
protected static $allgranularity = array(
'year',
'month',
'day',
'hour',
'minute',
'second',
'timezone'
);
private $serializedTime;
private $serializedTimezone;
@@ -402,7 +410,7 @@ class DateObject extends DateTime {
* A single date part.
*/
public function removeGranularity($g) {
if ($key = array_search($g, $this->granularity)) {
if (($key = array_search($g, $this->granularity)) !== FALSE) {
unset($this->granularity[$key]);
}
}
@@ -458,23 +466,35 @@ class DateObject extends DateTime {
$true = $this->hasGranularity() && (!$granularity || $flexible || $this->hasGranularity($granularity));
if (!$true && $granularity) {
foreach ((array) $granularity as $part) {
if (!$this->hasGranularity($part) && in_array($part, array('second', 'minute', 'hour', 'day', 'month', 'year'))) {
if (!$this->hasGranularity($part) && in_array($part, array(
'second',
'minute',
'hour',
'day',
'month',
'year')
)) {
switch ($part) {
case 'second':
$this->errors[$part] = t('The second is missing.');
break;
case 'minute':
$this->errors[$part] = t('The minute is missing.');
break;
case 'hour':
$this->errors[$part] = t('The hour is missing.');
break;
case 'day':
$this->errors[$part] = t('The day is missing.');
break;
case 'month':
$this->errors[$part] = t('The month is missing.');
break;
case 'year':
$this->errors[$part] = t('The year is missing.');
break;
@@ -537,7 +557,14 @@ class DateObject extends DateTime {
$temp = date_parse($time);
// Special case for 'now'.
if ($time == 'now') {
$this->granularity = array('year', 'month', 'day', 'hour', 'minute', 'second');
$this->granularity = array(
'year',
'month',
'day',
'hour',
'minute',
'second',
);
}
else {
// This PHP date_parse() method currently doesn't have resolution down to
@@ -600,7 +627,14 @@ class DateObject extends DateTime {
return FALSE;
}
$this->granularity = array();
$final_date = array('hour' => 0, 'minute' => 0, 'second' => 0, 'month' => 1, 'day' => 1, 'year' => 0);
$final_date = array(
'hour' => 0,
'minute' => 0,
'second' => 0,
'month' => 1,
'day' => 1,
'year' => 0,
);
foreach ($letters as $i => $letter) {
$value = $values[$i];
switch ($letter) {
@@ -609,21 +643,25 @@ class DateObject extends DateTime {
$final_date['day'] = intval($value);
$this->addGranularity('day');
break;
case 'n':
case 'm':
$final_date['month'] = intval($value);
$this->addGranularity('month');
break;
case 'F':
$array_month_long = array_flip(date_month_names());
$final_date['month'] = array_key_exists($value, $array_month_long) ? $array_month_long[$value] : -1;
$this->addGranularity('month');
break;
case 'M':
$array_month = array_flip(date_month_names_abbr());
$final_date['month'] = array_key_exists($value, $array_month) ? $array_month[$value] : -1;
$this->addGranularity('month');
break;
case 'Y':
$final_date['year'] = $value;
$this->addGranularity('year');
@@ -631,16 +669,19 @@ class DateObject extends DateTime {
$this->errors['year'] = t('The year is invalid. Please check that entry includes four digits.');
}
break;
case 'y':
$year = $value;
// If no century, we add the current one ("06" => "2006").
$final_date['year'] = str_pad($year, 4, substr(date("Y"), 0, 2), STR_PAD_LEFT);
$this->addGranularity('year');
break;
case 'a':
case 'A':
$ampm = strtolower($value);
break;
case 'g':
case 'h':
case 'G':
@@ -648,14 +689,17 @@ class DateObject extends DateTime {
$final_date['hour'] = intval($value);
$this->addGranularity('hour');
break;
case 'i':
$final_date['minute'] = intval($value);
$this->addGranularity('minute');
break;
case 's':
$final_date['second'] = intval($value);
$this->addGranularity('second');
break;
case 'U':
parent::__construct($value, $tz ? $tz : new DateTimeZone("UTC"));
$this->addGranularity('year');
@@ -665,7 +709,7 @@ class DateObject extends DateTime {
$this->addGranularity('minute');
$this->addGranularity('second');
return $this;
break;
}
}
if (isset($ampm) && $ampm == 'pm' && $final_date['hour'] < 12) {
@@ -758,10 +802,24 @@ class DateObject extends DateTime {
// date or we will get date slippage, i.e. a value of 2011-00-00 will get
// interpreted as November of 2010 by PHP.
if ($full) {
$arr += array('year' => 0, 'month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0, 'second' => 0);
$arr += array(
'year' => 0,
'month' => 1,
'day' => 1,
'hour' => 0,
'minute' => 0,
'second' => 0,
);
}
else {
$arr += array('year' => '', 'month' => '', 'day' => '', 'hour' => '', 'minute' => '', 'second' => '');
$arr += array(
'year' => '',
'month' => '',
'day' => '',
'hour' => '',
'minute' => '',
'second' => '',
);
}
$datetime = '';
if ($arr['year'] !== '') {
@@ -839,28 +897,27 @@ class DateObject extends DateTime {
case 'year':
$fallback = $now->format('Y');
return !is_int($value) || empty($value) || $value < variable_get('date_min_year', 1) || $value > variable_get('date_max_year', 4000) ? $fallback : $value;
break;
case 'month':
$fallback = $default == 'first' ? 1 : $now->format('n');
return !is_int($value) || empty($value) || $value <= 0 || $value > 12 ? $fallback : $value;
break;
case 'day':
$fallback = $default == 'first' ? 1 : $now->format('j');
$max_day = isset($year) && isset($month) ? date_days_in_month($year, $month) : 31;
return !is_int($value) || empty($value) || $value <= 0 || $value > $max_day ? $fallback : $value;
break;
case 'hour':
$fallback = $default == 'first' ? 0 : $now->format('G');
return !is_int($value) || $value < 0 || $value > 23 ? $fallback : $value;
break;
case 'minute':
$fallback = $default == 'first' ? 0 : $now->format('i');
return !is_int($value) || $value < 0 || $value > 59 ? $fallback : $value;
break;
case 'second':
$fallback = $default == 'first' ? 0 : $now->format('s');
return !is_int($value) || $value < 0 || $value > 59 ? $fallback : $value;
break;
}
}
@@ -898,18 +955,23 @@ class DateObject extends DateTime {
case 'year':
$errors['year'] = t('The year is invalid.');
break;
case 'month':
$errors['month'] = t('The month is invalid.');
break;
case 'day':
$errors['day'] = t('The day is invalid.');
break;
case 'hour':
$errors['hour'] = t('The hour is invalid.');
break;
case 'minute':
$errors['minute'] = t('The minute is invalid.');
break;
case 'second':
$errors['second'] = t('The second is invalid.');
break;
@@ -929,7 +991,7 @@ class DateObject extends DateTime {
* The stop date.
* @param string $measure
* (optional) A granularity date part. Defaults to 'seconds'.
* @param boolean $absolute
* @param bool $absolute
* (optional) Indicate whether the absolute value of the difference should
* be returned or if the sign should be retained. Defaults to TRUE.
*/
@@ -955,10 +1017,13 @@ class DateObject extends DateTime {
// The easy cases first.
case 'seconds':
return $diff;
case 'minutes':
return $diff / 60;
case 'hours':
return $diff / 3600;
case 'years':
return $year_diff;
@@ -1013,7 +1078,7 @@ class DateObject extends DateTime {
$sign = ($year_diff < 0) ? -1 : 1;
for ($i = 1; $i <= abs($year_diff); $i++) {
date_modify($date1, (($sign > 0) ? '+': '-').'1 year');
date_modify($date1, (($sign > 0) ? '+' : '-') . '1 year');
$week_diff += (date_iso_weeks_in_year($date1) * $sign);
}
return $week_diff;
@@ -1060,10 +1125,13 @@ function date_type_format($type) {
switch ($type) {
case DATE_ISO:
return DATE_FORMAT_ISO;
case DATE_UNIX:
return DATE_FORMAT_UNIX;
case DATE_DATETIME:
return DATE_FORMAT_DATETIME;
case DATE_ICAL:
return DATE_FORMAT_ICAL;
}
@@ -1119,7 +1187,7 @@ function date_month_names($required = FALSE) {
}
/**
* Constructs a translated array of month name abbreviations
* Constructs a translated array of month name abbreviations.
*
* @param bool $required
* (optional) If FALSE, the returned array will include a blank value.
@@ -1211,9 +1279,11 @@ function date_week_days_abbr($required = FALSE, $refresh = TRUE, $length = 3) {
case 1:
$context = 'day_abbr1';
break;
case 2:
$context = 'day_abbr2';
break;
default:
$context = '';
break;
@@ -1248,10 +1318,10 @@ function date_week_days_ordered($weekdays) {
/**
* Constructs an array of years.
*
* @param int $min
* The minimum year in the array.
* @param int $max
* The maximum year in the array.
* @param int $start
* The start year in the array.
* @param int $end
* The end year in the array.
* @param bool $required
* (optional) If FALSE, the returned array will include a blank value.
* Defaults to FALSE.
@@ -1259,16 +1329,16 @@ function date_week_days_ordered($weekdays) {
* @return array
* An array of years in the selected range.
*/
function date_years($min = 0, $max = 0, $required = FALSE) {
function date_years($start = 0, $end = 0, $required = FALSE) {
// Ensure $min and $max are valid values.
if (empty($min)) {
$min = intval(date('Y', REQUEST_TIME) - 3);
if (empty($start)) {
$start = intval(date('Y', REQUEST_TIME) - 3);
}
if (empty($max)) {
$max = intval(date('Y', REQUEST_TIME) + 3);
if (empty($end)) {
$end = intval(date('Y', REQUEST_TIME) + 3);
}
$none = array(0 => '');
return !$required ? $none + drupal_map_assoc(range($min, $max)) : drupal_map_assoc(range($min, $max));
return !$required ? $none + drupal_map_assoc(range($start, $end)) : drupal_map_assoc(range($start, $end));
}
/**
@@ -1474,7 +1544,14 @@ function date_granularity_names() {
* An array of date parts.
*/
function date_granularity_sorted($granularity) {
return array_intersect(array('year', 'month', 'day', 'hour', 'minute', 'second'), $granularity);
return array_intersect(array(
'year',
'month',
'day',
'hour',
'minute',
'second',
), $granularity);
}
/**
@@ -1492,14 +1569,19 @@ function date_granularity_array_from_precision($precision) {
switch ($precision) {
case 'year':
return array_slice($granularity_array, -6, 1);
case 'month':
return array_slice($granularity_array, -6, 2);
case 'day':
return array_slice($granularity_array, -6, 3);
case 'hour':
return array_slice($granularity_array, -6, 4);
case 'minute':
return array_slice($granularity_array, -6, 5);
default:
return $granularity_array;
}
@@ -1533,14 +1615,19 @@ function date_granularity_format($granularity) {
switch ($granularity) {
case 'year':
return substr($format, 0, 1);
case 'month':
return substr($format, 0, 3);
case 'day':
return substr($format, 0, 5);
case 'hour';
return substr($format, 0, 7);
case 'minute':
return substr($format, 0, 9);
default:
return $format;
}
@@ -1657,40 +1744,51 @@ function date_format_date($date, $type = 'medium', $format = '', $langcode = NUL
case 'l':
$datestring .= t($date->format('l'), array(), array('context' => '', 'langcode' => $langcode));
break;
case 'D':
$datestring .= t($date->format('D'), array(), array('context' => '', 'langcode' => $langcode));
break;
case 'F':
$datestring .= t($date->format('F'), array(), array('context' => 'Long month name', 'langcode' => $langcode));
break;
case 'M':
$datestring .= t($date->format('M'), array(), array('langcode' => $langcode));
break;
case 'A':
case 'a':
$datestring .= t($date->format($c), array(), array('context' => 'ampm', 'langcode' => $langcode));
break;
// The timezone name translations can use t().
case 'e':
case 'T':
$datestring .= t($date->format($c));
break;
// Remaining date parts need no translation.
case 'O':
$datestring .= sprintf('%s%02d%02d', (date_offset_get($date) < 0 ? '-' : '+'), abs(date_offset_get($date) / 3600), abs(date_offset_get($date) % 3600) / 60);
break;
case 'P':
$datestring .= sprintf('%s%02d:%02d', (date_offset_get($date) < 0 ? '-' : '+'), abs(date_offset_get($date) / 3600), abs(date_offset_get($date) % 3600) / 60);
break;
case 'Z':
$datestring .= date_offset_get($date);
break;
case '\\':
$datestring .= $format[++$i];
break;
case 'r':
$datestring .= date_format_date($date, 'custom', 'D, d M Y H:i:s O', $langcode);
$datestring .= date_format_date($date, 'custom', 'D, d M Y H:i:s O', 'en');
break;
default:
if (strpos('BdcgGhHiIjLmnNosStTuUwWYyz', $c) !== FALSE) {
$datestring .= $date->format($c);
@@ -1739,8 +1837,8 @@ function date_format_interval($date, $granularity = 2, $display_ago = TRUE) {
* (optional) Optionally force time to a specific timezone, defaults to user
* timezone, if set, otherwise site timezone. Defaults to NULL.
*
* @param boolean $reset [optional]
* Static cache reset
* @param bool $reset
* (optional) Static cache reset.
*
* @return object
* The current time as a date object.
@@ -1831,7 +1929,7 @@ function date_days_in_month($year, $month) {
* @param mixed $date
* (optional) The current date object, or a date string. Defaults to NULL.
*
* @return integer
* @return int
* The number of days in the year.
*/
function date_days_in_year($date = NULL) {
@@ -1860,7 +1958,7 @@ function date_days_in_year($date = NULL) {
* @param mixed $date
* (optional) The current date object, or a date string. Defaults to NULL.
*
* @return integer
* @return int
* The number of ISO weeks in a year.
*/
function date_iso_weeks_in_year($date = NULL) {
@@ -1952,7 +2050,7 @@ function date_week_range($week, $year) {
// Move forwards to the last day of the week.
$max_date = clone($min_date);
date_modify($max_date, '+7 days');
date_modify($max_date, '+6 days');
if (date_format($min_date, 'Y') != $year) {
$min_date = new DateObject($year . '-01-01 00:00:00');
@@ -1986,7 +2084,7 @@ function date_iso_week_range($week, $year) {
// Move forwards to the last day of the week.
$max_date = clone($min_date);
date_modify($max_date, '+7 days');
date_modify($max_date, '+6 days');
return array($min_date, $max_date);
}
@@ -2094,7 +2192,8 @@ function date_has_time($granularity) {
if (!is_array($granularity)) {
$granularity = array();
}
return (bool) count(array_intersect($granularity, array('hour', 'minute', 'second')));
$options = array('hour', 'minute', 'second');
return (bool) count(array_intersect($granularity, $options));
}
/**
@@ -2110,7 +2209,8 @@ function date_has_date($granularity) {
if (!is_array($granularity)) {
$granularity = array();
}
return (bool) count(array_intersect($granularity, array('year', 'month', 'day')));
$options = array('year', 'month', 'day');
return (bool) count(array_intersect($granularity, $options));
}
/**
@@ -2128,8 +2228,10 @@ function date_part_format($part, $format) {
switch ($part) {
case 'date':
return date_limit_format($format, array('year', 'month', 'day'));
case 'time':
return date_limit_format($format, array('hour', 'minute', 'second'));
default:
return date_limit_format($format, array($part));
}
@@ -2157,7 +2259,7 @@ function date_limit_format($format, $granularity) {
$drupal_static_fast['formats'] = &drupal_static(__FUNCTION__);
}
$formats = &$drupal_static_fast['formats'];
$format_granularity_cid = $format .'|'. implode(',', $granularity);
$format_granularity_cid = $format . '|' . implode(',', $granularity);
if (isset($formats[$format_granularity_cid])) {
return $formats[$format_granularity_cid];
}
@@ -2191,21 +2293,27 @@ function date_limit_format($format, $granularity) {
case 'year':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[Yy])';
break;
case 'day':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[l|D|d|dS|j|jS|N|w|W|z]{1,2})';
break;
case 'month':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[FMmn])';
break;
case 'hour':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[HhGg])';
break;
case 'minute':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[i])';
break;
case 'second':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[s])';
break;
case 'timezone':
$regex[] = '([\-/\.,:]?\s?(?<!\\\\)[TOZPe])';
break;
@@ -2278,25 +2386,30 @@ function date_format_order($format) {
case 'j':
$order[] = 'day';
break;
case 'F':
case 'M':
case 'm':
case 'n':
$order[] = 'month';
break;
case 'Y':
case 'y':
$order[] = 'year';
break;
case 'g':
case 'G':
case 'h':
case 'H':
$order[] = 'hour';
break;
case 'i':
$order[] = 'minute';
break;
case 's':
$order[] = 'second';
break;
@@ -2315,7 +2428,16 @@ function date_format_order($format) {
* A reduced set of granularitiy elements.
*/
function date_nongranularity($granularity) {
return array_diff(array('year', 'month', 'day', 'hour', 'minute', 'second', 'timezone'), (array) $granularity);
$options = array(
'year',
'month',
'day',
'hour',
'minute',
'second',
'timezone',
);
return array_diff($options, (array) $granularity);
}
/**
@@ -2335,7 +2457,11 @@ function date_api_theme($existing, $type, $theme, $path) {
'path' => "$path/theme",
);
return array(
'date_nav_title' => $base + array('variables' => array('granularity' => NULL, 'view' => NULL, 'link' => NULL, 'format' => NULL)),
'date_nav_title' => $base + array(
'variables' => array(
'granularity' => NULL, 'view' => NULL, 'link' => NULL, 'format' => NULL
),
),
'date_timezone' => $base + array('render element' => 'element'),
'date_select' => $base + array('render element' => 'element'),
'date_text' => $base + array('render element' => 'element'),
@@ -2355,7 +2481,11 @@ function date_api_theme($existing, $type, $theme, $path) {
'date_part_label_time' => $base + array('variables' => array('date_part' => NULL, 'element' => NULL)),
'date_views_filter_form' => $base + array('template' => 'date-views-filter-form', 'render element' => 'form'),
'date_calendar_day' => $base + array('variables' => array('date' => NULL)),
'date_time_ago' => $base + array('variables' => array('start_date' => NULL, 'end_date' => NULL, 'interval' => NULL)),
'date_time_ago' => $base + array(
'variables' => array(
'start_date' => NULL, 'end_date' => NULL, 'interval' => NULL
),
),
);
}
@@ -2375,9 +2505,11 @@ function date_get_timezone($handling, $timezone = '') {
case 'date':
$timezone = !empty($timezone) ? $timezone : date_default_timezone();
break;
case 'utc':
$timezone = 'UTC';
break;
default:
$timezone = date_default_timezone();
}
@@ -2404,6 +2536,7 @@ function date_get_timezone_db($handling, $timezone = NULL) {
// These handling modes all convert to UTC before storing in the DB.
$timezone = 'UTC';
break;
case ('date'):
if ($timezone == NULL) {
// This shouldn't happen, since it's meaning is undefined. But we need
@@ -2411,6 +2544,7 @@ function date_get_timezone_db($handling, $timezone = NULL) {
$timezone = date_default_timezone();
}
break;
case ('none'):
default:
$timezone = date_default_timezone();
@@ -2465,12 +2599,12 @@ function date_order() {
* TRUE if the date range is valid, FALSE otherwise.
*/
function date_range_valid($string) {
$matches = preg_match('@^(\-[0-9]+|[0-9]{4}):([\+|\-][0-9]+|[0-9]{4})$@', $string);
$matches = preg_match('@^([\+\-][0-9]+|[0-9]{4}):([\+\-][0-9]+|[0-9]{4})$@', $string);
return $matches < 1 ? FALSE : TRUE;
}
/**
* Splits a string like -3:+3 or 2001:2010 into an array of min and max years.
* Splits a string like -3:+3 or 2001:2010 into an array of start and end years.
*
* Center the range around the current year, if any, but expand it far
* enough so it will pick up the year value in the field in case
@@ -2482,45 +2616,44 @@ function date_range_valid($string) {
* (optional) A date object. Defaults to NULL.
*
* @return array
* A numerically indexed array, containing a minimum and maximum year.
* A numerically indexed array, containing a start and end year.
*/
function date_range_years($string, $date = NULL) {
$this_year = date_format(date_now(), 'Y');
list($min_year, $max_year) = explode(':', $string);
list($start_year, $end_year) = explode(':', $string);
// Valid patterns would be -5:+5, 0:+1, 2008:2010.
$plus_pattern = '@[\+|\-][0-9]{1,4}@';
$plus_pattern = '@[\+\-][0-9]{1,4}@';
$year_pattern = '@^[0-9]{4}@';
if (!preg_match($year_pattern, $min_year, $matches)) {
if (preg_match($plus_pattern, $min_year, $matches)) {
$min_year = $this_year + $matches[0];
if (!preg_match($year_pattern, $start_year, $matches)) {
if (preg_match($plus_pattern, $start_year, $matches)) {
$start_year = $this_year + $matches[0];
}
else {
$min_year = $this_year;
$start_year = $this_year;
}
}
if (!preg_match($year_pattern, $max_year, $matches)) {
if (preg_match($plus_pattern, $max_year, $matches)) {
$max_year = $this_year + $matches[0];
if (!preg_match($year_pattern, $end_year, $matches)) {
if (preg_match($plus_pattern, $end_year, $matches)) {
$end_year = $this_year + $matches[0];
}
else {
$max_year = $this_year;
$end_year = $this_year;
}
}
// We expect the $min year to be less than the $max year.
// Some custom values for -99:+99 might not obey that.
if ($min_year > $max_year) {
$temp = $max_year;
$max_year = $min_year;
$min_year = $temp;
}
// If there is a current value, stretch the range to include it.
$value_year = is_object($date) ? $date->format('Y') : '';
if (!empty($value_year)) {
$min_year = min($value_year, $min_year);
$max_year = max($value_year, $max_year);
if ($start_year <= $end_year) {
$start_year = min($value_year, $start_year);
$end_year = max($value_year, $end_year);
}
else {
$start_year = max($value_year, $start_year);
$end_year = min($value_year, $end_year);
}
}
return array($min_year, $max_year);
return array($start_year, $end_year);
}
/**
@@ -2680,6 +2813,7 @@ function date_is_all_day($string1, $string2, $granularity = 'second', $increment
|| ($hour2 == 23 && in_array($min2, array($max_minutes, 59)) && in_array($sec2, array($max_seconds, 59)))
|| ($hour1 == 0 && $hour2 == 0 && $min1 == 0 && $min2 == 0 && $sec1 == 0 && $sec2 == 0);
break;
case 'minute':
$min_match = $time1 == '00:00:00'
|| ($hour1 == 0 && $min1 == 0);
@@ -2687,6 +2821,7 @@ function date_is_all_day($string1, $string2, $granularity = 'second', $increment
|| ($hour2 == 23 && in_array($min2, array($max_minutes, 59)))
|| ($hour1 == 0 && $hour2 == 0 && $min1 == 0 && $min2 == 0);
break;
case 'hour':
$min_match = $time1 == '00:00:00'
|| ($hour1 == 0);
@@ -2694,6 +2829,7 @@ function date_is_all_day($string1, $string2, $granularity = 'second', $increment
|| ($hour2 == 23)
|| ($hour1 == 0 && $hour2 == 0);
break;
default:
$min_match = TRUE;
$max_match = FALSE;
@@ -2754,15 +2890,21 @@ function date_is_date($date) {
}
/**
* This function will replace ISO values that have the pattern 9999-00-00T00:00:00
* with a pattern like 9999-01-01T00:00:00, to match the behavior of non-ISO
* dates and ensure that date objects created from this value contain a valid month
* and day. Without this fix, the ISO date '2020-00-00T00:00:00' would be created as
* Replace specific ISO values using patterns.
*
* Function will replace ISO values that have the pattern 9999-00-00T00:00:00
* with a pattern like 9999-01-01T00:00:00, to match the behavior of non-ISO dates
* and ensure that date objects created from this value contain a valid month
* and day.
* Without this fix, the ISO date '2020-00-00T00:00:00' would be created as
* November 30, 2019 (the previous day in the previous month).
*
* @param string $iso_string
* An ISO string that needs to be made into a complete, valid date.
*
* @return mixed|string
* replaced value, or incoming value.
*
* @TODO Expand on this to work with all sorts of partial ISO dates.
*/
function date_make_iso_valid($iso_string) {
@@ -116,15 +116,19 @@ function date_default_date($element) {
case 16:
$format = 'Y-m-d H:i';
break;
case 13:
$format = 'Y-m-d H';
break;
case 10:
$format = 'Y-m-d';
break;
case 7:
$format = 'Y-m';
break;
case 4:
$format = 'Y';
break;
@@ -170,7 +174,7 @@ function date_year_range_element_process($element, &$form_state, $form) {
$element['#attached']['js'][] = drupal_get_path('module', 'date_api') . '/date_year_range.js';
$context = array(
'form' => $form,
'form' => $form,
);
drupal_alter('date_year_range_process', $element, $form_state, $context);
@@ -256,7 +260,7 @@ function date_timezone_element_process($element, &$form_state, $form) {
}
$context = array(
'form' => $form,
'form' => $form,
);
drupal_alter('date_timezone_process', $element, $form_state, $context);
@@ -264,7 +268,7 @@ function date_timezone_element_process($element, &$form_state, $form) {
}
/**
* Validation for timezone input
* Validation for timezone input.
*
* Move the timezone value from the nested field back to the original field.
*/
@@ -307,7 +311,6 @@ function date_text_element_value_callback($element, $input = FALSE, &$form_state
*
* The exact parts displayed in the field are those in #date_granularity.
* The display of each part comes from #date_format.
*
*/
function date_text_element_process($element, &$form_state, $form) {
if (date_hidden_element($element)) {
@@ -323,9 +326,18 @@ function date_text_element_process($element, &$form_state, $form) {
$now = date_example_date();
$element['date']['#title'] = t('Date');
$element['date']['#title_display'] = 'invisible';
$element['date']['#description'] = ' ' . t('Format: @date', array('@date' => date_format_date(date_example_date(), 'custom', $element['#date_format'])));
$element['date']['#description'] = ' ' . t('Format: @date', array(
'@date' => date_format_date(date_example_date(), 'custom', $element['#date_format']
)));
$element['date']['#ajax'] = !empty($element['#ajax']) ? $element['#ajax'] : FALSE;
// Make changes if instance is set to be rendered as a regular field.
if (!empty($element['#instance']['widget']['settings']['no_fieldset']) && $element['#field']['cardinality'] == 1) {
$element['date']['#title'] = check_plain($element['#instance']['label']);
$element['date']['#title_display'] = $element['#title_display'];
$element['date']['#required'] = $element['#required'];
}
// Keep the system from creating an error message for the sub-element.
// We'll set our own message on the parent element.
// $element['date']['#required'] = $element['#required'];
@@ -341,7 +353,7 @@ function date_text_element_process($element, &$form_state, $form) {
}
$context = array(
'form' => $form,
'form' => $form,
);
drupal_alter('date_text_process', $element, $form_state, $context);
@@ -349,12 +361,11 @@ function date_text_element_process($element, &$form_state, $form) {
}
/**
* Validation for text input.
* Validation for text input.
*
* When used as a Views widget, the validation step always gets triggered,
* even with no form submission. Before form submission $element['#value']
* contains a string, after submission it contains an array.
*
*/
function date_text_validate($element, &$form_state) {
if (date_hidden_element($element)) {
@@ -367,6 +378,11 @@ function date_text_validate($element, &$form_state) {
$input_exists = NULL;
$input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists);
// Trim extra spacing off user input of text fields.
if (isset($input['date'])) {
$input['date'] = trim($input['date']);
}
drupal_alter('date_text_pre_validate', $element, $form_state, $input);
$label = !empty($element['#date_title']) ? $element['#date_title'] : (!empty($element['#title']) ? $element['#title'] : '');
@@ -421,7 +437,14 @@ function date_text_input_date($element, $input) {
* Element value callback for date_select element.
*/
function date_select_element_value_callback($element, $input = FALSE, &$form_state = array()) {
$return = array('year' => '', 'month' => '', 'day' => '', 'hour' => '', 'minute' => '', 'second' => '');
$return = array(
'year' => '',
'month' => '',
'day' => '',
'hour' => '',
'minute' => '',
'second' => '',
);
$date = NULL;
if ($input !== FALSE) {
$return = $input;
@@ -431,7 +454,14 @@ function date_select_element_value_callback($element, $input = FALSE, &$form_sta
$date = date_default_date($element);
}
$granularity = date_format_order($element['#date_format']);
$formats = array('year' => 'Y', 'month' => 'n', 'day' => 'j', 'hour' => 'H', 'minute' => 'i', 'second' => 's');
$formats = array(
'year' => 'Y',
'month' => 'n',
'day' => 'j',
'hour' => 'H',
'minute' => 'i',
'second' => 's',
);
foreach ($granularity as $field) {
if ($field != 'timezone') {
$return[$field] = date_is_date($date) ? $date->format($formats[$field]) : '';
@@ -449,7 +479,6 @@ function date_select_element_value_callback($element, $input = FALSE, &$form_sta
*
* The exact parts displayed in the field are those in #date_granularity.
* The display of each part comes from ['#date_settings']['format'].
*
*/
function date_select_element_process($element, &$form_state, $form) {
if (date_hidden_element($element)) {
@@ -473,7 +502,14 @@ function date_select_element_process($element, &$form_state, $form) {
// Store a hidden value for all date parts not in the current display.
$granularity = date_format_order($element['#date_format']);
$formats = array('year' => 'Y', 'month' => 'n', 'day' => 'j', 'hour' => 'H', 'minute' => 'i', 'second' => 's');
$formats = array(
'year' => 'Y',
'month' => 'n',
'day' => 'j',
'hour' => 'H',
'minute' => 'i',
'second' => 's',
);
foreach (date_nongranularity($granularity) as $field) {
if ($field != 'timezone') {
$element[$field] = array(
@@ -490,7 +526,7 @@ function date_select_element_process($element, &$form_state, $form) {
}
$context = array(
'form' => $form,
'form' => $form,
);
drupal_alter('date_select_process', $element, $form_state, $context);
@@ -521,7 +557,7 @@ function date_parts_element($element, $date, $format) {
$sub_element = array('#granularity' => $granularity);
$order = array_flip($granularity);
$hours_format = strpos(strtolower($element['#date_format']), 'a') ? 'g': 'G';
$hours_format = strpos(strtolower($element['#date_format']), 'a') ? 'g' : 'G';
$month_function = strpos($element['#date_format'], 'F') !== FALSE ? 'date_month_names' : 'date_month_names_abbr';
$count = 0;
$increment = min(intval($element['#date_increment']), 1);
@@ -539,26 +575,29 @@ function date_parts_element($element, $date, $format) {
switch ($field) {
case 'year':
$range = date_range_years($element['#date_year_range'], $date);
$min_year = $range[0];
$max_year = $range[1];
$start_year = $range[0];
$end_year = $range[1];
$sub_element[$field]['#default_value'] = is_object($date) ? $date->format('Y') : '';
if ($part_type == 'select') {
$sub_element[$field]['#options'] = drupal_map_assoc(date_years($min_year, $max_year, $part_required));
$sub_element[$field]['#options'] = drupal_map_assoc(date_years($start_year, $end_year, $part_required));
}
break;
case 'month':
$sub_element[$field]['#default_value'] = is_object($date) ? $date->format('n') : '';
if ($part_type == 'select') {
$sub_element[$field]['#options'] = $month_function($part_required);
}
break;
case 'day':
$sub_element[$field]['#default_value'] = is_object($date) ? $date->format('j') : '';
if ($part_type == 'select') {
$sub_element[$field]['#options'] = drupal_map_assoc(date_days($part_required));
}
break;
case 'hour':
$sub_element[$field]['#default_value'] = is_object($date) ? $date->format($hours_format) : '';
if ($part_type == 'select') {
@@ -566,6 +605,7 @@ function date_parts_element($element, $date, $format) {
}
$sub_element[$field]['#prefix'] = theme('date_part_hour_prefix', $element);
break;
case 'minute':
$sub_element[$field]['#default_value'] = is_object($date) ? $date->format('i') : '';
if ($part_type == 'select') {
@@ -573,6 +613,7 @@ function date_parts_element($element, $date, $format) {
}
$sub_element[$field]['#prefix'] = theme('date_part_minsec_prefix', $element);
break;
case 'second':
$sub_element[$field]['#default_value'] = is_object($date) ? $date->format('s') : '';
if ($part_type == 'select') {
@@ -181,6 +181,7 @@ function date_ical_parse($icaldatafolded = array()) {
$parent[array_pop($parents)][] = array_pop($subgroups);
}
break;
// Add the timezones in with their index their TZID.
case 'VTIMEZONE':
$subgroup = end($subgroups);
@@ -196,6 +197,7 @@ function date_ical_parse($icaldatafolded = array()) {
array_pop($subgroups);
array_pop($parents);
break;
// Do some fun stuff with durations and all_day events and then append
// to parent.
case 'VEVENT':
@@ -222,9 +224,9 @@ function date_ical_parse($icaldatafolded = array()) {
// assumes the end date is inclusive.
if (!empty($subgroup['DTEND']) && (!empty($subgroup['DTEND']['all_day']))) {
// Make the end date one day earlier.
$date = new DateObject ($subgroup['DTEND']['datetime'] . ' 00:00:00', $subgroup['DTEND']['tz']);
$date = new DateObject($subgroup['DTEND']['datetime'] . ' 00:00:00', $subgroup['DTEND']['tz']);
date_modify($date, '-1 day');
$subgroup['DTEND']['datetime'] = date_format($date, 'Y-m-d');
$subgroup['DTEND']['datetime'] = date_format($date, 'Y-m-d');
}
// If a start datetime is defined AND there is no definition for
// the end datetime THEN make the end datetime equal the start
@@ -239,7 +241,7 @@ function date_ical_parse($icaldatafolded = array()) {
if (!empty($subgroup['DTSTART']['all_day'])) {
$subgroup['all_day'] = TRUE;
}
// Add this element to the parent as an array under the
// Add this element to the parent as an array under the.
prev($subgroups);
$parent = &$subgroups[key($subgroups)];
@@ -264,12 +266,13 @@ function date_ical_parse($icaldatafolded = array()) {
$field = !empty($matches[2]) ? $matches[2] : '';
$data = !empty($matches[3]) ? $matches[3] : '';
$parse_result = '';
switch ($name) {
// Keep blank lines out of the results.
case '':
break;
// Lots of properties have date values that must be parsed out.
// Lots of properties have date values that must be parsed out.
case 'CREATED':
case 'LAST-MODIFIED':
case 'DTSTART':
@@ -317,9 +320,9 @@ function date_ical_parse($icaldatafolded = array()) {
$parse_result = date_ical_parse_location($field, $data);
break;
// For all other properties, just store the property and the value.
// This can be expanded on in the future if other properties should
// be given special treatment.
// For all other properties, just store the property and the value.
// This can be expanded on in the future if other properties should
// be given special treatment.
default:
$parse_result = $data;
break;
@@ -360,7 +363,7 @@ function date_ical_parse($icaldatafolded = array()) {
* has no timezone; the ical specs say no timezone
* conversion should be done if no timezone info is
* supplied
* @todo
* @todo
* Another option for dates is the format PROPERTY;VALUE=PERIOD:XXXX. The
* period may include a duration, or a date and a duration, or two dates, so
* would have to be split into parts and run through date_ical_parse_date()
@@ -401,6 +404,7 @@ function date_ical_parse_date($field, $data) {
// Date.
$datetime = date_pad($regs[1]) . '-' . date_pad($regs[2]) . '-' . date_pad($regs[3]);
break;
case 'DATE-TIME':
preg_match(DATE_REGEX_ICAL_DATETIME, $data, $regs);
// Date.
@@ -519,12 +523,12 @@ function date_ical_parse_duration(&$subgroup, $field = 'DURATION') {
$data = $items['DATA'];
preg_match('/^P(\d{1,4}[Y])?(\d{1,2}[M])?(\d{1,2}[W])?(\d{1,2}[D])?([T]{0,1})?(\d{1,2}[H])?(\d{1,2}[M])?(\d{1,2}[S])?/', $data, $duration);
$items['year'] = isset($duration[1]) ? str_replace('Y', '', $duration[1]) : '';
$items['month'] = isset($duration[2]) ?str_replace('M', '', $duration[2]) : '';
$items['week'] = isset($duration[3]) ?str_replace('W', '', $duration[3]) : '';
$items['day'] = isset($duration[4]) ?str_replace('D', '', $duration[4]) : '';
$items['hour'] = isset($duration[6]) ?str_replace('H', '', $duration[6]) : '';
$items['minute'] = isset($duration[7]) ?str_replace('M', '', $duration[7]) : '';
$items['second'] = isset($duration[8]) ?str_replace('S', '', $duration[8]) : '';
$items['month'] = isset($duration[2]) ? str_replace('M', '', $duration[2]) : '';
$items['week'] = isset($duration[3]) ? str_replace('W', '', $duration[3]) : '';
$items['day'] = isset($duration[4]) ? str_replace('D', '', $duration[4]) : '';
$items['hour'] = isset($duration[6]) ? str_replace('H', '', $duration[6]) : '';
$items['minute'] = isset($duration[7]) ? str_replace('M', '', $duration[7]) : '';
$items['second'] = isset($duration[8]) ? str_replace('S', '', $duration[8]) : '';
$start_date = array_key_exists('DTSTART', $subgroup) ? $subgroup['DTSTART']['datetime'] : date_format(date_now(), DATE_FORMAT_ISO);
$timezone = array_key_exists('DTSTART', $subgroup) ? $subgroup['DTSTART']['tz'] : variable_get('date_default_timezone');
if (empty($timezone)) {
@@ -542,7 +546,7 @@ function date_ical_parse_duration(&$subgroup, $field = 'DURATION') {
'datetime' => date_format($date2, DATE_FORMAT_DATETIME),
'all_day' => isset($subgroup['DTSTART']['all_day']) ? $subgroup['DTSTART']['all_day'] : 0,
'tz' => $timezone,
);
);
$duration = date_format($date2, 'U') - date_format($date, 'U');
$subgroup['DURATION'] = array('DATA' => $data, 'DURATION' => $duration);
}
@@ -631,7 +635,6 @@ function date_ical_date($ical_date, $to_tz = FALSE) {
*
* @return string
* Escaped text
*
*/
function date_ical_escape_text($text) {
$text = drupal_html_to_text($text);
@@ -693,14 +696,14 @@ function date_ical_escape_text($text) {
* )
*/
function date_api_ical_build_rrule($form_values) {
$RRULE = '';
$rrule = '';
if (empty($form_values) || !is_array($form_values)) {
return $RRULE;
return $rrule;
}
// Grab the RRULE data and put them into iCal RRULE format.
$RRULE .= 'RRULE:FREQ=' . (!array_key_exists('FREQ', $form_values) ? 'DAILY' : $form_values['FREQ']);
$RRULE .= ';INTERVAL=' . (!array_key_exists('INTERVAL', $form_values) ? 1 : $form_values['INTERVAL']);
$rrule .= 'RRULE:FREQ=' . (!array_key_exists('FREQ', $form_values) ? 'DAILY' : $form_values['FREQ']);
$rrule .= ';INTERVAL=' . (!array_key_exists('INTERVAL', $form_values) ? 1 : $form_values['INTERVAL']);
// Unset the empty 'All' values.
if (array_key_exists('BYDAY', $form_values) && is_array($form_values['BYDAY'])) {
@@ -713,14 +716,14 @@ function date_api_ical_build_rrule($form_values) {
unset($form_values['BYMONTHDAY']['']);
}
if (array_key_exists('BYDAY', $form_values) && is_array($form_values['BYDAY']) && $BYDAY = implode(",", $form_values['BYDAY'])) {
$RRULE .= ';BYDAY=' . $BYDAY;
if (array_key_exists('BYDAY', $form_values) && is_array($form_values['BYDAY']) && $byday = implode(",", $form_values['BYDAY'])) {
$rrule .= ';BYDAY=' . $byday;
}
if (array_key_exists('BYMONTH', $form_values) && is_array($form_values['BYMONTH']) && $BYMONTH = implode(",", $form_values['BYMONTH'])) {
$RRULE .= ';BYMONTH=' . $BYMONTH;
if (array_key_exists('BYMONTH', $form_values) && is_array($form_values['BYMONTH']) && $bymonth = implode(",", $form_values['BYMONTH'])) {
$rrule .= ';BYMONTH=' . $bymonth;
}
if (array_key_exists('BYMONTHDAY', $form_values) && is_array($form_values['BYMONTHDAY']) && $BYMONTHDAY = implode(",", $form_values['BYMONTHDAY'])) {
$RRULE .= ';BYMONTHDAY=' . $BYMONTHDAY;
if (array_key_exists('BYMONTHDAY', $form_values) && is_array($form_values['BYMONTHDAY']) && $bymonthday = implode(",", $form_values['BYMONTHDAY'])) {
$rrule .= ';BYMONTHDAY=' . $bymonthday;
}
// The UNTIL date is supposed to always be expressed in UTC.
// The input date values may already have been converted to a date object on a
@@ -731,8 +734,17 @@ function date_api_ical_build_rrule($form_values) {
if (!is_object($form_values['UNTIL']['datetime'])) {
// If this is a date without time, give it time.
if (strlen($form_values['UNTIL']['datetime']) < 11) {
$granularity_options = drupal_map_assoc(array(
'year',
'month',
'day',
'hour',
'minute',
'second',
));
$form_values['UNTIL']['datetime'] .= ' 23:59:59';
$form_values['UNTIL']['granularity'] = serialize(drupal_map_assoc(array('year', 'month', 'day', 'hour', 'minute', 'second')));
$form_values['UNTIL']['granularity'] = serialize($granularity_options);
$form_values['UNTIL']['all_day'] = FALSE;
}
$until = date_ical_date($form_values['UNTIL'], 'UTC');
@@ -740,21 +752,21 @@ function date_api_ical_build_rrule($form_values) {
else {
$until = $form_values['UNTIL']['datetime'];
}
$RRULE .= ';UNTIL=' . date_format($until, DATE_FORMAT_ICAL) . 'Z';
$rrule .= ';UNTIL=' . date_format($until, DATE_FORMAT_ICAL) . 'Z';
}
// Our form doesn't allow a value for COUNT, but it may be needed by
// modules using the API, so add it to the rule.
if (array_key_exists('COUNT', $form_values)) {
$RRULE .= ';COUNT=' . $form_values['COUNT'];
$rrule .= ';COUNT=' . $form_values['COUNT'];
}
// iCal rules presume the week starts on Monday unless otherwise specified,
// so we'll specify it.
if (array_key_exists('WKST', $form_values)) {
$RRULE .= ';WKST=' . $form_values['WKST'];
$rrule .= ';WKST=' . $form_values['WKST'];
}
else {
$RRULE .= ';WKST=' . date_repeat_dow2day(variable_get('date_first_day', 0));
$rrule .= ';WKST=' . date_repeat_dow2day(variable_get('date_first_day', 0));
}
// Exceptions dates go last, on their own line.
@@ -765,7 +777,7 @@ function date_api_ical_build_rrule($form_values) {
foreach ($form_values['EXDATE'] as $value) {
if (!empty($value['datetime'])) {
$date = !is_object($value['datetime']) ? date_ical_date($value, 'UTC') : $value['datetime'];
$ex_date = !empty($date) ? date_format($date, DATE_FORMAT_ICAL) . 'Z': '';
$ex_date = !empty($date) ? date_format($date, DATE_FORMAT_ICAL) . 'Z' : '';
if (!empty($ex_date)) {
$ex_dates[] = $ex_date;
}
@@ -773,11 +785,11 @@ function date_api_ical_build_rrule($form_values) {
}
if (!empty($ex_dates)) {
sort($ex_dates);
$RRULE .= chr(13) . chr(10) . 'EXDATE:' . implode(',', $ex_dates);
$rrule .= chr(13) . chr(10) . 'EXDATE:' . implode(',', $ex_dates);
}
}
elseif (!empty($form_values['EXDATE'])) {
$RRULE .= chr(13) . chr(10) . 'EXDATE:' . $form_values['EXDATE'];
$rrule .= chr(13) . chr(10) . 'EXDATE:' . $form_values['EXDATE'];
}
// Exceptions dates go last, on their own line.
@@ -785,19 +797,19 @@ function date_api_ical_build_rrule($form_values) {
$ex_dates = array();
foreach ($form_values['RDATE'] as $value) {
$date = !is_object($value['datetime']) ? date_ical_date($value, 'UTC') : $value['datetime'];
$ex_date = !empty($date) ? date_format($date, DATE_FORMAT_ICAL) . 'Z': '';
$ex_date = !empty($date) ? date_format($date, DATE_FORMAT_ICAL) . 'Z' : '';
if (!empty($ex_date)) {
$ex_dates[] = $ex_date;
}
}
if (!empty($ex_dates)) {
sort($ex_dates);
$RRULE .= chr(13) . chr(10) . 'RDATE:' . implode(',', $ex_dates);
$rrule .= chr(13) . chr(10) . 'RDATE:' . implode(',', $ex_dates);
}
}
elseif (!empty($form_values['RDATE'])) {
$RRULE .= chr(13) . chr(10) . 'RDATE:' . $form_values['RDATE'];
$rrule .= chr(13) . chr(10) . 'RDATE:' . $form_values['RDATE'];
}
return $RRULE;
return $rrule;
}
@@ -23,13 +23,14 @@ function date_sql_concat($array) {
switch (Database::getConnection()->databaseType()) {
case 'mysql':
return "CONCAT(" . implode(",", $array) . ")";
case 'pgsql':
return implode(" || ", $array);
}
}
/**
* Helper function to do cross-database NULL replacements
* Helper function to do cross-database NULL replacements.
*
* @param array $array
* An array of values to test for NULL values.
@@ -61,6 +62,7 @@ function date_sql_pad($str, $size = 2, $pad = '0', $side = 'l') {
switch ($side) {
case 'r':
return "RPAD($str, $size, '$pad')";
default:
return "LPAD($str, $size, '$pad')";
}
@@ -69,6 +71,7 @@ function date_sql_pad($str, $size = 2, $pad = '0', $side = 'l') {
/**
* A class to manipulate date SQL.
*/
// @codingStandardsIgnoreStart
class date_sql_handler {
var $db_type = NULL;
var $date_type = DATE_DATETIME;
@@ -86,7 +89,7 @@ class date_sql_handler {
/**
* The object constuctor.
*/
function __construct($date_type = DATE_DATETIME, $local_timezone = NULL, $offset = '+00:00') {
public function __construct($date_type = DATE_DATETIME, $local_timezone = NULL, $offset = '+00:00') {
$this->db_type = Database::getConnection()->databaseType();
$this->date_type = $date_type;
$this->db_timezone = 'UTC';
@@ -97,7 +100,7 @@ class date_sql_handler {
/**
* See if the db has timezone name support.
*/
function db_tz_support($reset = FALSE) {
public function db_tz_support($reset = FALSE) {
$has_support = variable_get('date_db_tz_support', -1);
if ($has_support == -1 || $reset) {
$has_support = FALSE;
@@ -108,6 +111,7 @@ class date_sql_handler {
$has_support = TRUE;
}
break;
case 'pgsql':
$test = db_query("SELECT '2008-02-15 12:00:00 UTC' AT TIME ZONE 'US/Central'")->fetchField();
if ($test == '2008-02-15 06:00:00') {
@@ -136,7 +140,7 @@ class date_sql_handler {
* set a fixed offset, not a timezone, so any value other than
* '+00:00' should be used with caution.
*/
function set_db_timezone($offset = '+00:00') {
public function set_db_timezone($offset = '+00:00') {
static $already_set = FALSE;
$type = Database::getConnection()->databaseType();
if (!$already_set) {
@@ -144,9 +148,11 @@ class date_sql_handler {
case 'mysql':
db_query("SET @@session.time_zone = '$offset'");
break;
case 'pgsql':
db_query("SET TIME ZONE INTERVAL '$offset' HOUR TO MINUTE");
break;
case 'sqlsrv':
// Issue #1201342, This is the wrong way to set the timezone, this
// still needs to be fixed. In the meantime, commenting this out makes
@@ -161,7 +167,7 @@ class date_sql_handler {
/**
* Return timezone offset for the date being processed.
*/
function get_offset($comp_date = NULL) {
public function get_offset($comp_date = NULL) {
if (!empty($this->db_timezone) && !empty($this->local_timezone)) {
if ($this->db_timezone != $this->local_timezone) {
if (empty($comp_date)) {
@@ -199,47 +205,57 @@ class date_sql_handler {
case DATE_UNIX:
$field = "FROM_UNIXTIME($field)";
break;
case DATE_ISO:
$field = "STR_TO_DATE($field, '%Y-%m-%dT%T')";
break;
case DATE_DATETIME:
break;
}
break;
case 'pgsql':
switch ($this->date_type) {
case DATE_UNIX:
$field = "$field::ABSTIME";
break;
case DATE_ISO:
$field = "TO_DATE($field, 'FMYYYY-FMMM-FMDDTFMHH24:FMMI:FMSS')";
break;
case DATE_DATETIME:
break;
}
break;
case 'sqlite':
switch ($this->date_type) {
case DATE_UNIX:
$field = "datetime($field, 'unixepoch')";
break;
case DATE_ISO:
case DATE_DATETIME:
$field = "datetime($field)";
break;
}
break;
case 'sqlsrv':
switch ($this->date_type) {
case DATE_UNIX:
$field = "DATEADD(s, $field, '19700101 00:00:00:000')";
break;
case DATE_ISO:
case DATE_DATETIME:
$field = "CAST($field as smalldatetime)";
break;
}
break;
break;
}
// Adjust the resulting value to the right timezone/offset.
@@ -254,10 +270,13 @@ class date_sql_handler {
switch ($this->db_type) {
case 'mysql':
return "ADDTIME($field, SEC_TO_TIME($offset))";
case 'pgsql':
return "($field + INTERVAL '$offset SECONDS')";;
return "($field + INTERVAL '$offset SECONDS')";
case 'sqlite':
return "datetime($field, '$offset seconds')";
case 'sqlsrv':
return "DATEADD(second, $offset, $field)";
}
@@ -285,6 +304,7 @@ class date_sql_handler {
switch ($direction) {
case 'ADD':
return "DATE_ADD($field, INTERVAL $count $granularity)";
case 'SUB':
return "DATE_SUB($field, INTERVAL $count $granularity)";
}
@@ -294,6 +314,7 @@ class date_sql_handler {
switch ($direction) {
case 'ADD':
return "($field + INTERVAL '$count $granularity')";
case 'SUB':
return "($field - INTERVAL '$count $granularity')";
}
@@ -302,6 +323,7 @@ class date_sql_handler {
switch ($direction) {
case 'ADD':
return "datetime($field, '+$count $granularity')";
case 'SUB':
return "datetime($field, '-$count $granularity')";
}
@@ -352,6 +374,7 @@ class date_sql_handler {
switch ($this->db_type) {
case 'mysql':
return "CONVERT_TZ($field, $db_zone, $localzone)";
case 'pgsql':
// WITH TIME ZONE assumes the date is using the system
// timezone, which should have been set to UTC.
@@ -395,6 +418,7 @@ class date_sql_handler {
);
$format = strtr($format, $replace);
return "DATE_FORMAT($field, '$format')";
case 'pgsql':
$replace = array(
'Y' => 'YYYY',
@@ -421,6 +445,7 @@ class date_sql_handler {
);
$format = strtr($format, $replace);
return "TO_CHAR($field, '$format')";
case 'sqlite':
$replace = array(
// 4 digit year number.
@@ -460,6 +485,7 @@ class date_sql_handler {
);
$format = strtr($format, $replace);
return "strftime('$format', $field)";
case 'sqlsrv':
$replace = array(
// 4 digit year number.
@@ -528,18 +554,25 @@ class date_sql_handler {
switch (strtoupper($extract_type)) {
case 'DATE':
return $field;
case 'YEAR':
return "EXTRACT(YEAR FROM($field))";
case 'MONTH':
return "EXTRACT(MONTH FROM($field))";
case 'DAY':
return "EXTRACT(DAY FROM($field))";
case 'HOUR':
return "EXTRACT(HOUR FROM($field))";
case 'MINUTE':
return "EXTRACT(MINUTE FROM($field))";
case 'SECOND':
return "EXTRACT(SECOND FROM($field))";
// ISO week number for date.
case 'WEEK':
switch ($this->db_type) {
@@ -547,6 +580,7 @@ class date_sql_handler {
// WEEK using arg 3 in MySQl should return the same value as
// Postgres EXTRACT.
return "WEEK($field, 3)";
case 'pgsql':
return "EXTRACT(WEEK FROM($field))";
}
@@ -556,6 +590,7 @@ class date_sql_handler {
// MySQL returns 1 for Sunday through 7 for Saturday, PHP date
// functions and Postgres use 0 for Sunday and 6 for Saturday.
return "INTEGER(DAYOFWEEK($field) - 1)";
case 'pgsql':
return "EXTRACT(DOW FROM($field))";
}
@@ -563,6 +598,7 @@ class date_sql_handler {
switch ($this->db_type) {
case 'mysql':
return "DAYOFYEAR($field)";
case 'pgsql':
return "EXTRACT(DOY FROM($field))";
}
@@ -775,8 +811,7 @@ class date_sql_handler {
}
/**
* Create a complete datetime value out of an
* incomplete array of selected values.
* Create a complete date/time value out of an incomplete array of values.
*
* For example, array('year' => 2008, 'month' => 05) will fill
* in the day, hour, minute and second with the earliest possible
@@ -795,9 +830,11 @@ class date_sql_handler {
case 'empty_min':
case 'min':
return date_format($dates[0], 'Y-m-d H:i:s');
case 'empty_max':
case 'max':
return date_format($dates[1], 'Y-m-d H:i:s');
default:
return;
}
@@ -840,7 +877,7 @@ class date_sql_handler {
}
/**
* A function to test the validity of various date parts
* A function to test the validity of various date parts.
*/
function part_is_valid($value, $type) {
if (!preg_match('/^[0-9]*$/', $value)) {
@@ -856,16 +893,19 @@ class date_sql_handler {
return FALSE;
}
break;
case 'month':
if ($value < 0 || $value > 12) {
return FALSE;
}
break;
case 'day':
if ($value < 0 || $value > 31) {
return FALSE;
}
break;
case 'week':
if ($value < 0 || $value > 53) {
return FALSE;
@@ -890,26 +930,36 @@ class date_sql_handler {
$formats['display'] = 'Y';
$formats['sql'] = 'Y';
break;
case 'month':
$formats['display'] = date_limit_format($short, array('year', 'month'));
$formats['sql'] = 'Y-m';
break;
case 'day':
$formats['display'] = date_limit_format($short, array('year', 'month', 'day'));
$args = array('year', 'month', 'day');
$formats['display'] = date_limit_format($short, $args);
$formats['sql'] = 'Y-m-d';
break;
case 'hour':
$formats['display'] = date_limit_format($short, array('year', 'month', 'day', 'hour'));
$args = array('year', 'month', 'day', 'hour');
$formats['display'] = date_limit_format($short, $args);
$formats['sql'] = 'Y-m-d\TH';
break;
case 'minute':
$formats['display'] = date_limit_format($short, array('year', 'month', 'day', 'hour', 'minute'));
$args = array('year', 'month', 'day', 'hour', 'minute');
$formats['display'] = date_limit_format($short, $args);
$formats['sql'] = 'Y-m-d\TH:i';
break;
case 'second':
$formats['display'] = date_limit_format($short, array('year', 'month', 'day', 'hour', 'minute', 'second'));
$args = array('year', 'month', 'day', 'hour', 'minute', 'second');
$formats['display'] = date_limit_format($short, $args);
$formats['sql'] = 'Y-m-d\TH:i:s';
break;
case 'week':
$formats['display'] = 'F j Y (W)';
$formats['sql'] = 'Y-\WW';
@@ -927,7 +977,7 @@ class date_sql_handler {
'#type' => 'radios',
'#default_value' => $granularity,
'#options' => $this->date_parts(),
);
);
return $form;
}
@@ -1030,7 +1080,6 @@ class date_sql_handler {
$direction = $results[1];
$count = $results[2];
$item = $results[3];
$replace = array(
'now' => '@',
'+' => 'P',
@@ -1051,14 +1100,27 @@ class date_sql_handler {
'second' => 'S',
' ' => '',
' ' => '',
);
$prefix = in_array($item, array('hours', 'hour', 'minutes', 'minute', 'seconds', 'second')) ? 'T' : '';
return $prefix . strtr($direction, $replace) . $count . strtr($item, $replace);
);
$args = array('hours', 'hour', 'minutes', 'minute', 'seconds', 'second');
if (in_array($item, $args)) {
$prefix = 'T';
}
else {
$prefix = '';
}
$return = $prefix;
$return .= strtr($direction, $replace);
$return .= $count;
$return .= strtr($item, $replace);
return $return;
}
/**
* Use the parsed values from the ISO argument to determine the
* granularity of this period.
* Granularity arguments handler.
*
* Use the parsed values from the ISO argument
* to determine the granularity of this period.
*/
function arg_granularity($arg) {
$granularity = '';
@@ -1137,8 +1199,9 @@ class date_sql_handler {
}
return array($min_date, $max_date);
}
// Intercept invalid info and fall back to the current date.
// Intercept invalid info and fall back to the current date.
$now = date_now();
return array($now, $now);
}
}
// @codingStandardsIgnoreEnd
@@ -206,24 +206,31 @@ function theme_date_time_ago($variables) {
$now = date_format(date_now(), DATE_FORMAT_UNIX);
$start = date_format($start_date, DATE_FORMAT_UNIX);
// will be positive for a datetime in the past (ago), and negative for a datetime in the future (hence)
// Will be positive for a datetime in the past (ago), and negative for a datetime in the future (hence).
$time_diff = $now - $start;
// Uses the same options used by Views format_interval.
switch ($display) {
case 'raw time ago':
return format_interval($time_diff, $interval);
case 'time ago':
return t('%time ago', array('%time' => format_interval($time_diff, $interval)));
case 'raw time hence':
return format_interval(-$time_diff, $interval);
case 'time hence':
return t('%time hence', array('%time' => format_interval(-$time_diff, $interval)));
case 'raw time span':
return ($time_diff < 0 ? '-' : '') . format_interval(abs($time_diff), $interval);
case 'inverse time span':
return ($time_diff > 0 ? '-' : '') . format_interval(abs($time_diff), $interval);
case 'time span':
return t(($time_diff < 0 ? '%time hence' : '%time ago'), array('%time' => format_interval(abs($time_diff), $interval)));
}
}
@@ -8,9 +8,9 @@ dependencies[] = context
files[] = date_context.module
files[] = plugins/date_context_date_condition.inc
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -1,5 +1,8 @@
<?php
/**
* @file
* Add an option to set/not set the context on forms vs views.
*
* @TODO
*
* Currently only implemented for nodes. Need to add $plugin->execute()
@@ -8,8 +11,6 @@
* Cache the date processing, perhaps cache the formatted, timezone-adjusted
* date strings for each entity (would have to be cached differently for each
* timezone, based on the tz_handling method for the date).
*
* Add an option to set/not set the context on forms vs views.
*/
/**
@@ -22,7 +23,7 @@ function date_context_context_node_condition_alter($node, $op) {
}
/**
* Implements hook_context_plugins()
* Implements hook_context_plugins().
*/
function date_context_context_plugins() {
$plugins = array();
@@ -38,7 +39,7 @@ function date_context_context_plugins() {
}
/**
* Implements hook_context_registry()
* Implements hook_context_registry().
*/
function date_context_context_registry() {
return array(
@@ -51,4 +52,3 @@ function date_context_context_registry() {
),
);
}
@@ -1,10 +1,20 @@
<?php
/**
* @file
* Context date condition plugin.
*/
/**
* Expose term views/term forms by vocabulary as a context condition.
*/
// @codingStandardsIgnoreStart
class date_context_date_condition extends context_condition_node {
function condition_values() {
/**
* {@inheritdoc}
*/
public function condition_values() {
$values = array();
$fields = field_info_fields();
foreach ($fields as $field_name => $field) {
@@ -15,10 +25,13 @@ class date_context_date_condition extends context_condition_node {
return $values;
}
function options_form($context) {
/**
* {@inheritdoc}
*/
public function options_form($context) {
$defaults = $this->fetch_from_context($context, 'options');
$options = array(
'<' => t('Is less than'),
'<' => t('Is less than'),
'<=' => t('Is less than or equal to'),
'>=' => t('Is greater than or equal to'),
'>' => t('Is greater than'),
@@ -27,6 +40,8 @@ class date_context_date_condition extends context_condition_node {
'empty' => t('Is empty'),
'not empty' => t('Is not Empty'),
);
$dependency_options = array('<', '<=', '>', '>=', '=', '!=');
$form['operation'] = array(
'#title' => t('Operation'),
'#type' => 'select',
@@ -41,12 +56,15 @@ class date_context_date_condition extends context_condition_node {
'#description' => t("The value the field should contain to meet the condition. This can either be an absolute date in ISO format (YYYY-MM-DDTHH:MM:SS) or a relative string like '12AM today'. Examples: 2011-12-31T00:00:00, now, now +1 day, 12AM today, Monday next week. <a href=\"@relative_format\">More examples of relative date formats in the PHP documentation</a>.", array('@relative_format' => 'http://www.php.net/manual/en/datetime.formats.relative.php')),
'#default_value' => isset($defaults['value']) ? $defaults['value'] : '',
'#process' => array('ctools_dependent_process'),
'#dependency' => array('edit-conditions-plugins-date-context-date-condition-options-operation' => array('<', '<=', '>', '>=', '=', '!=')),
'#dependency' => array('edit-conditions-plugins-date-context-date-condition-options-operation' => $dependency_options),
);
return $form;
}
function execute($entity, $op) {
/**
* {@inheritdoc}
*/
public function execute($entity, $op) {
if (in_array($op, array('view', 'form'))) {
foreach ($this->get_contexts() as $context) {
$options = $this->fetch_from_context($context, 'options');
@@ -91,32 +109,37 @@ class date_context_date_condition extends context_condition_node {
str_replace('now', 'today', $options['value']);
$date = date_create($options['value'], date_default_timezone_object());
$compdate = $date->format(DATE_FORMAT_DATETIME);
switch($options['operation']) {
switch ($options['operation']) {
case '=':
if ($date2 >= $compdate && $date1 <= $compdate) {
$this->condition_met($context, $field_name);
}
break;
case '>':
if ($date1 > $compdate) {
$this->condition_met($context, $field_name);
}
break;
case '>=':
if ($date1 >= $compdate) {
$this->condition_met($context, $field_name);
}
break;
case '<':
if ($date2 < $compdate) {
$this->condition_met($context, $field_name);
}
break;
case '<=':
if ($date2 <= $compdate) {
$this->condition_met($context, $field_name);
}
break;
case '!=':
if ($date1 < $compdate || $date2 > $compdate) {
$this->condition_met($context, $field_name);
@@ -130,3 +153,4 @@ class date_context_date_condition extends context_condition_node {
}
}
}
// @codingStandardsIgnoreEnd
@@ -40,7 +40,6 @@
*
* - In the field's submission processing, the new date values, which are in
* the local timezone, are converted back to their UTC values and stored.
*
*/
function date_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $base) {
@@ -87,7 +86,7 @@ function date_field_widget_form(&$form, &$form_state, $field, $instance, $langco
}
module_load_include('inc', 'date_api', 'date_api_elements');
$timezone = date_get_timezone($field['settings']['tz_handling'], isset($items[0]['timezone']) ? $items[0]['timezone'] : date_default_timezone());
$timezone = date_get_timezone($field['settings']['tz_handling'], isset($items[$delta]['timezone']) ? $items[$delta]['timezone'] : date_default_timezone());
// TODO see if there's a way to keep the timezone element from ever being
// nested as array('timezone' => 'timezone' => value)). After struggling
@@ -122,7 +121,13 @@ function date_field_widget_form(&$form, &$form_state, $field, $instance, $langco
'#weight' => $instance['widget']['weight'] + 1,
'#attributes' => array('class' => array('date-no-float')),
'#date_label_position' => $instance['widget']['settings']['label_position'],
);
);
}
// Make changes if instance is set to be rendered as a regular field.
if (!empty($instance['widget']['settings']['no_fieldset'])) {
$element['#title'] = check_plain($instance['label']);
$element['#theme_wrappers'] = ($field['cardinality'] == 1) ? array('date_form_element') : array();
}
return $element;
@@ -148,6 +153,7 @@ function date_local_date($item, $timezone, $field, $instance, $part = 'value') {
// @TODO Figure out how to replace date_fuzzy_datetime() function.
// Special case for ISO dates to create a valid date object for formatting.
// Is this still needed?
// @codingStandardsIgnoreStart
/*
if ($field['type'] == DATE_ISO) {
$value = date_fuzzy_datetime($value);
@@ -157,6 +163,7 @@ function date_local_date($item, $timezone, $field, $instance, $part = 'value') {
$value = date_convert($value, $field['type'], DATE_DATETIME, $db_timezone);
}
*/
// @codingStandardsIgnoreEnd
$date = new DateObject($value, date_get_timezone_db($field['settings']['tz_handling']));
$date->limitGranularity($field['settings']['granularity']);
@@ -193,8 +200,7 @@ function date_default_value($field, $instance, $langcode) {
}
/**
* Helper function for the date default value callback to set
* either 'value' or 'value2' to its default value.
* Helper function for the date default value callback to set either 'value' or 'value2' to its default value.
*/
function date_default_value_part($item, $field, $instance, $langcode, $part = 'value') {
$timezone = date_get_timezone($field['settings']['tz_handling']);
@@ -241,7 +247,6 @@ function date_default_value_part($item, $field, $instance, $langcode, $part = 'v
* Process an individual date element.
*/
function date_combo_element_process($element, &$form_state, $form) {
if (date_hidden_element($element)) {
// A hidden value for a new entity that had its end date set to blank
// will not get processed later to populate the end date, so set it here.
@@ -296,6 +301,7 @@ function date_combo_element_process($element, &$form_state, $form) {
// Blank out the end date for optional end dates that match the start date,
// except when this is a new node that has default values that should be honored.
if (!$date_is_default && $field['settings']['todate'] != 'required'
&& is_array($element['#default_value'])
&& !empty($element['#default_value'][$to_field])
&& $element['#default_value'][$to_field] == $element['#default_value'][$from_field]) {
unset($element['#default_value'][$to_field]);
@@ -329,9 +335,9 @@ function date_combo_element_process($element, &$form_state, $form) {
'#date_increment' => $instance['widget']['settings']['increment'],
'#date_year_range' => $instance['widget']['settings']['year_range'],
'#date_label_position' => $instance['widget']['settings']['label_position'],
);
);
$description = !empty($element['#description']) ? t($element['#description']) : '';
$description = !empty($element['#description']) ? t($element['#description']) : '';
unset($element['#description']);
// Give this element the right type, using a Date API
@@ -347,11 +353,13 @@ function date_combo_element_process($element, &$form_state, $form) {
$element['#attached']['js'][] = drupal_get_path('module', 'date') . '/date.js';
$element[$from_field]['#ajax'] = !empty($element['#ajax']) ? $element['#ajax'] : FALSE;
break;
case 'date_popup':
$element[$from_field]['#type'] = 'date_popup';
$element[$from_field]['#theme_wrappers'] = array('date_popup');
$element[$from_field]['#ajax'] = !empty($element['#ajax']) ? $element['#ajax'] : FALSE;
break;
default:
$element[$from_field]['#type'] = 'date_text';
$element[$from_field]['#theme_wrappers'] = array('date_text');
@@ -380,8 +388,11 @@ function date_combo_element_process($element, &$form_state, $form) {
if ($field['settings']['todate'] == 'optional') {
$element[$to_field]['#states'] = array(
'visible' => array(
'input[name="' . $show_id . '"]' => array('checked' => TRUE),
));
'input[name="' . $show_id . '"]' => array(
'checked' => TRUE,
),
),
);
}
}
else {
@@ -404,16 +415,27 @@ function date_combo_element_process($element, &$form_state, $form) {
$element[$from_field]['#date_title'] = t('@field_name', array('@field_name' => $instance['label']));
}
// Make changes if instance is set to be rendered as a regular field.
if (!empty($instance['widget']['settings']['no_fieldset'])) {
unset($element[$from_field]['#description']);
if (!empty($field['settings']['todate']) && isset($element['#description'])) {
$element['#description'] .= '<span class="js-hide"> ' . t("Empty 'End date' values will use the 'Start date' values.") . '</span>';
}
}
$context = array(
'field' => $field,
'instance' => $instance,
'form' => $form,
'field' => $field,
'instance' => $instance,
'form' => $form,
);
drupal_alter('date_combo_process', $element, $form_state, $context);
return $element;
}
/**
* Empty a date element.
*/
function date_element_empty($element, &$form_state) {
$item = array();
$item['value'] = NULL;
@@ -428,6 +450,7 @@ function date_element_empty($element, &$form_state) {
/**
* Validate and update a combo element.
*
* Don't try this if there were errors before reaching this point.
*/
function date_combo_validate($element, &$form_state) {
@@ -444,6 +467,10 @@ function date_combo_validate($element, &$form_state) {
$delta = $element['#delta'];
$langcode = $element['#language'];
// Related issue: https://drupal.org/node/2279831.
if (!is_array($element['#field_parents'])) {
$element['#field_parents'] = array();
}
$form_values = drupal_array_get_nested_value($form_state['values'], $element['#field_parents']);
$form_input = drupal_array_get_nested_value($form_state['input'], $element['#field_parents']);
@@ -4,9 +4,9 @@ core = 7.x
package = Date/Time
hidden = TRUE
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -20,9 +20,9 @@ package = "Features"
project = "date_migrate_example"
version = "7.x-2.0"
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -47,8 +47,8 @@ class DateExampleMigration extends XMLMigration {
$xml_folder = drupal_get_path('module', 'date_migrate_example');
$items_url = $xml_folder . '/date_migrate_example.xml';
$item_xpath = '/source_data/item';
$item_ID_xpath = 'id';
$items_class = new MigrateItemsXML($items_url, $item_xpath, $item_ID_xpath);
$item_id_xpath = 'id';
$items_class = new MigrateItemsXML($items_url, $item_xpath, $item_id_xpath);
$this->source = new MigrateSourceMultiItems($items_class, $fields);
$this->destination = new MigrateDestinationNode('date_migrate_example');
@@ -78,7 +78,7 @@ class DateExampleMigration extends XMLMigration {
$this->addFieldMapping('field_datestamp_range:to', 'datestamp_range_to');
// You can specify a timezone to be applied to all values going into the
// field (Tokyo is UTC+9, no DST)
// field (Tokyo is UTC+9, no DST).
$this->addFieldMapping('field_datetime', 'datetime')
->xpath('datetime');
$this->addFieldMapping('field_datetime:timezone')
@@ -107,25 +107,25 @@ class DateExampleMigration extends XMLMigration {
// The date range field can have multiple values.
$current_row->date_range_from = array();
foreach ($current_row->xml->date_range as $range) {
$current_row->date_range_from[] = (string)$range->from[0];
$current_row->date_range_to[] = (string)$range->to[0];
$current_row->date_range_from[] = (string) $range->from[0];
$current_row->date_range_to[] = (string) $range->to[0];
}
$current_row->datestamp_range_from =
(string) $current_row->xml->datestamp_range->from[0];
$current_row->datestamp_range_to =
(string) $current_row->xml->datestamp_range->to[0];
$current_row->datestamp_range_from
= (string) $current_row->xml->datestamp_range->from[0];
$current_row->datestamp_range_to
= (string) $current_row->xml->datestamp_range->to[0];
$current_row->datetime_range_from =
(string) $current_row->xml->datetime_range->from[0];
$current_row->datetime_range_to =
(string) $current_row->xml->datetime_range->to[0];
$current_row->datetime_range_timezone =
(string) $current_row->xml->datetime_range->timezone[0];
$current_row->datetime_range_from
= (string) $current_row->xml->datetime_range->from[0];
$current_row->datetime_range_to
= (string) $current_row->xml->datetime_range->to[0];
$current_row->datetime_range_timezone
= (string) $current_row->xml->datetime_range->timezone[0];
$current_row->date_repeat =
(string) $current_row->xml->date_repeat->date[0];
$current_row->date_repeat_rrule =
(string) $current_row->xml->date_repeat->rule[0];
$current_row->date_repeat
= (string) $current_row->xml->date_repeat->date[0];
$current_row->date_repeat_rrule
= (string) $current_row->xml->date_repeat->rule[0];
}
}
@@ -7,9 +7,9 @@ configure = admin/config/date/date_popup
stylesheets[all][] = themes/datepicker.1.7.css
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"
@@ -5,6 +5,7 @@
* Install, update and uninstall functions for the Date Popup module.
*/
// @codingStandardsIgnoreStart
/**
* Implements hook_install().
*/
@@ -17,6 +18,7 @@ function date_popup_install() {
function date_popup_uninstall() {
}
// @codingStandardsIgnoreEnd
/**
* Implements hook_enable().
@@ -1,62 +1,65 @@
/**
* Attaches the calendar behavior to all required fields
*/
(function ($) {
Drupal.behaviors.date_popup = {
attach: function (context) {
for (var id in Drupal.settings.datePopup) {
$('#'+ id).bind('focus', Drupal.settings.datePopup[id], function(e) {
if (!$(this).hasClass('date-popup-init')) {
var datePopup = e.data;
// Explicitely filter the methods we accept.
switch (datePopup.func) {
case 'datepicker':
$(this)
.datepicker(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
(function($) {
function makeFocusHandler(e) {
if (!$(this).hasClass('date-popup-init')) {
var datePopup = e.data;
// Explicitely filter the methods we accept.
switch (datePopup.func) {
case 'datepicker':
$(this)
.datepicker(datePopup.settings)
.addClass('date-popup-init');
$(this).click(function(){
$(this).focus();
});
break;
case 'timeEntry':
$(this)
.timeEntry(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
case 'timepicker':
// Translate the PHP date format into the style the timepicker uses.
datePopup.settings.timeFormat = datePopup.settings.timeFormat
// 12-hour, leading zero,
.replace('h', 'hh')
// 12-hour, no leading zero.
.replace('g', 'h')
// 24-hour, leading zero.
.replace('H', 'HH')
// 24-hour, no leading zero.
.replace('G', 'H')
// AM/PM.
.replace('A', 'p')
// Minutes with leading zero.
.replace('i', 'mm')
// Seconds with leading zero.
.replace('s', 'ss');
case 'timeEntry':
$(this)
.timeEntry(datePopup.settings)
.addClass('date-popup-init');
$(this).click(function(){
$(this).focus();
});
break;
datePopup.settings.startTime = new Date(datePopup.settings.startTime);
$(this)
.timepicker(datePopup.settings)
.addClass('date-popup-init');
$(this).click(function(){
$(this).focus();
});
break;
}
case 'timepicker':
// Translate the PHP date format into the style the timepicker uses.
datePopup.settings.timeFormat = datePopup.settings.timeFormat
// 12-hour, leading zero,
.replace('h', 'hh')
// 12-hour, no leading zero.
.replace('g', 'h')
// 24-hour, leading zero.
.replace('H', 'HH')
// 24-hour, no leading zero.
.replace('G', 'H')
// AM/PM.
.replace('A', 'p')
// Minutes with leading zero.
.replace('i', 'mm')
// Seconds with leading zero.
.replace('s', 'ss');
datePopup.settings.startTime = new Date(datePopup.settings.startTime);
$(this)
.timepicker(datePopup.settings)
.addClass('date-popup-init');
$(this).click(function(){
$(this).focus();
});
break;
}
});
}
}
}
};
Drupal.behaviors.date_popup = {
attach: function (context) {
for (var id in Drupal.settings.datePopup) {
$('#'+ id).bind('focus', Drupal.settings.datePopup[id], makeFocusHandler);
}
}
};
})(jQuery);
@@ -16,7 +16,6 @@
* If no time elements are included in the format string, only the date
* textfield will be created. If no date elements are included in the format
* string, only the time textfield, will be created.
*
*/
/**
@@ -44,7 +43,7 @@ function date_popup_add() {
/**
* Get the location of the Willington Vega timepicker library.
*
* @return
* @return string
* The location of the library, or FALSE if the library isn't installed.
*/
function date_popup_get_wvega_path() {
@@ -94,9 +93,11 @@ function date_popup_library() {
}
/**
* Create a unique CSS id name and output a single inline JS block for
* each startup function to call and settings array to pass it. This
* used to create a unique CSS class for each unique combination of
* Create a unique CSS id name and output a single inline JS block.
*
* For each startup function to call and settings array to pass it.
*
* This used to create a unique CSS class for each unique combination of
* function and settings, but using classes requires a DOM traversal
* and is much slower than an id lookup. The new approach returns to
* requiring a duplicate copy of the settings/code for every element
@@ -104,17 +105,20 @@ function date_popup_library() {
* putting the ids for each unique function/settings combo into
* Drupal.settings and searching for each listed id.
*
* @param $pfx
* @param string $id
* The CSS class prefix to search the DOM for.
* TODO : unused ?
* @param $func
* The jQuery function to invoke on each DOM element containing the
* returned CSS class.
* @param $settings
*
* @param string $func
* The jQuery function to invoke on each DOM element
* containing the returned CSS class.
*
* @param array $settings
* The settings array to pass to the jQuery function.
*
* @returns
* The CSS id to assign to the element that should have
* $func($settings) invoked on it.
* The CSS id to assign to the element that should have $func($settings)
* invoked on it.
*/
function date_popup_js_settings_id($id, $func, $settings) {
static $js_added = FALSE;
@@ -123,14 +127,15 @@ function date_popup_js_settings_id($id, $func, $settings) {
// Make sure popup date selector grid is in correct year.
if (!empty($settings['yearRange'])) {
$parts = explode(':', $settings['yearRange']);
// Set the default date to 0 or the lowest bound if the date ranges do not include the current year
// Necessary for the datepicker to render and select dates correctly
$defaultDate = ($parts[0] > 0 || 0 > $parts[1]) ? $parts[0] : 0;
$settings += array('defaultDate' => (string) $defaultDate . 'y');
// Set the default date to 0 or the lowest bound if
// the date ranges do not include the current year.
// Necessary for the datepicker to render and select dates correctly.
$default_date = ($parts[0] > 0 || 0 > $parts[1]) ? $parts[0] : 0;
$settings += array('defaultDate' => (string) $default_date . 'y');
}
if (!$js_added) {
drupal_add_js(drupal_get_path('module', 'date_popup') .'/date_popup.js');
drupal_add_js(drupal_get_path('module', 'date_popup') . '/date_popup.js');
$js_added = TRUE;
}
@@ -140,29 +145,35 @@ function date_popup_js_settings_id($id, $func, $settings) {
$id_count[$id] = 0;
}
// It looks like we need the additional id_count for this to
// work correctly when there are multiple values.
// $return_id = "$id-$func-popup";
$return_id = "$id-$func-popup-". $id_count[$id]++;
// It looks like we need the additional id_count for this to
// work correctly when there are multiple values.
// $return_id = "$id-$func-popup";
$return_id = "$id-$func-popup-" . $id_count[$id]++;
$js_settings['datePopup'][$return_id] = array(
'func' => $func,
'settings' => $settings
'settings' => $settings,
);
drupal_add_js($js_settings, 'setting');
return $return_id;
}
/**
* Date popup theme handler.
*/
function date_popup_theme() {
return array(
'date_popup' => array('render element' => 'element'),
);
'date_popup' => array(
'render element' => 'element',
),
);
}
/**
* Implements hook_element_info().
*
* Set the #type to date_popup and fill the element #default_value with
* a date adjusted to the proper local timezone in datetime format (YYYY-MM-DD HH:MM:SS).
* a date adjusted to the proper local timezone in datetime format
* (YYYY-MM-DD HH:MM:SS).
*
* The element will create two textfields, one for the date and one for the
* time. The date textfield will include a jQuery popup calendar date picker,
@@ -218,20 +229,32 @@ function date_popup_element_info() {
return $type;
}
/**
* Date popup date granularity.
*/
function date_popup_date_granularity($element) {
$granularity = date_format_order($element['#date_format']);
return array_intersect($granularity, array('month', 'day', 'year'));
}
/**
* Date popup time granularity.
*/
function date_popup_time_granularity($element) {
$granularity = date_format_order($element['#date_format']);
return array_intersect($granularity, array('hour', 'minute', 'second'));
}
/**
* Date popup date format.
*/
function date_popup_date_format($element) {
return (date_limit_format($element['#date_format'], date_popup_date_granularity($element)));
}
/**
* Date popup time format.
*/
function date_popup_time_format($element) {
return date_popup_format_to_popup_time(date_limit_format($element['#date_format'], date_popup_time_granularity($element)), $element['#timepicker']);
}
@@ -239,6 +262,7 @@ function date_popup_time_format($element) {
/**
* Element value callback for date_popup element.
*/
// @codingStandardsIgnoreStart
function date_popup_element_value_callback($element, $input = FALSE, &$form_state) {
$granularity = date_format_order($element['#date_format']);
$has_time = date_has_time($granularity);
@@ -266,9 +290,11 @@ function date_popup_element_value_callback($element, $input = FALSE, &$form_stat
return $return;
}
// @codingStandardsIgnoreEnd
/**
* Javascript popup element processing.
*
* Add popup attributes to $element.
*/
function date_popup_element_process($element, &$form_state, $form) {
@@ -284,7 +310,9 @@ function date_popup_element_process($element, &$form_state, $form) {
if (!empty($element['#ajax'])) {
$element['#ajax'] += array(
'trigger_as' => array('name' =>$element['#name']),
'trigger_as' => array(
'name' => $element['#name'],
),
'event' => 'change',
);
}
@@ -292,6 +320,18 @@ function date_popup_element_process($element, &$form_state, $form) {
$element['date'] = date_popup_process_date_part($element);
$element['time'] = date_popup_process_time_part($element);
// Make changes if instance is set to be rendered as a regular field.
if (!empty($element['#instance']['widget']['settings']['no_fieldset']) && $element['#field']['cardinality'] == 1) {
if (!empty($element['date']) && empty($element['time'])) {
$element['date']['#title'] = check_plain($element['#instance']['label']);
$element['date']['#required'] = $element['#required'];
}
elseif (empty($element['date']) && !empty($element['time'])) {
$element['time']['#title'] = check_plain($element['#instance']['label']);
$element['time']['#required'] = $element['#required'];
}
}
if (isset($element['#element_validate'])) {
array_push($element['#element_validate'], 'date_popup_validate');
}
@@ -300,7 +340,7 @@ function date_popup_element_process($element, &$form_state, $form) {
}
$context = array(
'form' => $form,
'form' => $form,
);
drupal_alter('date_popup_process', $element, $form_state, $context);
@@ -313,13 +353,22 @@ function date_popup_element_process($element, &$form_state, $form) {
function date_popup_process_date_part(&$element) {
$granularity = date_format_order($element['#date_format']);
$date_granularity = date_popup_date_granularity($element);
if (empty($date_granularity)) return array();
if (empty($date_granularity)) {
return array();
}
// The datepicker can't handle zero or negative values like 0:+1
// even though the Date API can handle them, so rework the value
// we pass to the datepicker to use defaults it can accept (such as +0:+1)
// date_range_string() adds the necessary +/- signs to the range string.
$this_year = date_format(date_now(), 'Y');
// When used as a Views exposed filter widget, $element['#value'] contains an array instead an string.
// Fill the 'date' string in this case.
$mock = NULL;
$callback_values = date_popup_element_value_callback($element, FALSE, $mock);
if (!isset($element['#value']['date']) && isset($callback_values['date'])) {
$element['#value']['date'] = $callback_values['date'];
}
$date = '';
if (!empty($element['#value']['date'])) {
$date = new DateObject($element['#value']['date'], $element['#date_timezone'], date_popup_date_format($element));
@@ -336,8 +385,9 @@ function date_popup_process_date_part(&$element) {
'closeAtTop' => FALSE,
'speed' => 'immediate',
'firstDay' => intval(variable_get('date_first_day', 0)),
//'buttonImage' => base_path() . drupal_get_path('module', 'date_api') ."/images/calendar.png",
//'buttonImageOnly' => TRUE,
// 'buttonImage' => base_path()
// . drupal_get_path('module', 'date_api') ."/images/calendar.png",
// 'buttonImageOnly' => TRUE,
'dateFormat' => date_popup_format_to_popup(date_popup_date_format($element), 'datepicker'),
'yearRange' => $year_range,
// Custom setting, will be expanded in Drupal.behaviors.date_popup()
@@ -347,26 +397,33 @@ function date_popup_process_date_part(&$element) {
// Create a unique id for each set of custom settings.
$id = date_popup_js_settings_id($element['#id'], 'datepicker', $settings);
// Manually build this element and set the value - this will prevent corrupting
// the parent value
// Manually build this element and set the value -
// this will prevent corrupting the parent value.
$parents = array_merge($element['#parents'], array('date'));
$sub_element = array(
'#type' => 'textfield',
'#title' => theme('date_part_label_date', array('part_type' => 'date', 'element' => $element)),
'#title_display' => $element['#date_label_position'] == 'above' ? 'before' : 'invisible',
'#default_value' => $element['#value']['date'],
'#default_value' => date_format_date($date, 'custom', date_popup_date_format($element)),
'#id' => $id,
'#input' => FALSE,
'#size' => !empty($element['#size']) ? $element['#size'] : 20,
'#maxlength' => !empty($element['#maxlength']) ? $element['#maxlength'] : 30,
'#attributes' => $element['#attributes'],
'#parents' => $parents,
'#name' => array_shift($parents) . '['. implode('][', $parents) .']',
'#name' => array_shift($parents) . '[' . implode('][', $parents) . ']',
'#ajax' => !empty($element['#ajax']) ? $element['#ajax'] : FALSE,
);
$sub_element['#value'] = $sub_element['#default_value'];
// TODO, figure out exactly when we want this description. In many places it is not desired.
$sub_element['#description'] = ' '. t('E.g., @date', array('@date' => date_format_date(date_example_date(), 'custom', date_popup_date_format($element))));
// TODO, figure out exactly when we want this description.
// In many places it is not desired.
$sub_element['#description'] = ' ' . t('E.g., @date', array(
'@date' => date_format_date(
date_example_date(),
'custom',
date_popup_date_format($element)
),
));
return $sub_element;
}
@@ -377,7 +434,17 @@ function date_popup_process_date_part(&$element) {
function date_popup_process_time_part(&$element) {
$granularity = date_format_order($element['#date_format']);
$has_time = date_has_time($granularity);
if (empty($has_time)) return array();
if (empty($has_time)) {
return array();
}
// When used as a Views exposed filter widget, $element['#value'] contains an array instead an string.
// Fill the 'time' string in this case.
$mock = NULL;
$callback_values = date_popup_element_value_callback($element, FALSE, $mock);
if (!isset($element['#value']['time']) && isset($callback_values['time'])) {
$element['#value']['time'] = $callback_values['time'];
}
switch ($element['#timepicker']) {
case 'default':
@@ -385,10 +452,14 @@ function date_popup_process_time_part(&$element) {
$settings = array(
'show24Hours' => strpos($element['#date_format'], 'H') !== FALSE ? TRUE : FALSE,
'showSeconds' => (in_array('second', $granularity) ? TRUE : FALSE),
'timeSteps' => array(1, intval($element['#date_increment']), (in_array('second', $granularity) ? $element['#date_increment'] : 0)),
'timeSteps' => array(
1,
intval($element['#date_increment']),
(in_array('second', $granularity) ? $element['#date_increment'] : 0),
),
'spinnerImage' => '',
'fromTo' => isset($fromto),
);
);
if (strpos($element['#date_format'], 'a') !== FALSE) {
// Then we are using lowercase am/pm.
$settings['ampmNames'] = array('am', 'pm');
@@ -397,9 +468,11 @@ function date_popup_process_time_part(&$element) {
$settings['ampmPrefix'] = ' ';
}
break;
case 'wvega':
$func = 'timepicker';
$time_granularity = array_intersect($granularity, array('hour', 'minute', 'second'));
$grans = array('hour', 'minute', 'second');
$time_granularity = array_intersect($granularity, $grans);
$format = date_popup_format_to_popup_time(date_limit_format($element['#date_format'], $time_granularity), 'wvega');
// The first value in the dropdown list should be the same as the element
// default_value, but it needs to be in JS format (i.e. milliseconds since
@@ -414,6 +487,7 @@ function date_popup_process_time_part(&$element) {
'scrollbar' => TRUE,
);
break;
default:
$func = '';
$settings = array();
@@ -423,8 +497,8 @@ function date_popup_process_time_part(&$element) {
// Create a unique id for each set of custom settings.
$id = date_popup_js_settings_id($element['#id'], $func, $settings);
// Manually build this element and set the value - this will prevent corrupting
// the parent value
// Manually build this element and set the value -
// this will prevent corrupting the parent value.
$parents = array_merge($element['#parents'], array('time'));
$sub_element = array(
'#type' => 'textfield',
@@ -436,16 +510,22 @@ function date_popup_process_time_part(&$element) {
'#maxlength' => 10,
'#attributes' => $element['#attributes'],
'#parents' => $parents,
'#name' => array_shift($parents) . '['. implode('][', $parents) .']',
'#name' => array_shift($parents) . '[' . implode('][', $parents) . ']',
'#ajax' => !empty($element['#ajax']) ? $element['#ajax'] : FALSE,
);
$sub_element['#value'] = $sub_element['#default_value'];
// TODO, figure out exactly when we want this description. In many places it is not desired.
// TODO, figure out exactly when we want this description.
// In many places it is not desired.
$example_date = date_now();
date_increment_round($example_date, $element['#date_increment']);
$sub_element['#description'] = t('E.g., @date', array('@date' => date_format_date($example_date, 'custom', date_popup_time_format($element))));
$sub_element['#description'] = t('E.g., @date', array(
'@date' => date_format_date(
$example_date,
'custom',
date_popup_time_format($element)
)));
return ($sub_element);
}
@@ -456,7 +536,6 @@ function date_popup_process_time_part(&$element) {
* When used as a Views widget, the validation step always gets triggered,
* even with no form submission. Before form submission $element['#value']
* contains a string, after submission it contains an array.
*
*/
function date_popup_validate($element, &$form_state) {
@@ -473,6 +552,11 @@ function date_popup_validate($element, &$form_state) {
$input_exists = NULL;
$input = drupal_array_get_nested_value($form_state['values'], $element['#parents'], $input_exists);
// If the date is a string, it is not considered valid and can cause problems
// later on, so just exit out now.
if (is_string($input)) {
return;
}
drupal_alter('date_popup_pre_validate', $element, $form_state, $input);
@@ -481,9 +565,15 @@ function date_popup_validate($element, &$form_state) {
$time_granularity = date_popup_time_granularity($element);
$has_time = date_has_time($granularity);
$label = !empty($element['#date_title']) ? $element['#date_title'] : (!empty($element['#title']) ? $element['#title'] : '');
$label = t($label);
// @codingStandardsIgnoreStart
$label = '';
if (!empty($element['#date_title'])) {
$label = t($element['#date_title']);
}
elseif (!empty($element['#title'])) {
$label = t($element['#title']);
}
// @codingStandardsIgnoreEnd
$date = date_popup_input_date($element, $input);
// If the date has errors, display them.
@@ -517,7 +607,7 @@ function date_popup_validate($element, &$form_state) {
/**
* Helper function for extracting a date value out of user input.
*
* @param autocomplete
* @param bool $auto_complete
* Should we add a time value to complete the date if there is no time?
* Useful anytime the time value is optional.
*/
@@ -532,8 +622,8 @@ function date_popup_input_date($element, $input, $auto_complete = FALSE) {
$format = date_popup_date_format($element);
$format .= $has_time ? ' ' . date_popup_time_format($element) : '';
$datetime = $input['date'];
$datetime .= $has_time ? ' ' . $input['time'] : '';
$datetime = trim($input['date']);
$datetime .= $has_time ? ' ' . trim($input['time']) : '';
$date = new DateObject($datetime, $element['#date_timezone'], $format);
if (is_object($date)) {
$date->limitGranularity($granularity);
@@ -552,7 +642,7 @@ function date_popup_time_formats($with_seconds = FALSE) {
return array(
'H:i:s',
'h:i:sA',
);
);
}
/**
@@ -561,8 +651,17 @@ function date_popup_time_formats($with_seconds = FALSE) {
* TODO Remove any formats not supported by the widget, if any.
*/
function date_popup_formats() {
$formats = str_replace('i', 'i:s', array_keys(system_get_date_formats('short')));
// Load short date formats.
$formats = system_get_date_formats('short');
// Load custom date formats.
if ($formats_custom = system_get_date_formats('custom')) {
$formats = array_merge($formats, $formats_custom);
}
$formats = str_replace('i', 'i:s', array_keys($formats));
$formats = drupal_map_assoc($formats);
return $formats;
}
@@ -570,7 +669,8 @@ function date_popup_formats() {
* Recreate a date format string so it has the values popup expects.
*
* @param string $format
* a normal date format string, like Y-m-d
* A normal date format string, like Y-m-d
*
* @return string
* A format string in popup format, like YMD-, for the
* earlier 'calendar' version, or m/d/Y for the later 'datepicker'
@@ -588,15 +688,34 @@ function date_popup_format_to_popup($format) {
* Recreate a time format string so it has the values popup expects.
*
* @param string $format
* a normal time format string, like h:i (a)
* A normal time format string, like h:i (a)
*
* @return string
* a format string that the popup can accept like h:i a
* A format string that the popup can accept like h:i a
*/
function date_popup_format_to_popup_time($format, $timepicker = NULL) {
if (empty($format)) {
$format = 'H:i';
}
$format = str_replace(array('/', '-', ' .', ',', 'F', 'M', 'l', 'z', 'w', 'W', 'd', 'j', 'm', 'n', 'y', 'Y'), '', $format);
$symbols = array(
'/',
'-',
' .',
',',
'F',
'M',
'l',
'z',
'w',
'W',
'd',
'j',
'm',
'n',
'y',
'Y',
);
$format = str_replace($symbols, '', $format);
$format = strtr($format, date_popup_timepicker_format_replacements($timepicker));
return $format;
}
@@ -605,9 +724,10 @@ function date_popup_format_to_popup_time($format, $timepicker = NULL) {
* Reconstruct popup format string into normal format string.
*
* @param string $format
* a string in popup format, like YMD-
* A string in popup format, like YMD-
*
* @return string
* a normal date format string, like Y-m-d
* A normal date format string, like Y-m-d
*/
function date_popup_popup_to_format($format) {
$replace = array_flip(date_popup_datepicker_format_replacements());
@@ -621,22 +741,21 @@ function date_popup_popup_to_format($format) {
* This function returns a map of format replacements required to change any
* input format into one that the given timepicker can support.
*
* @param $timepicker
* @param string $timepicker
* The time entry plugin being used: either 'wvega' or 'default'.
* @return
*
* @return array
* A map of replacements.
*/
function date_popup_timepicker_format_replacements($timepicker = 'default') {
switch ($timepicker) {
case 'wvega':
return array(
'a' => 'A', // The wvega timepicker only supports uppercase AM/PM.
);
// The wvega timepicker only supports uppercase AM/PM.
return array('a' => 'A');
default:
return array(
'G' => 'H', // The default timeEntry plugin requires leading zeros.
'g' => 'h',
);
// The default timeEntry plugin requires leading zeros.
return array('G' => 'H', 'g' => 'h');
}
}
@@ -645,16 +764,16 @@ function date_popup_timepicker_format_replacements($timepicker = 'default') {
*/
function date_popup_datepicker_format_replacements() {
return array(
'd' => 'dd',
'j' => 'd',
'l' => 'DD',
'D' => 'D',
'm' => 'mm',
'n' => 'm',
'F' => 'MM',
'M' => 'M',
'Y' => 'yy',
'y' => 'y',
'd' => 'dd',
'j' => 'd',
'l' => 'DD',
'D' => 'D',
'm' => 'mm',
'n' => 'm',
'F' => 'MM',
'M' => 'M',
'Y' => 'yy',
'y' => 'y',
);
}
@@ -667,16 +786,18 @@ function theme_date_popup($vars) {
$element = $vars['element'];
$attributes = !empty($element['#wrapper_attributes']) ? $element['#wrapper_attributes'] : array('class' => array());
$attributes['class'][] = 'container-inline-date';
// If there is no description, the floating date elements need some extra padding below them.
// If there is no description, the floating date
// elements need some extra padding below them.
$wrapper_attributes = array('class' => array('date-padding'));
if (empty($element['date']['#description'])) {
$wrapper_attributes['class'][] = 'clearfix';
}
// Add an wrapper to mimic the way a single value field works, for ease in using #states.
// Add an wrapper to mimic the way a single value field works,
// for ease in using #states.
if (isset($element['#children'])) {
$element['#children'] = '<div id="' . $element['#id'] . '" ' . drupal_attributes($wrapper_attributes) .'>' . $element['#children'] . '</div>';
$element['#children'] = '<div id="' . $element['#id'] . '" ' . drupal_attributes($wrapper_attributes) . '>' . $element['#children'] . '</div>';
}
return '<div ' . drupal_attributes($attributes) .'>' . theme('form_element', $element) . '</div>';
return '<div ' . drupal_attributes($attributes) . '>' . theme('form_element', $element) . '</div>';
}
/**
@@ -707,8 +828,8 @@ function date_popup_settings() {
'#type' => 'select',
'#options' => array(
'default' => t('Use default jQuery timepicker'),
'wvega' => t('Use dropdown timepicker'),
'none' => t('Manual time entry, no jQuery timepicker')
'wvega' => t('Use dropdown timepicker'),
'none' => t('Manual time entry, no jQuery timepicker'),
),
'#title' => t('Timepicker'),
'#default_value' => variable_get('date_popup_timepicker', $preferred_timepicker),
@@ -734,7 +855,7 @@ function date_popup_settings() {
}
EOM;
$form['#suffix'] = t('<p>The Date Popup calendar includes some css for IE6 that breaks css validation. Since IE 6 is now superceded by IE 7, 8, and 9, the special css for IE 6 has been removed from the regular css used by the Date Popup. If you find you need that css after all, you can add it back in your theme. Look at the way the Garland theme adds special IE-only css in in its page.tpl.php file. The css you need is:</p>') .'<blockquote><PRE>' . $css .'</PRE></blockquote>';
$form['#suffix'] = t('<p>The Date Popup calendar includes some css for IE6 that breaks css validation. Since IE 6 is now superceded by IE 7, 8, and 9, the special css for IE 6 has been removed from the regular css used by the Date Popup. If you find you need that css after all, you can add it back in your theme. Look at the way the Garland theme adds special IE-only css in in its page.tpl.php file. The css you need is:</p>') . '<blockquote><PRE>' . $css . '</PRE></blockquote>';
return system_settings_form($form);
}
File diff suppressed because one or more lines are too long
@@ -2,5 +2,6 @@
/**
* @file
* Empty file to avoid fatal error if it doesn't exist.
*
* Formerly the Date Repeat field code.
*/
*/
@@ -7,9 +7,9 @@ php = 5.2
files[] = tests/date_repeat.test
files[] = tests/date_repeat_form.test
; Information added by Drupal.org packaging script on 2014-07-29
version = "7.x-2.8"
; Information added by Drupal.org packaging script on 2015-09-08
version = "7.x-2.9"
core = "7.x"
project = "date"
datestamp = "1406653438"
datestamp = "1441727353"

Some files were not shown because too many files have changed in this diff Show More