trinion_base-1.0.x-dev/trinion_base.module
trinion_base.module
<?php
/**
* Implements hook_theme().
*/
function trinion_base_theme($existing, $type, $theme, $path) {
return [
'trinion_widget_pie' => [
'variables' => [
'data' => NULL,
'title' => NULL,
'id' => NULL,
],
'template' => 'widget_pie',
'path' => $path . '/templates',
],
'trinion_widget_pie_my_all' => [
'variables' => [
'my' => NULL,
'data' => NULL,
'title' => NULL,
'id' => NULL,
],
'template' => 'widget_pie_my_all',
'path' => $path . '/templates',
],
'trinion_widget_bar' => [
'variables' => [
'data' => NULL,
'status' => NULL,
'id' => NULL,
],
'template' => 'widget_bar',
'path' => $path . '/templates',
],
'trinion_accordion' => [
'variables' => [
'data' => NULL,
],
'template' => 'trinion_accordion',
'path' => $path . '/templates',
],
'trinion_notices' => [
'variables' => [
'data' => NULL,
'has_new' => NULL,
'show_new' => NULL,
],
'template' => 'trinion_notices',
'path' => $path . '/templates',
],
'trinion_notices_list_dropdown' => [
'variables' => [
'data' => NULL,
],
'template' => 'trinion_notices_list_dropdown',
'path' => $path . '/templates',
],
];
}
/**
* Implements hook_form_alter().
*/
function trinion_base_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$route_match = Drupal::routeMatch();
$route_name = $route_match->getRouteName();
if ($form_id == 'bulk_edit_form') {
$form['node']['zadacha']['revision_information']['#access'] = FALSE;
$form['node']['zadacha']['#type'] = 'container';
}
if ($form_id == 'user_login_form') {
$form['#submit'][] = 'trinion_base_user_login_form_submit';
}
if ($form_id == 'user_form' || $form_id == 'user_register_form') {
$trinion_admin_fields = ['field_tz_proekt', 'field_tz_redaktirovat_zadachi', 'field_tp_tip_ceny', 'field_tb_erp_user', 'field_ts_course_access', 'field_tt_user_phone_inner', 'contact', 'field_ts_uchenik', 'field_ts_completed_lessons', 'field_tz_sotrudnik', 'field_tlc_operator_zanyat', 'field_vyvodit_na_stranice_studen', 'field_blok_razmetki_ob_avtore', 'field_tzc_hourly_rate', 'field_tp_portal_klienta', 'field_tp_portal_postavshchika', 'field_tbi_biznes_process_rol', ];
if (Drupal::currentUser()->hasPermission('administer users')) {
$destination = Drupal::request()->get('destination');
if (!is_null($destination) && strpos($destination, '/admin/trinion_users') === 0) {
foreach ($form as $field => $value) {
if ($field[0] == '#')
continue;
if ($field == 'user_picture')
$form[$field]['#access'] = FALSE;
if (substr($field, 0, 6) == 'field_' && !in_array($field, $trinion_admin_fields))
$form[$field]['#access'] = FALSE;
}
}
}
else {
foreach ($trinion_admin_fields as $field)
$form[$field]['#access'] = FALSE;
}
}
elseif ($form_id == 'trinion_permissions_admin_permissions') {
$rid = \Drupal::request()->get('rid');
if (!empty($rid)) {
$role = \Drupal\user\Entity\Role::load($rid);
$role_permissions = $role->getPermissions();
$form['#submit'][] = 'trinion_base_trinion_permissions_admin_permissions_submit';
$permissions = Drupal::service('user.permissions')->getPermissions();
$form['trinion_permissions'] = [
'#type' => 'table',
'#header' => [t('Access to the Trinion modules'), ''],
'#id' => 'trinion-permissions',
'#sticky' => TRUE,
];
foreach ($permissions as $perm => $data) {
if (strpos($perm, 'trinion_') === 0) {
$form['trinion_permissions'][$perm]['description']['#markup'] = $data['title'];
$form['trinion_permissions'][$perm]['checkbox'] = [
'#type' => 'checkbox',
'#default_value' => in_array($perm, $role_permissions) ? 1 : 0,
];
}
}
}
}
elseif ($form_id == 'node_pdf_print_form_template_form' || $form_id == 'node_pdf_print_form_template_edit_form') {
/** @var \Drupal\Core\Extension\ThemeHandler $module_handler */
$theme_handler = \Drupal::service('theme_handler');
$theme_path = $theme_handler->getTheme('trinion_user_templates')->getPath();
$dir = $theme_path . '/templates';
$templates = scandir($dir);
$form['field_tb_template_name']['widget'][0]['value']['#type'] = 'select';
unset($form['field_tb_template_name']['widget'][0]['value']['#size']);
foreach ($templates as $file) {
if (is_file($dir . '/' . $file))
$form['field_tb_template_name']['widget'][0]['value']['#options'][$file] = $file;
}
}
if (isset($form['field_tb_shablon_pechatnoy_formi'])) {
if ($node = $route_match->getParameter('node'))
$bundle = $node->bundle();
elseif ($type = $route_match->getParameter('node_type'))
$bundle = $type->id();
foreach ($form['field_tb_shablon_pechatnoy_formi']['widget']['#options'] as $key => $value) {
if (is_numeric($key)) {
$hide = TRUE;
if ($tpl = \Drupal\node\Entity\Node::load($key)) {
$hide = $bundle != $tpl->get('field_tb_vid_dokumenta')->getString();
}
if ($hide)
unset($form['field_tb_shablon_pechatnoy_formi']['widget']['#options'][$key]);
}
}
}
}
function trinion_base_user_login_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
$user = Drupal::currentUser();
if (in_array('crm_user', $user->getRoles())) {
if (empty(Drupal::request()->get('destination')))
$form_state->setRedirect('view.zadachi_naznachennye_mne.page_1');
}
}
function trinion_base_trinion_permissions_admin_permissions_submit ($form, \Drupal\Core\Form\FormStateInterface $form_state) {
$perms = [];
foreach ($form_state->getValue('trinion_permissions') as $perm => $val) {
$perms[$perm] = $val['checkbox'];
}
user_role_change_permissions(\Drupal::request()->get('rid'), $perms);
}
/**
* Implements hook_preprocess_HOOK().
*/
function trinion_base_preprocess_inline_entity_form_entity_table(&$variables) {
$variables['table']['0']['actions']['ief_entity_remove']['#value'] = t('Remove');
}
/**
* Implements hook_preprocess_HOOK().
*/
function trinion_base_preprocess_views_view_table(&$variables) {
if ($variables['view']->id() == 'zadachi_naznachennye_mne' && ($variables['view']->current_display == 'page_1' || $variables['view']->current_display == 'page_4')) {
$variables['#attached']['library'][] = 'core/drupal.autocomplete';
foreach ($variables['result'] as $key => $res) {
foreach (['field_tz_tema', 'field_tz_otvetstvennyy', 'field_tz_ikonka', 'field_tz_ikonka_1', 'field_tz_kategoriya_zadachi'] as $field_name) {
$variables['rows'][$key]['attributes']->setAttribute('data-type', 'node');
$variables['rows'][$key]['attributes']->setAttribute('data-id', $res->nid);
$variables['rows'][$key]['columns'][$field_name]['attributes']->setAttribute('id', $field_name . '-' . $res->nid);
$variables['rows'][$key]['columns'][$field_name]['attributes']->setAttribute('data-field', $field_name);
$variables['rows'][$key]['columns'][$field_name]['attributes']->addClass('inline-change');
}
}
$variables['attributes']['class'][] = 't-changed-table';
$variables['attributes']['data-bundle'] = $variables['result'][0]->_entity->bundle();
}
}
function trinion_base_preprocess_trinion_notices(&$variables) {
$uid = Drupal::currentUser()->id();
$new = \Drupal::service('user.data')->get('trinion_base', $uid, 'new-notices-switcher');
$variables['data'] = [
'#theme' => 'trinion_notices_list_dropdown',
'#data' => \Drupal\trinion_base\Controller\NoticeController::getUserNotices($new),
];
$variables['has_new'] = \Drupal\trinion_base\Controller\NoticeController::getCountNewUserNotices();
$variables['show_new'] = \Drupal::service('user.data')->get('trinion_base', \Drupal::currentUser()->id(), 'new-notices-switcher');
}
/**
* Implements hook_entity_access().
*/
function trinion_base_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
if ($entity->getEntityType()->id() == 'node') {
$bundle = $entity->bundle();
$node_is_event_type = Drupal::service('trinion_main.helper')->getEntitiesTypeIsVocabularyList();
if (!in_array($bundle, $node_is_event_type) && $bundle != 'kurs_obucheniya') {
$otvetstvenniy = Drupal::service('trinion_main.helper')->getDocumentOtvetstvenniy($entity);
if ($otvetstvenniy && $otvetstvenniy != $account->id()) {
if ($operation == 'view') {
if ($bundle == 'zakaz_klienta')
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp zakaz_klienta') && $account->id() != $entity->get('uid')->getString());
else
return \Drupal\Core\Access\AccessResult::allowedIf($account->hasPermission('trinion_base view all'));
}
if ($operation == 'update') {
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_base edit all'));
}
}
}
if ($bundle == 'pdf_print_form_template') {
if ($operation == 'view') {
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('edit any pdf_print_form_template content'));
}
}
elseif ($bundle == 'trinion_uvedomlenie') {
return \Drupal\Core\Access\AccessResult::forbidden();
}
}
}
/**
* Implements hook_views_query_alter().
*/
function trinion_base_views_query_alter(\Drupal\views\ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query) {
if (in_array($view->id(), ['crm_spisok_sdelki', 'crm_spisok_kommercheskikh_predlozheniy', 'crm_spisok_zakazy_klienta', 'crm_spisok_scheta_klienta', 'crm_spisok_zakazy_postavschiku', 'crm_spisok_otgruzki', 'crm_spisok_schetov_postavschika', 'crm_spisok_poluchennye', 'crm_spisok_poluchennye', 'crm_spisok_postupleniya_tovarov', 'crm_spisok_zvonki', ])) {
if (Drupal::currentUser()->hasPermission('trinion_base view all')) {
foreach ($query->where as $key => $group) {
foreach ($group['conditions'] as $key2 => $condition) {
if ($condition['field'] instanceof \Drupal\Core\Database\Query\Condition) {
foreach ($condition['field']->conditions() as $key3 => $fd) {
if (isset($fd['value']) && $fd['value'] == '***CURRENT_USER***') {
unset($query->where[$key]['conditions'][$key2]);
}
}
}
}
}
}
}
}
/**
* Implements hook_mail().
*/
function trinion_base_mail($key, &$message, $params) {
$message['from'] .= ' ';
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
$message['headers']['Return-Path'] = $message['from'];
$mail_params = function($params) {
return [
'@nomer' => '#' . $params['nomer'],
'@tema' => $params['tema'],
'@url' => $params['url'],
'@avtor' => $params['avtor'],
'@change_maker' => $params['change_maker'],
'@status' => $params['status'],
'@project' => $params['project'],
'@prioritet' => $params['prioritet'],
'@otvetstvenniy' => $params['otvetstvenniy'],
'@start_time' => $params['start_time'] ?? '-',
'@activnost' => $params['activnost'],
'@host' => $params['host'],
'@text' => \Drupal\Core\Render\Markup::create($params['text'])
];
};
$task_notice_template = "<div style='font-family: sans-serif;'><h4><a href='@url'>@activnost @nomer: @tema</a></h4><ul><li><b>Task creator:</b> @avtor</li><li><b>Change maker:</b> @change_maker</li><li><b>Status:</b> @status</li><li><b>Priority:</b> @prioritet</li><li><b>Responsible:</b> @otvetstvenniy</li><li><b>Planned start time of the task:</b> @start_time</li></ul><div>@text</div><small>You have received this email because you are a user of the support portal <a href='@host'>@host</a></small></div>";
switch ($key) {
case 'noviy_comment_k_documentu':
$document_notice_template = "<div style='font-family: sans-serif;'>New comment by @tip_docuemtna <a href='@url'>@nomer</a> (@avtor) <hr><h4><a href='@url'>@tip_docuemtna @nomer</a></h4><ul><li><b>Author:</b> @avtor</li><li><b>Responsible:</b> @otvetstvenniy</li></ul><div>@text</div><hr><small>You have received this email because you are a user of the support portal <a href='@host'>@host</a></small></div>";
$placeholders = [
'@nomer' => '#' . $params['nomer'],
'@url' => $params['url'],
'@avtor' => $params['avtor'],
'@host' => $params['host'],
'@tip_docuemtna' => $params['tip_documenta'],
];
$placeholders['@text'] = \Drupal\Core\Render\Markup::create($params['comment']);
$message['subject'] = t('[@project - @activnost @nomer] New comment by @tip_docuemtna @nomer', $placeholders);
$message['body'][] = t($document_notice_template, $placeholders);
break;
case 'noviy_comment_k_zadache':
$placeholders = $mail_params($params);
$placeholders['@text'] = \Drupal\Core\Render\Markup::create($params['comment']);
$message['subject'] = t('[@project - @activnost @nomer] New comment @tema', $placeholders);
$message['body'][] = t($task_notice_template, $placeholders);
break;
case 'novya_zadacha':
$placeholders = $mail_params($params);
$message['subject'] = t('[@project - @activnost @nomer] New task: @tema', $placeholders);
$message['body'][] = t($task_notice_template, $placeholders);
break;
case 'izmeneniye_zadacha':
$placeholders = $mail_params($params);
$message['subject'] = t('[@project - @activnost @nomer] Task @nomer has been changed by @change_maker', $placeholders);
$message['body'][] = t($task_notice_template, $placeholders);
break;
case 'registratia_polzovatelia_zakaz':
$site_name = \Drupal::config('system.site')->get('name');
$login_url = $_SERVER['HTTP_ORIGIN'] . \Drupal\Core\Url::fromRoute('user.login')->toString();
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('An account has been created for you on the site @site_name', ['@site_name' => $site_name]);
$message['body'][] = t("Hello.\nAn account has been created for you on the site @site_name\nTo log in, follow the link @login_url\nLogin: @login\nPassword: @password", ['@site_name' => $site_name, '@login_url' => $login_url, '@login' => $params['login'], '@password' => $params['password']]);
break;
case 'oplata_kursa':
$site_name = \Drupal::config('system.site')->get('name');
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('Successful payment of the order on the site @site_name', ['@site_name' => $site_name]);
$message['body'][] = t("Hello.\nYou have successfully paid for the course \"@course_name\".\nTo complete the course, you must log in and go to the course page.", ['@course_name' => $params['course_name']]);
break;
}
}
function trinion_base_update_or_install_config($prefix, $dir) {
$updated = [];
$created = [];
/** @var \Drupal\Core\Config\ConfigManagerInterface $config_manger */
$config_manger = \Drupal::service('config.manager');
$files = glob($dir . '/config/install/' . $prefix . '.yml');
foreach ($files as $file) {
$raw = file_get_contents($file);
$value = \Drupal\Component\Serialization\Yaml::decode($raw);
if (!is_array($value)) {
throw new \RuntimeException(sprintf('Invalid YAML file %s'), $file);
}
$type = $config_manger->getEntityTypeIdByName(preg_replace('/\.yml$/', '', basename($file)));
if (is_null($type)) {
$active_storage = \Drupal::service('config.storage');
$active_storage->write($prefix, $value);
}
else {
$entity_manager = $config_manger->getEntityTypeManager();
$definition = $entity_manager->getDefinition($type);
$id_key = $definition->getKey('id');
$id = $value[$id_key];
/** @var \Drupal\Core\Config\Entity\ConfigEntityStorage $entity_storage */
$entity_storage = $entity_manager->getStorage($type);
$entity = $entity_storage->load($id);
if ($entity) {
$entity = $entity_storage->updateFromStorageRecord($entity, $value);
$entity->save();
$updated[] = $id;
} else {
$entity = $entity_storage->createFromStorageRecord($value);
$entity->save();
$created[] = $id;
}
}
}
drupal_flush_all_caches();
return [
'updated' => $updated,
'created' => $created,
];
}
function trinion_base_common_update_operations(&$sandbox, $prefixes, $dir) {
if (!isset($sandbox['total'])) {
$sandbox['total'] = count($prefixes);
$sandbox['current'] = 0;
}
$results = [];
foreach ($prefixes as $key => $prefix) {
if ($key == $sandbox['current']) {
$results[$prefix] = trinion_base_update_or_install_config($prefix, $dir);
$msg = $prefix;
}
}
$sandbox['current']++;
$sandbox['#finished'] = $sandbox['current'] == count($prefixes);
return $msg;
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function trinion_base_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
if (strpos($hook, 'trinion_widget_') === 0) {
$suggestions[] = 'trinion_widget_pie__' . $variables['id'];
}
}
