Code for Recovery is a nonprofit organization of volunteer members building technology services for recovery fellowships, such as A.A. and Al-Anon.', '12-step-meeting-list'), TSML_ALLOWED_HTML) ?>
'; foreach ($meetings as $m) { $output .= '
' . wp_kses($message, TSML_ALLOWED_HTML) . '
';
print_r($obj);
echo '';
exit;
}
/**
* efficiently remove an array of post_ids
* used: tsml_delete_orphans(), admin-import.php
*
* @param mixed $post_ids
* @return void
*/
function tsml_delete($post_ids)
{
global $wpdb;
//special case
if ($post_ids == 'everything') {
$post_ids = get_posts([
'post_type' => ['tsml_meeting', 'tsml_location', 'tsml_group'],
'post_status' => 'any',
'fields' => 'ids',
'numberposts' => -1,
]);
//when we're deleting *everything*, also delete regions & districts
if ($term_ids = implode(',', $wpdb->get_col('SELECT term_id FROM ' . $wpdb->term_taxonomy . ' WHERE taxonomy IN ("tsml_district", "tsml_region")'))) {
$wpdb->query('DELETE FROM ' . $wpdb->terms . ' WHERE term_id IN (' . $term_ids . ')');
$wpdb->query('DELETE FROM ' . $wpdb->term_taxonomy . ' WHERE term_id IN (' . $term_ids . ')');
}
}
if (empty($post_ids) || !is_array($post_ids)) {
return;
}
// sanitize
$post_ids = array_map('intval', $post_ids);
$post_ids = array_unique($post_ids);
$post_ids = implode(', ', $post_ids);
// run deletes
$wpdb->query('DELETE FROM ' . $wpdb->posts . ' WHERE ID IN (' . $post_ids . ')');
$wpdb->query('DELETE FROM ' . $wpdb->postmeta . ' WHERE post_id IN (' . $post_ids . ')');
$wpdb->query('DELETE FROM ' . $wpdb->term_relationships . ' WHERE object_id IN (' . $post_ids . ')');
// rebuild cache
tsml_cache_rebuild();
}
/**
* efficiently deletes all orphaned locations and groups (have no meetings associated)
* used: save_post filter
*
* @return void
*/
function tsml_delete_orphans()
{
global $wpdb;
$location_ids = $wpdb->get_col('SELECT l.ID FROM ' . $wpdb->posts . ' l WHERE l.post_type = "tsml_location" AND (SELECT COUNT(*) FROM ' . $wpdb->posts . ' m WHERE m.post_type="tsml_meeting" AND m.post_parent = l.id) = 0');
$group_ids = $wpdb->get_col('SELECT g.ID FROM ' . $wpdb->posts . ' g WHERE g.post_type = "tsml_group" AND (SELECT COUNT(*) FROM ' . $wpdb->postmeta . ' m WHERE m.meta_key="group_id" AND m.meta_value = g.id) = 0');
tsml_delete(array_merge($location_ids, $group_ids));
// edge case: draft-ify locations with only unpublished meetings
$location_ids = $wpdb->get_col('SELECT l.ID FROM ' . $wpdb->posts . ' l
WHERE l.post_type = "tsml_location" AND
(SELECT COUNT(*) FROM ' . $wpdb->posts . ' m
WHERE m.post_type="tsml_meeting" AND m.post_status="publish" AND m.post_parent = l.id) = 0');
if (count($location_ids)) {
$wpdb->query('UPDATE ' . $wpdb->posts . ' l SET l.post_status = "draft" WHERE ID IN (' . implode(', ', $location_ids) . ')');
}
}
/**
* send a nice-looking email
* used by tsml_ajax_feedback() and save.php (change notifications)
*
* @param mixed $to
* @param mixed $subject
* @param mixed $message
* @param mixed $reply_to
* @return bool
*/
function tsml_email($to, $subject, $message, $reply_to = false)
{
$headers = ['Content-Type: text/html; charset=UTF-8'];
if ($reply_to) {
$headers[] = 'Reply-To: ' . $reply_to;
}
// prepend subject as h1
$message = '', '
', $message);
$message = str_replace('
|
' . $address . '. Response was ' . $error . '',
];
}
// decode result
$data = json_decode($result);
// if over query limit, wait two seconds and retry, or then exit
if ($data->status === 'OVER_QUERY_LIMIT') {
sleep(2);
$result = curl_exec($tsml_curl_handle);
// could not connect error
if ($result === false) {
return [
'status' => 'error',
'reason' => 'Google could not validate the address ' . $address . '. Response was ' . curl_error($tsml_curl_handle) . '',
];
}
// decode result
$data = json_decode($result);
// if we're still over the limit, stop
if ($data->status === 'OVER_QUERY_LIMIT') {
tsml_log('geocode_error', 'OVER_QUERY_LIMIT', $address);
return [
'status' => 'error',
'reason' => 'We are over the rate limit for the Google Geocoding API.'
];
}
}
// if there are no results report it
if ($data->status === 'ZERO_RESULTS') {
tsml_log('geocode_error', 'ZERO_RESULTS', $address);
return [
'status' => 'error',
'reason' => 'Google could not validate the address ' . $address . '',
];
}
// if result is otherwise bad, stop
if (($data->status !== 'OK') || empty($data->results[0]->formatted_address)) {
tsml_log('geocode_error', $data->status, $address);
return [
'status' => 'error',
'reason' => 'Google gave an unexpected response for address ' . $address . '. Response was ' . var_export($data, true) . '', ]; } // check our overrides array again in case google is wrong if (array_key_exists($data->results[0]->formatted_address, $tsml_google_overrides)) { $response = $tsml_google_overrides[$data->results[0]->formatted_address]; if (empty($response['approximate'])) { $response['approximate'] = 'no'; } } else { tsml_log('geocode_success', $data->results[0]->formatted_address, $address); // start building response $response = [ 'formatted_address' => $data->results[0]->formatted_address, 'latitude' => $data->results[0]->geometry->location->lat, 'longitude' => $data->results[0]->geometry->location->lng, 'approximate' => ($data->results[0]->geometry->location_type === 'APPROXIMATE') ? 'yes' : 'no', 'city' => null, 'status' => 'geocode', ]; // get city, we might need it for the region, and we are going to cache it foreach ($data->results[0]->address_components as $component) { if (in_array('locality', $component->types)) { $response['city'] = $component->short_name; } } } return $response; } /** * return spelled-out meeting types * called from save.php (updates) and archive-meetings.php (display) * * @param mixed $types * @return string | void */ function tsml_meeting_types($types) { global $tsml_programs, $tsml_program; if (empty($tsml_programs[$tsml_program]['types'])) { return; } $return = []; foreach ($types as $type) { if (array_key_exists($type, $tsml_programs[$tsml_program]['types'])) { $return[] = $tsml_programs[$tsml_program]['types'][$type]; } } sort($return); return implode(', ', $return); } /** * return an array of languages, with legacy code substitutions per-program * used: variables.php, meeting-edit.php */ function tsml_languages($types = []) { global $tsml_program; // https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes $languages = [ 'AF' => __('Afrikaans', '12-step-meeting-list'), 'AM' => __('Amharic', '12-step-meeting-list'), 'AR' => __('Arabic', '12-step-meeting-list'), 'BG' => __('Bulgarian', '12-step-meeting-list'), 'DA' => __('Danish', '12-step-meeting-list'), 'DE' => __('German', '12-step-meeting-list'), 'EL' => __('Greek', '12-step-meeting-list'), 'EN' => __('English', '12-step-meeting-list'), 'ES' => __('Spanish', '12-step-meeting-list'), 'FA' => __('Persian', '12-step-meeting-list'), 'FI' => __('Finnish', '12-step-meeting-list'), 'FR' => __('French', '12-step-meeting-list'), 'HE' => __('Hebrew', '12-step-meeting-list'), 'HI' => __('Hindi', '12-step-meeting-list'), 'HR' => __('Croatian', '12-step-meeting-list'), 'HU' => __('Hungarian', '12-step-meeting-list'), 'IS' => __('Icelandic', '12-step-meeting-list'), 'IT' => __('Italian', '12-step-meeting-list'), 'JA' => __('Japanese', '12-step-meeting-list'), 'KA' => __('Georgian', '12-step-meeting-list'), 'KO' => __('Korean', '12-step-meeting-list'), 'LT' => __('Lithuanian', '12-step-meeting-list'), 'ML' => __('Malayalam', '12-step-meeting-list'), 'MT' => __('Maltese', '12-step-meeting-list'), 'NE' => __('Nepali', '12-step-meeting-list'), 'NL' => __('Dutch', '12-step-meeting-list'), 'NO' => __('Norwegian', '12-step-meeting-list'), 'PA' => __('Punjabi', '12-step-meeting-list'), 'PL' => __('Polish', '12-step-meeting-list'), 'PT' => __('Portuguese', '12-step-meeting-list'), 'RU' => __('Russian', '12-step-meeting-list'), 'SK' => __('Slovak', '12-step-meeting-list'), 'SL' => __('Slovenian', '12-step-meeting-list'), 'SV' => __('Swedish', '12-step-meeting-list'), 'TH' => __('Thai', '12-step-meeting-list'), 'TL' => __('Tagalog', '12-step-meeting-list'), 'TR' => __('Turkish', '12-step-meeting-list'), 'UK' => __('Ukrainian', '12-step-meeting-list'), ]; // substitutions $substitutions = [ 'aca' => [ 'ES' => 'SP', ], 'al-anon' => [ 'ES' => 'S', ], 'aa' => [ 'ES' => 'S', 'IT' => 'ITA', 'KO' => 'KOR', 'PA' => 'PUN', 'PL' => 'POL', 'PT' => 'POR', 'RU' => 'RUS', 'TR' => 'TUR', ], 'ca' => [ 'ES' => 'S', 'IT' => 'ITA', 'KO' => 'KOR', 'PA' => 'PUN', 'PL' => 'POL', 'PT' => 'POR', 'RU' => 'RUS', ], 'cma' => [ 'ES' => 'S', ], 'coda' => [ 'ES' => 'S', ], 'eda' => [ 'ES' => 'S', 'IT' => 'ITA', ], 'ga' => [ 'ES' => 'S', 'IT' => 'ITA', 'KO' => 'KOR', 'PA' => 'PUN', 'PL' => 'POL', 'PT' => 'POR', 'RU' => 'RUS', ], 'slaa' => [ 'ES' => 'S', ], 'sia' => [ 'ES' => 'S', 'IT' => 'ITA', 'KO' => 'KOR', 'PA' => 'PUN', 'PL' => 'POL', 'PT' => 'POR', 'RU' => 'RUS', 'UK' => 'UA', ], ]; // if the program has no types, return the languages if (array_key_exists($tsml_program, $substitutions)) { foreach ($substitutions[$tsml_program] as $key => $value) { if (array_key_exists($key, $languages)) { $languages[$value] = $languages[$key]; unset($languages[$key]); } } } foreach ($languages as $key => $value) { $types[$key] = $value; } asort($types); return $types; } /** * Render an anchor tag with a class * @deprecated this function is no longer used. it will be removed in the future * @param mixed $url * @param mixed $string * @param mixed $exclude * @param mixed $class * @return string */ function tsml_link($url, $string, $exclude = '', $class = false) { $appends = $_GET; if (array_key_exists($exclude, $appends)) { unset($appends[$exclude]); } if (!empty($appends)) { $url .= strstr($url, '?') ? '&' : '?'; $url .= http_build_query($appends, '', '&'); } $return = ''; return $return; } /** * return string link with current query string appended * * @param string $url * @param mixed $exclude * @return string */ function tsml_link_url($url, $exclude = '') { $appends = $_GET; if (array_key_exists($exclude, $appends)) { unset($appends[$exclude]); } if (!empty($appends)) { $url .= strstr($url, '?') ? '&' : '?'; $url .= http_build_query($appends, '', '&'); } return $url; } /** * link to meetings page with parameters * used: admin_import.php, admin_settings.php, archive-meetings.php, init.php, widgets.php, tsml_geocode_google() * * @param mixed $parameters * @return string */ function tsml_meetings_url($parameters = []) { $url = get_post_type_archive_link('tsml_meeting'); if (empty($url)) { $url = get_home_url(); } $url = add_query_arg($parameters, $url); return $url; } /** * convert line breaks in plain text to HTML paragraphs * used: save.php in lieu of nl2br() * * @param mixed $string * @return string */ function tsml_paragraphs($string) { $paragraphs = ''; foreach (explode("\n", trim($string)) as $line) { if ($line = trim($line)) { $paragraphs .= '
' . $line . '
'; } } return $paragraphs; } /** * boolean whether current program has types * used: meeting edit screen, meeting save * * @return bool */ function tsml_program_has_types() { global $tsml_programs, $tsml_program; return !empty($tsml_programs[$tsml_program]['types']); } /** * exit if user does not have permission to edit meetings * * @return void */ function tsml_require_meetings_permission() { if (!current_user_can(TSML_MEETINGS_PERMISSION)) { // translators: %s is the permission required wp_die(wp_kses(sprintf(__('You do not have sufficient permissions to access this page (%s).', '12-step-meeting-list'), TSML_MEETINGS_PERMISSION), TSML_ALLOWED_HTML));
}
}
/**
* exit if user does not have permission to edit settings
*
* @return void
*/
function tsml_require_settings_permission()
{
if (!current_user_can(TSML_SETTINGS_PERMISSION)) {
// translators: %s is the permission required
wp_die(wp_kses(sprintf(__('You do not have sufficient permissions to access this page (%s).', '12-step-meeting-list'), TSML_SETTINGS_PERMISSION), TSML_ALLOWED_HTML));
}
}
/**
* flag whether a location's map pin was placed manually
* used: save.php
*
* @param int $location_id
* @param bool $use_custom_coordinates
* @return void
*/
function tsml_update_use_custom_coordinates($location_id, $use_custom_coordinates)
{
if ($use_custom_coordinates) {
update_post_meta($location_id, 'use_custom_coordinates', 'yes');
} else {
delete_post_meta($location_id, 'use_custom_coordinates');
}
}
/**
* set an option with the currently-used types
* used tsml_import() and save.php
*
* @return void
*/
function tsml_update_types_in_use()
{
global $tsml_types_in_use, $wpdb;
// shortcut to getting all meta values without getting all posts first
$types = $wpdb->get_col('SELECT
m.meta_value
FROM ' . $wpdb->postmeta . ' m
JOIN ' . $wpdb->posts . ' p ON m.post_id = p.id
WHERE p.post_type = "tsml_meeting" AND m.meta_key = "types" AND p.post_status = "publish"');
// main array
$all_types = [];
// loop through results and append to main array
foreach ($types as $type) {
$type = unserialize($type);
if (is_array($type)) {
$all_types = array_merge($all_types, $type);
}
}
// update global variable
$tsml_types_in_use = array_unique($all_types);
// set option value
update_option('tsml_types_in_use', $tsml_types_in_use);
}
/**
* sanitize a value
* used: save.php
*
* @param mixed $type
* @param mixed $value
* @return array|string|null
*/
function tsml_sanitize($type, $value)
{
if ($type == 'url') {
return esc_url_raw($value, ['http', 'https']);
} elseif ($type == 'date') {
return date('Y-m-d', strtotime($value));
} elseif ($type == 'time') {
return date('H:i', strtotime($value));
} elseif ($type == 'phone') {
return preg_replace('/[^0-9,+#]/', '', $value);
}
return sanitize_text_field($value);
}
/**
* sanitize multi-line text
* used tsml_import() and save.php
* @param string $value
* @return string
*/
function tsml_sanitize_text_area($value)
{
return implode("\n", array_map('sanitize_text_field', explode("\n", trim($value))));
}
/**
* does a string end with another string
* used: save.php
*
* @param mixed $string
* @param mixed $end
* @return bool
*/
function tsml_string_ends($string, $end)
{
$length = strlen($end);
if (!$length) {
return true;
}
return (substr($string, -$length) === $end);
}
/**
* tokenize string for the typeaheads
* used: ajax functions
* @param mixed $string
* @return array
*/
function tsml_string_tokens($string)
{
// shorten words that have quotes in them instead of splitting them
$string = html_entity_decode($string);
$string = str_replace("'", '', $string);
$string = str_replace('’', '', $string);
// remove everything that's not a letter or a number
$string = preg_replace("/[^a-zA-Z 0-9]+/", ' ', $string);
// return array
return array_values(array_unique(array_filter(explode(' ', $string))));
}
/**
* Implodes given array $types into lower-cased class names, prefixing each with $prefix
*
* @param string[] $types
* @param string $prefix
* @return string
*/
function tsml_to_css_classes($types, $prefix = 'type-')
{
if (!$types) {
return '';
}
$types = array_map('strtolower', $types);
return $prefix . implode(' ' . $prefix, $types);
}
/**
* Sanitizes a string for sorting purposes. Similar to sanitize_title(), but uses Unicode regular expressions to support multiple languages.
*
* @param string $string
* @return string
*/
function tsml_sanitize_data_sort($string)
{
global $tsml_sanitize_data_sort_regexps;
// Populate regex array only once
if (!isset($tsml_sanitize_data_sort_regexps)) {
$tsml_sanitize_data_sort_regexps = [
['/<[^>]+>/', ''], // Strip HTML Tags
['/[&\'"<>]+/', ''], // Strip unsupported chars
['/[\\/\\.\\p{Zs}\\p{Pd}]/u', '-'], // Change forward slashes, periods, spaces and dashes to dash (Unicode)
['/[^\\p{L}\\p{N}\\p{M}\-]+/u', ''], // Remove any Unicode char that is not an alpha-numeric, mark character or dash
['/\-+/', '-'], // Convert runs of dashes into a single dash
['/^\-|\-$/', ''] // Strip trailing/leading dash
];
}
// Convert all html entities to chars so encodings are uniform
$t = html_entity_decode($string);
// Do regex-based sanitization
foreach ($tsml_sanitize_data_sort_regexps as $a) {
$t = preg_replace($a[0], $a[1], $t);
}
// Unicode-aware lowercase of characters in string
if (function_exists('mb_strtolower')) {
return mb_strtolower($t);
} else {
return strtolower($t);
}
}
/**
* incorporates wp timezone into php's date() function
* used: admin_import.php, admin_log.php
*
* @param mixed $format
* @param mixed $timestamp
* @return string
*/
function tsml_date_localised($format, $timestamp = null)
{
// This function behaves a bit like PHP's Date() function, but taking into account the Wordpress site's timezone
// CAUTION: It will throw an exception when it receives invalid input - please catch it accordingly
// From https://mediarealm.com.au/
$tz_string = get_option('timezone_string');
$tz_offset = get_option('gmt_offset', 0);
if (!empty($tz_string)) {
// If site timezone option string exists, use it
$timezone = $tz_string;
} elseif ($tz_offset == 0) {
// get UTC offset, if it isn’t set then return UTC
$timezone = 'UTC';
} else {
$timezone = $tz_offset;
if (substr($tz_offset, 0, 1) != "-" && substr($tz_offset, 0, 1) != "+" && substr($tz_offset, 0, 1) != "U") {
$timezone = "+" . $tz_offset;
}
}
if ($timestamp === null) {
$timestamp = time();
}
$datetime = new DateTime();
$datetime->setTimestamp($timestamp);
$datetime->setTimezone(new DateTimeZone($timezone));
return $datetime->format($format);
}
/**
* Compares content of an import meeting against local meeting
* @param array $meeting_old Old version of meeting (local version)
* @param array $meeting_new New version of meeting (imported version)
* @param boolean $compare_import [default false] Imported meetings use source fields for comparison
* @param boolean $translate_fields [default false] Translate system fields to field labels
* @return array|null
*/
function tsml_compare_meetings($meeting_old, $meeting_new, $compare_import = false, $translate_fields = false)
{
global $tsml_export_columns, $tsml_source_fields_map, $tsml_entity_fields, $tsml_array_fields;
$meeting_old = (array) $meeting_old;
$meeting_new = (array) $meeting_new;
// update local meeting with stored source field values
if ($compare_import) {
foreach ($tsml_source_fields_map as $source_field => $field) {
if (isset($meeting_old[$source_field])) {
$meeting_old[$field] = $meeting_old[$source_field];
} else {
unset($meeting_old[$field]);
}
}
}
$compare_fields = array_merge(array_keys($tsml_export_columns), $tsml_entity_fields);
$compare_fields = array_diff(
$compare_fields,
// these fields are internal fields, not content fields for comparison
explode(',', 'id,slug,author,data_source,data_source_name,updated,latitude,longitude')
);
// normalize meetings for comparison
$normalized_meetings = array();
foreach (array($meeting_old, $meeting_new) as $index => $meeting) {
$normalized_meetings[$index] = array();
foreach ($compare_fields as $field) {
$value = isset($meeting[$field]) ? $meeting[$field] : '';
if (in_array($field, $tsml_array_fields, true)) {
$value = empty($value) ? [] : ((array) $value);
}
// import meeting: post_title <=> name
if (!$value && 'name' === $field) {
$value = isset($meeting['post_title']) ? $meeting['post_title'] : '';
}
if (is_object($value) || is_array($value)) {
$value = json_encode($value);
} elseif (null !== $value) {
$value = trim(htmlspecialchars_decode(html_entity_decode(strval($value)), ENT_QUOTES));
} else {
$value = '';
}
$normalized_meetings[$index][$field] = $value;
}
}
// if 'group' is blank on both, we don't compare group_notes or district
if (!$normalized_meetings[0]['group'] && !$normalized_meetings[1]['group']) {
$compare_fields = array_diff($compare_fields, ['district', 'group_notes']);
}
$diff_fields = array();
foreach ($compare_fields as $field) {
if ($normalized_meetings[0][$field] !== $normalized_meetings[1][$field]) {
$diff_fields[] = ($translate_fields && isset($tsml_export_columns[$field])) ? $tsml_export_columns[$field] : $field;
}
}
return count($diff_fields) ? $diff_fields : null;
}
/**
* Return hash for imported meeting, for later comparison
*
* @param [array] $meeting
* @return string
*/
function tsml_get_import_hash($meeting)
{
$remove_fields = explode(',', ',row,import_hash');
if (is_array($meeting)) {
foreach ($meeting as $field => $value) {
if (in_array(strtolower($field), $remove_fields)) {
unset($meeting[$field]);
}
}
}
return md5(serialize($meeting));
}
function tsml_header()
{
if (function_exists('wp_is_block_theme') && wp_is_block_theme()) {
include(TSML_PATH . '/templates/header.php');
} else {
get_header();
}
}
function tsml_footer()
{
if (function_exists('wp_is_block_theme') && wp_is_block_theme()) {
include(TSML_PATH . '/templates/footer.php');
} else {
get_footer();
}
}
/**
* Redirect legacy query parameters to TSML UI's url structure
*/
function tsml_redirect_legacy_query_params()
{
global $tsml_program, $tsml_programs;
$replacements = [];
if (isset($_GET['tsml-attendance_option'])) {
if ($_GET['tsml-attendance_option'] === 'active') {
$replacements['type'][] = 'active';
} elseif ($_GET['tsml-attendance_option'] === 'in_person') {
$replacements['type'][] = 'in-person';
} elseif ($_GET['tsml-attendance_option'] === 'online') {
$replacements['type'][] = 'online';
}
}
if (isset($_GET['tsml-day'])) {
$days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
if (array_key_exists($_GET['tsml-day'], $days)) {
$replacements['weekday'] = $days[$_GET['tsml-day']];
}
}
if (isset($_GET['tsml-mode'])) {
$replacements['mode'] = $_GET['tsml-mode'];
if (isset($_GET['tsml-distance'])) {
$replacements['distance'] = $_GET['tsml-distance'];
} else {
$replacements['distance'] = 10;
}
}
if (isset($_GET['tsml-query'])) {
$replacements['search'] = $_GET['tsml-query'];
}
if (isset($_GET['tsml-region'])) {
$replacements['region'] = $_GET['tsml-region'];
}
if (isset($_GET['tsml-time'])) {
$replacements['time'] = $_GET['tsml-time'];
}
if (isset($_GET['tsml-type'])) {
$types = explode(',', $_GET['tsml-type']);
foreach ($types as $type) {
if (array_key_exists($type, $tsml_programs[$tsml_program]['types'])) {
$replacements['type'][] = sanitize_title($tsml_programs[$tsml_program]['types'][$type]);
}
}
}
if (isset($replacements['type'])) {
$replacements['type'] = implode('/', $replacements['type']);
}
if (count($replacements) > 0) {
wp_redirect(tsml_meetings_url($replacements));
}
}