WIP: Add PauseTraining plugin BT#16298

pull/3350/head
Julio Montoya 6 years ago
parent dcf85208b7
commit 57cff428f1
  1. 99
      main/auth/pausetraining.php
  2. 22
      main/auth/profile.php
  3. 6
      main/cron/notification.php
  4. 40
      main/inc/lib/api.lib.php
  5. 17
      main/inc/lib/tracking.lib.php
  6. 1
      main/inc/lib/webservices/Rest.php
  7. 2
      main/webservices/api/tests/CreateSessionFromModelTest.php
  8. 1
      main/webservices/api/tests/GetCourseLpProgressTest.php
  9. 37
      main/webservices/api/tests/UpdateUserPauseTrainingTest.php
  10. 16
      main/webservices/api/v2.php
  11. 197
      plugin/pausetraining/PauseTraining.php
  12. 6
      plugin/pausetraining/README.md
  13. 4
      plugin/pausetraining/config.php
  14. 6
      plugin/pausetraining/cron.php
  15. 1
      plugin/pausetraining/index.php
  16. 9
      plugin/pausetraining/install.php
  17. 17
      plugin/pausetraining/lang/english.php
  18. 15
      plugin/pausetraining/lang/french.php
  19. 1
      plugin/pausetraining/lang/spanish.php
  20. 4
      plugin/pausetraining/plugin.php
  21. 6
      plugin/pausetraining/view/notification_content.tpl

@ -0,0 +1,99 @@
<?php
/* For licensing terms, see /license.txt */
$cidReset = true;
require_once __DIR__.'/../inc/global.inc.php';
api_block_anonymous_users(true);
$allow = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
$allowPauseFormation = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
if (false === $allow || false === $allowPauseFormation) {
api_not_allowed(true);
}
$userId = api_get_user_id();
$userInfo = api_get_user_info($userId);
$justification = '';
$plugin = PauseTraining::create();
$form = new FormValidator('pausetraining');
$form->addHeader($plugin->get_lang('PauseTraining'));
$extraField = new ExtraField('user');
$return = $extraField->addElements(
$form,
$userId,
[],
false,
false,
['pause_formation', 'start_pause_date', 'end_pause_date', 'allow_notifications'],
[],
[],
false,
true
);
$form->addRule(
['extra_start_pause_date', 'extra_end_pause_date'],
get_lang('StartDateShouldBeBeforeEndDate'),
'date_compare',
'lte'
);
$form->addButtonSend(get_lang('Update'));
if ($form->validate()) {
$values = $form->getSubmitValues(1);
$values['item_id'] = $userId;
if (!isset($values['extra_pause_formation'])) {
$values['extra_pause_formation'] = 0;
}
if (!isset($values['extra_allow_notifications'])) {
$values['extra_allow_notifications'] = 0;
}
$extraField = new ExtraFieldValue('user');
$extraField->saveFieldValues($values, true, false, [], [], true);
Display::addFlash(Display::return_message(get_lang('Update')));
header('Location: '.api_get_self());
exit;
}
$headers = [
[
'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
'content' => get_lang('Profile'),
],
[
'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
'content' => $plugin->get_lang('PauseTraining'),
],
];
$tab = Display::tabsOnlyLink($headers, 2);
$content = $tab.$form->returnForm();
$tpl = new Template(get_lang('ModifyProfile'));
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'home');
$menu = SocialManager::show_social_menu(
'home',
null,
api_get_user_id(),
false,
false
);
$tpl->assign('social_menu_block', $menu);
$tpl->assign('social_right_content', $content);
$social_layout = $tpl->get_template('social/edit_profile.tpl');
$tpl->display($social_layout);

@ -727,6 +727,24 @@ if ($allowJustification) {
$justification = Display::tabsOnlyLink($headers, 1);
}
$allowPauseTraining = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
$allowEdit = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
$pauseTraining = '';
if ($allowPauseTraining && $allowEdit) {
$plugin = PauseTraining::create();
$headers = [
[
'url' => api_get_self(),
'content' => get_lang('Profile'),
],
[
'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
'content' => $plugin->get_lang('PauseTraining'),
],
];
$pauseTraining = Display::tabsOnlyLink($headers, 1);
}
if ($allowSocialTool) {
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'home');
$menu = SocialManager::show_social_menu(
@ -738,7 +756,7 @@ if ($allowSocialTool) {
);
$tpl->assign('social_menu_block', $menu);
$tpl->assign('social_right_content', $justification.$form->returnForm());
$tpl->assign('social_right_content', $justification.$pauseTraining.$form->returnForm());
$social_layout = $tpl->get_template('social/edit_profile.tpl');
$tpl->display($social_layout);
@ -750,7 +768,7 @@ if ($allowSocialTool) {
$imageToShow .= '<a class="expand-image pull-right" href="'.$bigImage.'" /><img src="'.$normalImage.'"></a>';
$imageToShow .= '</div>';
$content = $imageToShow.$form->returnForm().$justification;
$content = $imageToShow.$form->returnForm().$justification.$pauseTraining;
$tpl->assign('content', $content);
$tpl->display_one_col_template();

@ -1,11 +1,11 @@
<?php
/* For licensing terms, see /license.txt */
/**
* @package chamilo.notification
*
* @author Julio Montoya <gugli100@gmail.com>
*/
if (PHP_SAPI != 'cli') {
if (PHP_SAPI !== 'cli') {
die('Run this script through the command line or comment this line in the code');
}

@ -9057,6 +9057,46 @@ function api_mail_html(
return true;
}
$allow = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
$allowPauseFormation = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
if ($allow && $allowPauseFormation) {
$userInfo = api_get_user_info_from_email($recipient_email);
if (!empty($userInfo)) {
$extraFieldValue = new ExtraFieldValue('user');
$allowNotifications = $extraFieldValue->get_values_by_handler_and_field_variable(
$userInfo['user_id'],
'allow_notifications'
);
if (!empty($allowNotifications) && isset($allowNotifications['value']) && 0 === (int) $allowNotifications['value']) {
$startDate = $extraFieldValue->get_values_by_handler_and_field_variable(
$userInfo['user_id'],
'start_pause_date'
);
$endDate = $extraFieldValue->get_values_by_handler_and_field_variable(
$userInfo['user_id'],
'end_pause_date'
);
if (
!empty($startDate) && isset($startDate['value']) && !empty($startDate['value']) &&
!empty($endDate) && isset($endDate['value']) && !empty($endDate['value'])
) {
$now = time();
$start = api_strtotime($startDate['value']);
$end = api_strtotime($startDate['value']);
if ($now > $start && $now < $end) {
return false;
}
}
}
}
}
$mail = new PHPMailer();
$mail->Mailer = $platform_email['SMTP_MAILER'];
$mail->Host = $platform_email['SMTP_HOST'];

@ -4459,9 +4459,24 @@ class Tracking
}
$rs = Database::query($sql);
$allow = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
$allowPauseFormation = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
$extraFieldValue = new ExtraFieldValue('user');
$users = [];
while ($user = Database::fetch_array($rs)) {
$users[] = $user['user_id'];
$userId = $user['user_id'];
if ($allow && $allowPauseFormation) {
$pause = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'pause_formation');
if (!empty($pause) && isset($pause['value']) && 1 == $pause['value']) {
// Skip user because he paused his formation.
continue;
}
}
$users[] = $userId;
}
return $users;

@ -67,6 +67,7 @@ class Rest extends WebService
const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
const USERNAME_EXIST = 'username_exist';
const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
/**
* @var Session

@ -50,7 +50,6 @@ class CreateSessionFromModelTest extends V2TestCase
'endDate' => $endDate,
]
);
//var_dump($newSessionId);exit;
// assert the session was created and given the returned session id
$entityManager = Database::getManager();
@ -70,7 +69,6 @@ class CreateSessionFromModelTest extends V2TestCase
// clean up
SessionManager::delete($modelSessionId);
SessionManager::delete($newSessionId);
//var_dump($modelSessionId);exit;
}
/**

@ -15,7 +15,6 @@ class GetCourseLpProgressTest extends V2TestCase
public function testCourseList()
{
$result = $this->dataArray();
var_dump($result);
$this->assertIsArray($result);
//$result = $this->dataArray();

@ -0,0 +1,37 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* UPDATE_USER_PAUSE_TRAINING webservice unit tests
*/
class UpdateUserPauseTrainingTest extends V2TestCase
{
public function action()
{
return Rest::UPDATE_USER_PAUSE_TRAINING;
}
/**
* creates a minimal test user
* asserts that it was created with the supplied data
*
* @throws Exception if it cannot delete the created test user
*/
public function testUpdate()
{
$params = [
'user_id' => 1,
'pause_formation' => 0,
'start_pause_date' => '2020-06-30 10:00',
'end_pause_date' => '2020-06-30 11:00',
'allow_notifications' => 0,
];
$userId = $this->integer($params);
// assert each field was filled with provided information
$this->assertSame($userId, 1);
}
}

@ -340,6 +340,22 @@ try {
echo json_encode($data, JSON_PRETTY_PRINT);
exit;
break;
case Rest::UPDATE_USER_PAUSE_TRAINING:
$allow = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
$allowPauseFormation = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
if (false === $allow || false === $allowPauseFormation) {
throw new Exception(get_lang('Plugin configured'));
}
if (empty($_POST['user_id'])) {
throw new Exception('user_id is required');
}
$plugin = PauseTraining::create();
$data = $plugin->updateUserPauseTraining($_POST['user_id'], $_POST);
$restResponse->setData([$data]);
break;
default:
throw new Exception(get_lang('InvalidAction'));
}

@ -0,0 +1,197 @@
<?php
/* For licensing terms, see /license.txt */
class PauseTraining extends Plugin
{
public $isCoursePlugin = false;
protected function __construct()
{
parent::__construct(
'0.1',
'Julio Montoya',
[
'tool_enable' => 'boolean',
'allow_users_to_edit_pause_formation' => 'boolean',
'cron_alert_users_if_inactive_days' => 'text', // Example: "5" or "5,10,15"
]
);
}
public static function create()
{
static $result = null;
return $result ? $result : $result = new self();
}
public function updateUserPauseTraining($userId, $values)
{
$userInfo = api_get_user_info($userId);
if (empty($userInfo)) {
throw new Exception("User #$userId does not exists");
}
$variables = [
'pause_formation',
'start_pause_date',
'end_pause_date',
'allow_notifications',
];
$valuesToUpdate = [
'item_id' => $userId,
];
// Check if variables exist.
foreach ($variables as $variable) {
if (!isset($values[$variable])) {
throw new Exception("Variable '$variable' is missing. Cannot updated.");
}
$valuesToUpdate['extra_'.$variable] = $values[$variable];
}
// Clean variables
$pause = (int) $valuesToUpdate['extra_pause_formation'];
if (empty($pause)) {
$valuesToUpdate['extra_pause_formation'] = 0;
} else {
$valuesToUpdate['extra_pause_formation'] = [];
$valuesToUpdate['extra_pause_formation']['extra_pause_formation'] = $pause;
}
$notification = (int) $valuesToUpdate['extra_allow_notifications'];
if (empty($notification)) {
$valuesToUpdate['extra_allow_notifications'] = 0;
} else {
$valuesToUpdate['extra_allow_notifications'] = [];
$valuesToUpdate['extra_allow_notifications']['extra_allow_notifications'] = $notification;
}
$check = DateTime::createFromFormat('Y-m-d H:i', $valuesToUpdate['extra_start_pause_date']);
if (false === $check) {
throw new Exception("start_pause_date is not valid date time format should be: Y-m-d H:i");
}
$check = DateTime::createFromFormat('Y-m-d H:i', $valuesToUpdate['extra_end_pause_date']);
if (false === $check) {
throw new Exception("end_pause_date is not valid date time format should be: Y-m-d H:i");
}
if (api_strtotime($valuesToUpdate['extra_start_pause_date']) > api_strtotime($valuesToUpdate['extra_end_pause_date'])) {
throw new Exception("end_pause_date must be bigger than start_pause_date");
}
$extraField = new ExtraFieldValue('user');
$extraField->saveFieldValues($valuesToUpdate, true, false, [], [], true);
return (int) $userId;
}
public function runCron()
{
$enable = $this->get('tool_enable');
$enableDays = $this->get('cron_alert_users_if_inactive_days');
if ($enable && !empty($enableDays)) {
$enableDaysList = explode(',', $enableDays);
rsort($enableDaysList);
$loginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
$userTable = Database::get_main_table(TABLE_MAIN_USER);
$now = api_get_utc_datetime();
$usersNotificationPerDay = [];
$users = [];
foreach ($enableDaysList as $day) {
$day = (int) $day;
$sql = "SELECT
stats_login.user_id,
MAX(stats_login.login_course_date) max_date
FROM $loginTable stats_login
INNER JOIN $userTable u
ON (u.id = stats_login.user_id)
WHERE
u.status <> ".ANONYMOUS." AND
u.active = 1
GROUP BY stats_login.user_id
HAVING DATE_SUB('$now', INTERVAL '$day' DAY) > max_date ";
$rs = Database::query($sql);
while ($user = Database::fetch_array($rs)) {
$userId = $user['user_id'];
if (in_array($userId, $users)) {
continue;
}
$users[] = $userId;
$usersNotificationPerDay[$day][] = $userId;
}
}
$usersNotificationPerDay[5][] = 1;
if (!empty($usersNotificationPerDay)) {
ksort($usersNotificationPerDay);
$extraFieldValue = new ExtraFieldValue('user');
foreach ($usersNotificationPerDay as $day => $userList) {
$template = new Template();
// @todo check email format
$title = sprintf($this->get_lang('NotificationXDays'), $day);
foreach ($userList as $userId) {
$userInfo = api_get_user_info($userId);
$pause = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'pause_formation');
if (!empty($pause) && isset($pause['value']) && 1 == $pause['value']) {
// Skip user because he paused his formation.
continue;
}
$template->assign('days', $day);
$template->assign('user', $userInfo);
$content = $template->fetch('pausetraining/view/notification_content.tpl');
//MessageManager::send_message($userId, $title, $content);
}
}
}
}
}
public function install()
{
UserManager::create_extra_field(
'pause_formation',
ExtraField::FIELD_TYPE_CHECKBOX,
$this->get_lang('PauseFormation'),
''
);
UserManager::create_extra_field(
'start_pause_date',
ExtraField::FIELD_TYPE_DATETIME,
$this->get_lang('StartPauseDateTime'),
''
);
UserManager::create_extra_field(
'end_pause_date',
ExtraField::FIELD_TYPE_DATETIME,
$this->get_lang('EndPauseDateTime'),
''
);
UserManager::create_extra_field(
'allow_notifications',
ExtraField::FIELD_TYPE_CHECKBOX,
$this->get_lang('AllowEmailNotification'),
''
);
}
public function uninstall()
{
}
}

@ -0,0 +1,6 @@
Installation
============
1. Enabled the plugin from the list of plugins.
2. Click "Configure" once the plugin was enabled.
3. Select tool_enable = Yes and save.

@ -0,0 +1,4 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../main/inc/global.inc.php';

@ -0,0 +1,6 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../main/inc/global.inc.php';
PauseTraining::create()->runCron();

@ -0,0 +1,9 @@
<?php
/* For license terms, see /license.txt */
require_once __DIR__.'/config.php';
if (!api_is_platform_admin()) {
die('You must have admin permissions to install plugins');
}
PauseTraining::create()->install();

@ -0,0 +1,17 @@
<?php
$strings['plugin_title'] = "Pause training";
$strings['plugin_comment'] = "";
$strings['tool_enable'] = 'Enable plugin';
$strings['tool_enable_help'] = '';
$strings['PauseTraining'] = "Pause training";
$strings['allow_users_to_edit_pause_formation'] = 'Allow users to edit pause formation';
$strings['cron_alert_users_if_inactive_days'] = 'Alert users if inactive days (via cron)';
$strings['PauseFormation'] = 'Pause my formation';
$strings['StartPauseDateTime'] = 'Start pause date';
$strings['EndPauseDateTime'] = 'End pause date';
$strings['AllowEmailNotification'] = 'Allow email notifications';
$strings['NotificationXDays'] = 'Notification %s days';

@ -0,0 +1,15 @@
<?php
$strings['plugin_title'] = "Pause training";
$strings['plugin_comment'] = "";
$strings['tool_enable'] = 'Enable plugin';
$strings['tool_enable_help'] = '';
$strings['PauseTraining'] = "Pause training";
$strings['allow_users_to_edit_pause_formation'] = 'Allow users to edit pause formation';
$strings['cron_alert_users_if_inactive_days'] = 'Alert users if inactive days (via cron)';
$strings['PauseFormation'] = 'Mettre en pause ma formation';
$strings['StartPauseDateTime'] = 'Date de début de pause';
$strings['EndPauseDateTime'] = 'Date de fin de pause';
$strings['AllowEmailNotification'] = 'Continuer à recevoir les mails de la plateforme';
$strings['NotificationXDays'] = 'Notification %s days';

@ -0,0 +1,4 @@
<?php
require_once __DIR__.'/config.php';
$plugin_info = PauseTraining::create()->get_info();

@ -0,0 +1,6 @@
{{ 'Days' | get_lang }}: {{ days }}
{{ 'User' | get_lang }}: {{ user.complete_name }}
{#{{ 'AppliesTo'|get_plugin_lang('PauseTraining') }}#}
Loading…
Cancel
Save