From ec3f16a45e2c6b601edb43aef0a6c0333a4204cc Mon Sep 17 00:00:00 2001 From: Alex Orluc <alex.orluc@maarch.org> Date: Wed, 14 Mar 2018 20:32:30 +0100 Subject: [PATCH] FEAT #132 refactoring notifications components --- ...notification-administration.component.html | 138 +++-- ...otifications-administration.component.html | 102 +++- .../notification-administration.component.ts | 71 +-- .../notifications-administration.component.ts | 131 ++++- .../js/angular/lang/lang-en.ts | 60 ++- .../js/angular/lang/lang-fr.ts | 59 ++- apps/maarch_entreprise/js/angularFunctions.js | 2 +- core/Test/NotificationControllerTest.php | 243 +++++---- .../NotificationScheduleControllerTest.php | 156 +++--- .../batch/basket_event_stack.php | 488 +++++++++--------- .../batch/process_event_stack.php | 456 ++++++++-------- .../notifications/diffusion_types/contact.php | 72 ++- .../diffusion_types/copy_list.php | 286 +++++----- .../diffusion_types/copy_list_sample.php | 165 ------ .../diffusion_types/dest_entity.php | 312 +++++------ .../diffusion_types/dest_user.php | 303 +++++------ .../diffusion_types/dest_user_sample.php | 115 ----- .../diffusion_types/dest_user_sign.php | 308 +++++------ .../diffusion_types/dest_user_visa.php | 308 +++++------ .../notifications/diffusion_types/entity.php | 122 ++--- .../notifications/diffusion_types/group.php | 89 +--- .../diffusion_types/note_copy_list.php | 47 -- .../diffusion_types/note_dest_user.php | 46 -- .../notifications/diffusion_types/user.php | 107 ++-- .../notifications/manage_notifications.php | 289 +++++------ .../manage_notifications_controler.php | 309 ++++++----- .../xml/IVS/validation_rules.xml | 1 - modules/notifications/xml/diffusion_type.xml | 135 ----- modules/notifications/xml/event_type.xml | 24 +- sql/data_fr.sql | 65 ++- sql/develop.sql | 3 + sql/structure.sql | 1 - .../controllers/NotificationController.php | 168 +++--- .../NotificationScheduleController.php | 78 +-- .../models/NotificationModelAbstract.php | 173 +++---- .../NotificationScheduleModelAbstract.php | 108 ++-- 36 files changed, 2432 insertions(+), 3108 deletions(-) delete mode 100755 modules/notifications/diffusion_types/copy_list_sample.php delete mode 100755 modules/notifications/diffusion_types/dest_user_sample.php delete mode 100755 modules/notifications/diffusion_types/note_copy_list.php delete mode 100755 modules/notifications/diffusion_types/note_dest_user.php delete mode 100755 modules/notifications/xml/diffusion_type.xml diff --git a/apps/maarch_entreprise/Views/notification-administration.component.html b/apps/maarch_entreprise/Views/notification-administration.component.html index a8f4de71734..7af22db2d28 100644 --- a/apps/maarch_entreprise/Views/notification-administration.component.html +++ b/apps/maarch_entreprise/Views/notification-administration.component.html @@ -4,10 +4,10 @@ <mat-icon class="maarchLogo" [svgIcon]="mobileQuery.matches ? 'maarchLogoOnly' : 'maarchLogo'"></mat-icon> </button> <h1 class="admin-toolbar-title" *ngIf="!creationMode">{{lang.notificationModification}} - <small [class.hide-for-mobile]="mobileQuery.matches">{{notification.notification_id}}</small> + <small [class.hide-for-mobile]="mobileQuery.matches">{{notification.description}} ({{notification.notification_id}})</small> </h1> <h1 class="admin-toolbar-title" *ngIf="creationMode">{{lang.notificationCreation}} - <small [class.hide-for-mobile]="mobileQuery.matches">{{notification.notification_id}}</small> + <small [class.hide-for-mobile]="mobileQuery.matches">{{notification.description}} ({{notification.notification_id}})</small> </h1> <span style="flex: 1 1 auto;"></span> </mat-toolbar> @@ -16,14 +16,26 @@ [opened]="mobileQuery.matches ? false : true"> <menu-nav></menu-nav> <mat-divider></mat-divider> - <mat-nav-list *ngIf="!creationMode && !loading && !notification.scriptcreated"> + <mat-nav-list> <h3 mat-subheader>{{lang.actions}}</h3> - <a mat-list-item (click)="createScript()"> + <a mat-list-item (click)="createScript()" *ngIf="!creationMode && !loading && !notification.scriptcreated"> <mat-icon color="primary" mat-list-icon class="fa fa-terminal"></mat-icon> <p mat-line> {{lang.createScriptNotification}} </p> </a> + <a mat-list-item *ngIf="!creationMode && !loading && notification.is_enabled == 'N'" (click)="toggleNotif()"> + <mat-icon color="accent" mat-list-icon class="fa fa-play"></mat-icon> + <p mat-line> + {{lang.activateNotification}} + </p> + </a> + <a mat-list-item *ngIf="!creationMode && !loading && notification.is_enabled == 'Y'" (click)="toggleNotif()"> + <mat-icon color="warn" mat-list-icon class="fa fa-pause"></mat-icon> + <p mat-line> + {{lang.suspendNotification}} + </p> + </a> </mat-nav-list> <mat-divider></mat-divider> <menu-app></menu-app> @@ -33,15 +45,15 @@ <mat-spinner style="margin:auto;"></mat-spinner> </div> <mat-card *ngIf="!loading" class="card-app-content"> + <div *ngIf="notification.is_enabled == 'N'" class="text-warning" style="position: absolute;opacity: 0.1;font-size: 120px;transform: rotate(324deg);-webkit-transform: rotate(324deg);margin-left: 25%;margin-top: 90px;">{{lang.suspended}}</div> <form class="form-horizontal" (ngSubmit)="onSubmit()" #notificationsFormUp="ngForm"> <div class="form-group"> <div class="col-md-12"> <mat-form-field> <input matInput [(ngModel)]="notification.notification_id" required name="notification_id" id="notification_id" title="{{lang.id}}" - type="text" pattern="^[\w.-]*$" placeholder="{{lang.id}}" maxlength="50"> + type="text" pattern="^[\w.-]*$" placeholder="{{lang.id}}" maxlength="50" [disabled]="!creationMode"> </mat-form-field> </div> - </div> <div class="form-group"> <div class="col-md-12"> @@ -50,64 +62,114 @@ type="text" placeholder="{{lang.description}}" maxlength="255"> </mat-form-field> </div> - - </div> - <div class="form-group"> - <div class="col-md-12"> - <mat-slide-toggle [(ngModel)]="notification.is_enabled" id="is_enabled" name="is_enabled" color="primary" [checked]="notification.is_enabled == 'Y'"> - {{lang.NotificationToEnable}} - </mat-slide-toggle> - </div> - </div> <div class="form-group"> <div class="col-md-12"> <mat-form-field> <mat-select id="event_id" name="event_id" title="{{lang.NotificationEvent}}" placeholder="{{lang.NotificationEvent}}" [(ngModel)]="notification.event_id" - required maxlength="255"> - <mat-option *ngFor="let event of notification.data.event" [value]="event.id"> - {{event.label_action}} - </mat-option> + required> + <mat-optgroup label="{{lang.triggerSystem}} :"> + <ng-container *ngFor="let event of notification.data.event"> + <mat-option *ngIf="!isNumber(event.id)" [value]="event.id"> + <mat-icon class="fa fa-gear" color="primary" style="height:auto;"></mat-icon> {{event.label_action}} + </mat-option> + </ng-container> + </mat-optgroup> + <mat-optgroup label="{{lang.triggerAction}} :"> + <ng-container *ngFor="let event of notification.data.event"> + <mat-option *ngIf="isNumber(event.id)" [value]="event.id"> + <mat-icon class="fa fa-exchange" color="primary" style="height:auto;"></mat-icon> {{event.label_action}} + </mat-option> + </ng-container> + </mat-optgroup> </mat-select> </mat-form-field> </div> </div> <div class="form-group"> - <div class="col-md-12"> + <div class="col-md-8"> <mat-form-field> - <mat-select id="template_id" name="template_id" title="{{lang.NotificationModel}}" placeholder="{{lang.NotificationModel}}" - [(ngModel)]="notification.template_id" required maxlength="1"> + <mat-select id="template_id" name="template_id" title="{{lang.notificationModel}}" placeholder="{{lang.notificationModel}}" + [(ngModel)]="notification.template_id" required> <mat-option *ngFor="let template of notification.data.template" [value]="template.template_id"> {{template.template_label}} </mat-option> </mat-select> </mat-form-field> </div> - - </div> - <div class="form-group"> - <div class="col-md-12"> + <div class="col-md-4"> <mat-form-field> - <mat-select id="diffusion_type" name="diffusion_type" title="{{lang.NotificationDiffusionType}}" placeholder="{{lang.NotificationDiffusionType}}" - [(ngModel)]="notification.diffusion_type" required maxlength="50"> - <mat-option *ngFor="let diffusionType of notification.data.diffusionType" [value]="diffusionType.id"> - {{diffusionType.label}} + <mat-select id="attachfor_type" name="attachfor_type" title="{{lang.attachment}}" placeholder="{{lang.attachment}}" [(ngModel)]="notification.attachfor_type"> + <mat-option value=""> + {{lang.noAttachment}} + </mat-option> + <mat-option value="main_document"> + {{lang.notificationJoinDocument}} </mat-option> </mat-select> </mat-form-field> </div> - </div> - <div class="form-group"> - <div class="col-md-12"> + <div class="col-md-4"> <mat-form-field> - <mat-select id="attachfor_type" name="attachfor_type" title="{{lang.NotificationJoinDocument}}" placeholder="{{lang.NotificationJoinDocument}}" - [(ngModel)]="notification.attachfor_type"> - <mat-option value="">Jamais</mat-option> - <mat-option *ngFor="let diffusionType of notification.data.diffusionType" [value]="diffusionType.id"> - {{diffusionType.label}} + <mat-select id="diffusion_type" name="diffusion_type" title="{{lang.sendTo}}" placeholder="{{lang.sendTo}}" + [(ngModel)]="notification.diffusion_type" required> + <mat-optgroup label="{{lang.memberUserDest}} :" *ngIf="notification.event_id != 'baskets'"> + <ng-container *ngFor="let diffusionType of notification.data.diffusionType"> + <mat-option *ngIf="diffusionType.id == 'dest_user'" [value]="diffusionType.id">{{diffusionType.label}}</mat-option> + </ng-container> + </mat-optgroup> + <mat-optgroup label="{{lang.memberUsersCopy}} :" *ngIf="notification.event_id != 'baskets'"> + <ng-container *ngFor="let diffusionType of notification.data.diffusionType"> + <mat-option *ngIf="diffusionType.id == 'copy_list'" [value]="diffusionType.id">{{diffusionType.label}}</mat-option> + </ng-container> + </mat-optgroup> + <mat-optgroup label="{{lang.memberAllUsers}} :"> + <ng-container *ngFor="let diffusionType of notification.data.diffusionType"> + <mat-option *ngIf="diffusionType.id == 'group' || (diffusionType.id == 'entity' && notification.event_id != 'baskets') || (diffusionType.id == 'user' && notification.event_id != 'baskets')" [value]="diffusionType.id">{{diffusionType.label}}</mat-option> + </ng-container> + </mat-optgroup> + <mat-optgroup label="{{lang.others}} :" *ngIf="notification.event_id != 'baskets'"> + <ng-container *ngFor="let diffusionType of notification.data.diffusionType"> + <mat-option *ngIf="diffusionType.id != 'group' && diffusionType.id != 'entity' && diffusionType.id != 'user' && diffusionType.id != 'copy_list' && diffusionType.id != 'group' && diffusionType.id != 'dest_user'" + [value]="diffusionType.id">{{diffusionType.label}}</mat-option> + </ng-container> + </mat-optgroup> + </mat-select> + </mat-form-field> + </div> + <div class="col-md-8"> + <mat-form-field *ngIf="notification.diffusion_type == 'group'"> + <mat-select id="diffusion_properties" name="diffusion_properties" title="{{lang.memberDiffTypeUsers}}" placeholder="{{lang.memberDiffTypeUsers}}" + required multiple [(ngModel)]="notification.diffusion_properties"> + <mat-option *ngFor="let group of notification.data.groups" [value]="group.group_id"> + {{group.group_desc}} + </mat-option> + </mat-select> + </mat-form-field> + <mat-form-field *ngIf="notification.diffusion_type == 'user'"> + <mat-select id="diffusion_properties" name="diffusion_properties" title="{{lang.memberDiffTypeUsers}}" placeholder="{{lang.memberDiffTypeUsers}}" + required multiple [(ngModel)]="notification.diffusion_properties"> + <mat-option *ngFor="let user of notification.data.users" [value]="user.user_id"> + {{user.label}} + </mat-option> + </mat-select> + </mat-form-field> + <mat-form-field *ngIf="notification.diffusion_type == 'entity'"> + <mat-select id="diffusion_properties" name="diffusion_properties" title="{{lang.memberDiffTypeUsers}}" placeholder="{{lang.memberDiffTypeUsers}}" + required multiple [(ngModel)]="notification.diffusion_properties"> + <mat-option *ngFor="let entity of notification.data.entities" [value]="entity.entity_id"> + {{entity.entity_label}} + </mat-option> + </mat-select> + </mat-form-field> + <mat-form-field *ngIf="notification.diffusion_type == 'dest_user' || notification.diffusion_type == 'copy_list' || notification.diffusion_type == 'dest_entity' || notification.diffusion_type == 'dest_user_visa' || notification.diffusion_type == 'dest_user_sign'"> + <mat-select id="diffusion_properties" name="diffusion_properties" title="{{lang.selectedDocumentStatus}} (optionnel)" placeholder="{{lang.selectedDocumentStatus}} ({{lang.optional}})" + multiple [(ngModel)]="notification.diffusion_properties"> + <mat-option *ngFor="let status of notification.data.status" [value]="status.id"> + {{status.label_status}} </mat-option> </mat-select> </mat-form-field> diff --git a/apps/maarch_entreprise/Views/notifications-administration.component.html b/apps/maarch_entreprise/Views/notifications-administration.component.html index f6f2e334854..127c4d16100 100644 --- a/apps/maarch_entreprise/Views/notifications-administration.component.html +++ b/apps/maarch_entreprise/Views/notifications-administration.component.html @@ -21,7 +21,7 @@ {{lang.add}} </p> </a> - <a mat-list-item routerLink="/administration/notifications/schedule"> + <a mat-list-item (click)="loadCron();snav2.toggle();"> <mat-icon color="primary" mat-list-icon class="fa fa-clock-o"></mat-icon> <p mat-line> {{lang.toSchedule}} @@ -57,11 +57,10 @@ <mat-cell *matCellDef="let element" style="flex:2;"> {{element.description}} </mat-cell> </ng-container> <ng-container matColumnDef="is_enabled"> - <mat-header-cell *matHeaderCellDef mat-sort-header style="flex:1;" [class.hide-for-mobile]="mobileQuery.matches">{{lang.NotificationEnabled}}</mat-header-cell> - <mat-cell *matCellDef="let element" matTooltip="{{lang.view}}" - style="flex:1;" [class.hide-for-mobile]="mobileQuery.matches"> - <span *ngIf="element.is_enabled == 'N'"> {{lang.no}} </span> - <span *ngIf="element.is_enabled == 'Y'"> {{lang.yes}} </span> + <mat-header-cell *matHeaderCellDef mat-sort-header style="flex:1;" [class.hide-for-mobile]="mobileQuery.matches">{{lang.status}}</mat-header-cell> + <mat-cell *matCellDef="let element" matTooltip="{{lang.view}}" style="flex:1;" [class.hide-for-mobile]="mobileQuery.matches"> + <span *ngIf="element.is_enabled == 'Y'" color="primary" class="label">{{lang.active}}</span> + <span *ngIf="element.is_enabled == 'N'" color="warn" class="label">{{lang.suspended}}</span> </mat-cell> </ng-container> <ng-container matColumnDef="notifications"> @@ -73,16 +72,97 @@ </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> - <mat-row *matRowDef="let row; columns: displayedColumns;" routerLink="/administration/notifications/{{row.notification_sid}}" style="cursor:pointer;" matTooltip="{{lang.view}}"></mat-row> + <mat-row *matRowDef="let row; columns: displayedColumns;" routerLink="/administration/notifications/{{row.notification_sid}}" + style="cursor:pointer;" matTooltip="{{lang.view}}"></mat-row> </mat-table> </mat-card> </mat-sidenav-content> <mat-sidenav #snav2 [mode]="mobileQuery.matches ? 'over' : 'side'" [fixedInViewport]="mobileQuery.matches" fixedTopGap="56" position='end' [opened]="mobileQuery.matches ? false : false"> - - <mat-nav-list> - <h3 mat-subheader>Actions</h3> - </mat-nav-list> + <div class="alert alert-info" role="alert" style="margin:15px;"> + {{lang.NotificationScheduleInfo}} + </div> + <mat-list> + <h3 mat-subheader>{{lang.notificationSchedule}}</h3> + <form class="form-horizontal" #notifForm="ngForm" style="overflow:hidden;"> + <div class="form-group" style="padding-left:15px;padding-right:15px;"> + <div class="col-sm-4"> + <mat-form-field> + <mat-select name="hour" id="hour" title="{{lang.hour}}" placeholder="{{lang.hour}}" [(ngModel)]="newCron.h" required> + <mat-option *ngFor="let hour of hours" [value]="hour.value"> + {{hour.label}} + </mat-option> + </mat-select> + </mat-form-field> + </div> + <div class="col-sm-4"> + <mat-form-field> + <mat-select name="minute" id="minute" title="{{lang.minute}}" placeholder="{{lang.minute}}" [(ngModel)]="newCron.m" required> + <mat-option *ngFor="let minute of minutes" [value]="minute.value"> + {{minute.label}} + </mat-option> + </mat-select> + </mat-form-field> + </div> + <div class="col-sm-4"> + <mat-form-field> + <mat-select name="day" id="day" title="{{lang.day}}" placeholder="{{lang.day}}" [(ngModel)]="newCron.dow" required> + <mat-option *ngFor="let day of dow" [value]="day.value"> + {{day.label}} + </mat-option> + </mat-select> + </mat-form-field> + </div> + </div> + <div class="form-group" style="padding-left:15px;padding-right:15px;"> + <div class="col-sm-6"> + <mat-form-field> + <mat-select name="month" id="month" title="{{lang.month}}" placeholder="{{lang.month}}" [(ngModel)]="newCron.mon" required> + <mat-option *ngFor="let month of months" [value]="month.value"> + {{month.label}} + </mat-option> + </mat-select> + </mat-form-field> + </div> + <div class="col-sm-6"> + <mat-form-field> + <mat-select name="dayM" id="dayM" title="{{lang.dayOfMonth}}" placeholder="{{lang.dayOfMonth}}" [(ngModel)]="newCron.dom" required> + <mat-option *ngFor="let dayM of dom" [value]="dayM.value"> + {{dayM.label}} + </mat-option> + </mat-select> + </mat-form-field> + </div> + <div class="col-sm-12"> + <mat-form-field> + <mat-select name="script" id="script" title="{{lang.script}}" placeholder="{{lang.script}}" [(ngModel)]="newCron.cmd" required> + <mat-option *ngFor="let notif of authorizedNotification" [value]="notif.path"> + {{notif.description}} + </mat-option> + </mat-select> + </mat-form-field> + </div> + <div class="col-sm-12 text-center" style="padding:10px;"> + <button mat-raised-button [disabled]="!notifForm.form.valid" color="primary" (click)="saveCron()">{{lang.save}}</button> + </div> + </div> + </form> + </mat-list> + <mat-divider></mat-divider> + <mat-list> + <h3 mat-subheader>{{lang.activeCron}}</h3> + <mat-chip-list #chipList class="mat-chip-list-stacked"> + <span *ngFor="let notif of crontab;let i = index"> + <mat-chip color="primary" *ngIf="notif.state == 'normal'" style="cursor:pointer;margin:5px;border-radius:0px;display:flex;" + selectable="false" removable="true" (remove)="deleteCron(i)"> + {{notif.description}} + <span style="flex: 1 1 auto;"></span> + <b>{{notif.m}} {{notif.h}} {{notif.dom}} {{notif.mon}} {{notif.dow}}</b> + <mat-icon matTooltip="{{lang.delete}}" matChipRemove color="warn" class="fa fa-times"></mat-icon> + </mat-chip> + </span> + </mat-chip-list> + </mat-list> </mat-sidenav> </mat-sidenav-container> </div> \ No newline at end of file diff --git a/apps/maarch_entreprise/js/angular/app/administration/notification-administration.component.ts b/apps/maarch_entreprise/js/angular/app/administration/notification-administration.component.ts index fb9d60c3258..2334f9222c9 100644 --- a/apps/maarch_entreprise/js/angular/app/administration/notification-administration.component.ts +++ b/apps/maarch_entreprise/js/angular/app/administration/notification-administration.component.ts @@ -26,7 +26,6 @@ export class NotificationAdministrationComponent implements OnInit { loading: boolean = false; lang: any = LANG; - constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher, public http: HttpClient, private route: ActivatedRoute, private router: Router, private notify: NotificationService) { $j("link[href='merged_css.php']").remove(); this.mobileQuery = media.matchMedia('(max-width: 768px)'); @@ -34,17 +33,6 @@ export class NotificationAdministrationComponent implements OnInit { this.mobileQuery.addListener(this._mobileQueryListener); } - updateBreadcrumb(applicationName: string) { - var breadCrumb = "<a href='index.php?reinit=true'>" + applicationName + "</a> > <a onclick='location.hash = \"/administration\"' style='cursor: pointer'>" + this.lang.administration + "</a> > <a onclick='location.hash = \"/administration/notifications\"' style='cursor: pointer'>" + this.lang.notifications + "</a> > "; - - if (this.creationMode == true) { - breadCrumb += this.lang.notificationCreation; - } else { - breadCrumb += this.lang.notificationModification; - } - $j('#ariane')[0].innerHTML = breadCrumb; - } - ngOnDestroy(): void { this.mobileQuery.removeListener(this._mobileQueryListener); } @@ -59,7 +47,7 @@ export class NotificationAdministrationComponent implements OnInit { this.http.get(this.coreUrl + 'rest/administration/notifications/new') .subscribe((data: any) => { this.notification = data.notification; - + this.notification.attachfor_properties = []; this.loading = false; }, (err) => { this.notify.error(err.error.errors); @@ -69,6 +57,7 @@ export class NotificationAdministrationComponent implements OnInit { this.http.get(this.coreUrl + 'rest/notifications/' + params['identifier']) .subscribe((data: any) => { this.notification = data.notification; + this.notification.attachfor_properties = []; this.loading = false; }, (err) => { this.notify.error(err.error.errors); @@ -76,59 +65,25 @@ export class NotificationAdministrationComponent implements OnInit { } }); - this.updateBreadcrumb(angularGlobals.applicationName); - } createScript() { this.http.post(this.coreUrl + 'rest/scriptNotification', this.notification) .subscribe((data: any) => { this.notification.scriptcreated = data; - this.notify.success(this.lang.ScriptCreated); + this.notify.success(this.lang.scriptCreated); }, (err) => { this.notify.error(err.error.errors); }); } - selectAll(event: any) { - var target = event.target.getAttribute("data-target"); - $j('#' + target + ' option').prop('selected', true); - $j('#' + target).trigger('chosen:updated'); - } - - unselectAll(event: any) { - var target = event.target.getAttribute("data-target"); - $j('#' + target + ' option').prop('selected', false); - $j('#' + target).trigger('chosen:updated'); - } - onSubmit() { - if ($j("#groupslist").val()) { - this.notification.diffusion_properties = $j("#groupslist").val(); - } else if ($j("#entitieslist").val()) { - this.notification.diffusion_properties = $j("#entitieslist").val(); - } else if ($j("#statuseslist").val()) { - this.notification.diffusion_properties = $j("#statuseslist").val(); - } else if ($j("#userslist").val()) { - this.notification.diffusion_properties = $j("#userslist").val(); - } - if ($j("#joinDocJd").val() == null) { - this.notification.attachfor_properties = ''; - } else if ($j("#groupslistJd").val()) { - this.notification.attachfor_properties = $j("#groupslistJd").val(); - } else if ($j("#entitieslistJd").val()) { - this.notification.attachfor_properties = $j("#entitieslistJd").val(); - } else if ($j("#statuseslistJd").val()) { - this.notification.attachfor_properties = $j("#statuseslistJd").val(); - } else if ($j("#userslistJd").val()) { - this.notification.attachfor_properties = $j("#userslistJd").val(); - } - if (this.creationMode) { + this.notification.is_enabled = "Y"; this.http.post(this.coreUrl + 'rest/notifications', this.notification) .subscribe((data: any) => { this.router.navigate(['/administration/notifications']); - this.notify.success(this.lang.NotificationAdded); + this.notify.success(this.lang.notificationAdded); }, (err) => { this.notify.error(err.error.errors); }); @@ -142,4 +97,20 @@ export class NotificationAdministrationComponent implements OnInit { }); } } + + toggleNotif() { + if (this.notification.is_enabled == "Y") { + this.notification.is_enabled = "N"; + } else { + this.notification.is_enabled = "Y"; + } + this.http.put(this.coreUrl + 'rest/notifications/' + this.notification.notification_sid, this.notification) + .subscribe((data: any) => { + this.notify.success(this.lang.notificationUpdated); + }, (err) => { + this.notify.error(err.error.errors); + }); + } + + isNumber(val:any) { return typeof val === 'number'; } } diff --git a/apps/maarch_entreprise/js/angular/app/administration/notifications-administration.component.ts b/apps/maarch_entreprise/js/angular/app/administration/notifications-administration.component.ts index 6f1de1f61ee..b4996220ef0 100644 --- a/apps/maarch_entreprise/js/angular/app/administration/notifications-administration.component.ts +++ b/apps/maarch_entreprise/js/angular/app/administration/notifications-administration.component.ts @@ -3,7 +3,7 @@ import { MediaMatcher } from '@angular/cdk/layout'; import { HttpClient } from '@angular/common/http'; import { LANG } from '../translate.component'; import { NotificationService } from '../notification.service'; -import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material'; +import { MatSidenav, MatPaginator, MatTableDataSource, MatSort } from '@angular/material'; declare function $j(selector: any): any; @@ -24,6 +24,29 @@ export class NotificationsAdministrationComponent implements OnInit { loading: boolean = false; lang: any = LANG; + hours : any; + minutes : any; + + months : any = []; + + dom : any = []; + + dow : any = [] + + newCron: any = { + "m" : "", + "h" : "", + "dom" : "", + "mon" : "", + "cmd" : "", + "state": "normal" + } + + authorizedNotification :any; + crontab:any; + + @ViewChild('snav2') sidenav: MatSidenav; + displayedColumns = ['notification_id', 'description', 'is_enabled', 'notifications']; dataSource = new MatTableDataSource(this.notifications); @ViewChild(MatPaginator) paginator: MatPaginator; @@ -46,8 +69,6 @@ export class NotificationsAdministrationComponent implements OnInit { } ngOnInit(): void { - this.updateBreadcrumb(angularGlobals.applicationName); - this.coreUrl = angularGlobals.coreUrl; this.loading = true; @@ -65,12 +86,6 @@ export class NotificationsAdministrationComponent implements OnInit { }); } - updateBreadcrumb(applicationName: string) { - if ($j('#ariane')[0]) { - $j('#ariane')[0].innerHTML = "<a href='index.php?reinit=true'>" + applicationName + "</a> > <a onclick='location.hash = \"/administration\"' style='cursor: pointer'>" + this.lang.administration + "</a> > " + this.lang.notifications; - } - } - deleteNotification(notification: any) { let r = confirm(this.lang.deleteMsg); @@ -83,10 +98,108 @@ export class NotificationsAdministrationComponent implements OnInit { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; }, 0); + this.sidenav.close(); this.notify.success(this.lang.notificationDeleted); }, (err) => { this.notify.error(err.error.errors); }); } } + + loadCron() { + + this.hours = [{label:this.lang.eachHour,value:'*'}]; + this.minutes = [{label:this.lang.eachMinute,value:'*'}]; + + this.months = [ + {label:this.lang.eachMonth,value:'*'}, + {label:this.lang.january,value:"0"}, + {label:this.lang.february,value:"1"}, + {label:this.lang.march,value:"2"}, + {label:this.lang.april,value:"3"}, + {label:this.lang.may,value:"4"}, + {label:this.lang.june,value:"5"}, + {label:this.lang.july,value:"6"}, + {label:this.lang.august,value:"7"}, + {label:this.lang.september,value:"8"}, + {label:this.lang.october,value:"9"}, + {label:this.lang.november,value:"10"}, + {label:this.lang.december,value:"11"} + ] + + this.dom = [{label:this.lang.notUsed,value:'*'}]; + + this.dow = [ + {label:this.lang.eachDay,value:'*'}, + {label:this.lang.monday,value:"0"}, + {label:this.lang.thuesday,value:"1"}, + {label:this.lang.wednesday,value:"2"}, + {label:this.lang.thursday,value:"3"}, + {label:this.lang.friday,value:"4"}, + {label:this.lang.saturday,value:"5"}, + {label:this.lang.sunday,value:"6"} + ]; + + this.newCron = { + "m" : "", + "h" : "", + "dom" : "", + "mon" : "", + "cmd" : "", + "state": "normal" + }; + + for (var i = 0; i <= 23; i++) { + this.hours.push({label:i,value:String(i)}); + } + + for (var i = 0; i <= 59; i++) { + this.minutes.push({label:i,value:String(i)}); + } + + for (var i = 0; i <= 31; i++) { + this.dom.push({label:i,value:String(i)}); + } + + this.http.get(this.coreUrl + 'rest/notifications/schedule') + .subscribe((data: any) => { + this.crontab = data.crontab; + this.authorizedNotification = data.authorizedNotification; + }, (err) => { + this.notify.error(err.error.errors); + }); + + } + + saveCron() { + var description = this.newCron.cmd.split("/"); + this.newCron.description = description[description.length-1]; + this.crontab.push(this.newCron); + this.http.post(this.coreUrl + 'rest/notifications/schedule', this.crontab) + .subscribe((data: any) => { + this.newCron = { + "m" : "", + "h" : "", + "dom" : "", + "mon" : "", + "cmd" : "", + "description" : "", + "state": "normal" + } + this.notify.success(this.lang.notificationScheduleUpdated); + }, (err) => { + this.crontab.pop(); + this.notify.error(err.error.errors); + }); + } + + deleteCron(i:number) { + this.crontab[i].state = 'deleted'; + this.http.post(this.coreUrl + 'rest/notifications/schedule', this.crontab) + .subscribe((data: any) => { + this.notify.success(this.lang.notificationScheduleUpdated); + }, (err) => { + this.notify.error(err.error.errors); + }); + } } diff --git a/apps/maarch_entreprise/js/angular/lang/lang-en.ts b/apps/maarch_entreprise/js/angular/lang/lang-en.ts index e6cd2b7b089..3775eafabe2 100755 --- a/apps/maarch_entreprise/js/angular/lang/lang-en.ts +++ b/apps/maarch_entreprise/js/angular/lang/lang-en.ts @@ -14,7 +14,9 @@ export const LANG_EN = { "actions" : "Action(s)", "actionUpdated" : "Action updated", "activateAbsence" : "Activate absence", + "activateNotification" : "Activate notification", "active" : "Active", + "activeCron" : "Active cron", "add" : "Add", "address" : "Address", "addStatus" : "Add a status", @@ -25,10 +27,13 @@ export const LANG_EN = { "administrationServices" : "Administration services", "allActions" : "All actions", "application" : "Application", + "april" : "April", "archivalAgency" : "Archival agency", "archivalAgreement" : "Archival agreement", "associatedStatus" : "Associated status", + "attachment" : "Attachment", "attachments" : "Attachments", + "august" : "August", "authorize" : "Authorize", "autoLogoutAbsence" : "You are going to be automaticaly disconnected after your redirections", "available" : "available", @@ -67,6 +72,10 @@ export const LANG_EN = { "country" : "Country", "createScriptNotification" : "Create the script", "currentPsw" : "Current password", + "date" : "Date", + "day" : "Day", + "dayOfMonth" : "Day of month", + "december" : "December", "default" : "default", "defaultAction" : "Default action", "delete" : "Delete", @@ -83,6 +92,10 @@ export const LANG_EN = { "display" : "display", "documents" : "document(s)", "doNotModifyUnlessExpert" : "Do not edit this section unless you know what you are doing. Incorrect settings can cause the application to malfunction !", + "eachDay" : "Each day", + "eachHour" : "Each hour", + "eachMinute" : "Each minute", + "eachMonth" : "Each month", "email" : "Email", "emailSignatures" : "Email signatures", "entities" : "Entities", @@ -94,6 +107,7 @@ export const LANG_EN = { "entityUpdated" : "Entité updated", "entityReplacement" : "Entity replacement", "export_seda" : "Seda export", + "february" : "February", "fileplan" : "Fileplan", "filterBy" : "Filter by", "fingerprint" : "Digital fingerprint", @@ -101,6 +115,7 @@ export const LANG_EN = { "folder" : "Folder", "folders" : "Folders", "for" : "for", + "friday" : "Friday", "functionnalities" : "Functionnalities", "groupAdded" : "Group added", "groupCreation" : "Create group", @@ -112,6 +127,7 @@ export const LANG_EN = { "history" : "Historique", "historyBatch" : "Historique des batchs", "home" : "Accueil", + "hour" : "Hour", "id" : "Login", "imgRelated" : "Associated image", "inactive" : "Inactive", @@ -128,6 +144,9 @@ export const LANG_EN = { "isLinkedTo" : "Is linked to", "isSearchBasket" : "Only search basket", "isSytemAction" : "System action", + "january" : "January", + "july" : "July", + "june" : "June", "keyword" : "Keyword", "keywordHelp" : "Keyword help", "keywordHelpDesc_1" : "Identifier of logged user", @@ -150,10 +169,19 @@ export const LANG_EN = { "maarchApplication" : "Maarch App", "manageAbsences" : "Manage absences", "manageSignatures" : "Manage signatures", + "march" : "March", + "may" : "May", + "memberAllUsers" : "All users member", + "memberDiffTypeUsers" : "Diffusion type users member", + "memberUserDest" : "Dest user member", + "memberUsersCopy" : "Copy users member", "menus" : "Menus", + "minute" : "Minute", "modificationSaved" : "Modification has been saved", "module" : "Module", "modules" : "Modules", + "monday" : "Monday", + "month" : "Month", "moreOptions" : "More options", "move" : "Move", "myMenu" : "Personal menu", @@ -163,24 +191,30 @@ export const LANG_EN = { "newPsw" : "New password", "newSignature" : "New signature", "no" : "No", + "noAttachment" : "No attachment", "noReplacement" : "No replacement", "notes" : "Notes", - "NotificationAdded" : "Notification added", + "notificationAdded" : "Notification added", "notificationCreation" : "Notification creation", "notificationDeleted" : "Notification deleted", "NotificationDiffusionType" : "Diffusion type", "NotificationEnabled" : "Enabled", "NotificationEvent" : "Event", - "NotificationJoinDocument" : "Join document to notification", - "NotificationModel" : "Model", + "notificationJoinDocument" : "Join document to notification", + "notificationModel" : "Sendmail template", "notificationModification" : "Notification modification", "notifications" : "Notification(s)", "notificationSchedule" : "Notifications schedule", - "NotificationScheduleInfo" : "This part is used to define when notifications will be sent.\n\nIf you choose * from all the drop-down lists, the notification will be sent every minute 365 days a year.\n\nFrequency example :\n14 30 * * * [courrier] Nouveaux courriers à traiter : La notification sera envoyée tous les jours à 14h30\n9 30 * * Lundi [courrier] Nouveaux courriers à traiter : La notification sera envoyée tous les lundi à 9h30", - "NotificationScheduleUpdated" : "Schedule updated", + "NotificationScheduleInfo" : "As a reminder,\n\ncrontab format : [minute] [hour] [day of month] [month] [day of week]", + "notificationScheduleUpdated" : "Schedule updated", "notificationsSchedule" : "Notifications schedule", "NotificationToEnable" : "To enable", "notificationUpdated" : "Notification updated", + "notUsed" : "Not used", + "november" : "November", + "october" : "October", + "optional" : "Optional", + "others" : "Other(s)", "otherActions" : "Other(s) action(s)", "otherInformations" : "Other(s) information(s)", "otherParameters" : "Other(s) parameter(s)", @@ -219,14 +253,19 @@ export const LANG_EN = { "resId" : "Res Identifier", "resultPages" : "Rseult pages", "role" : "Role", + "saturday" : "Saturday", "save" : "Save", + "september" : "September", "sbSignatures" : "Signature Book Signatures", - "ScriptCreated" : "Script created", + "script" : "Script", + "scriptCreated" : "Script created", "search" : "Search", "searchEntities" : "Search entity", "secondaryEntity" : "Secondary entity", "selectAll" : "Select all", + "selectedDocumentStatus" : "Document status selected", "sendmail" : "Sendmail", + "sendTo" : "Send to", "shortLabel" : "Short label", "signAdded" : "Sign added", "signDeleted" : "Sign deleted", @@ -240,12 +279,18 @@ export const LANG_EN = { "statusModification" : "Status modification", "statusName" : "Status name", "statusUpdated" : "Status updated", + "string" : "String", + "sunday" : "Sunday", "suspend" : "Suspend", + "suspended" : "Suspended", + "suspendNotification" : "Suspend notification", "system" : "System", "systemParameters" : "System parameters", "tags" : "Tags", "templates" : "Templates", "thesaurus" : "Thesaurus", + "thuesday" : "Thuesday", + "thursday" : "Thursday", "to" : "to", "toDefault" : "default", "toEntities" : "To entities", @@ -259,6 +304,8 @@ export const LANG_EN = { "totalErrors" : "Errors element(s)", "totalProcessed" : "Processed element(s)", "toUsersEntities" : "To users in entities", + "triggerAction" : "Trigger action", + "triggerSystem" : "System trigger", "type" : "Type", "unlinkAction" : "Unlink action", "unlinkGroup" : "Unlink group", @@ -327,4 +374,5 @@ export const LANG_EN = { "tooltipPriorityDefault" : "Set this priority by default when saving a mail", "defaultPriority" : "Default priority", "chooseColor" : "Choose a color", + "wednesday" : "Wednesday" }; diff --git a/apps/maarch_entreprise/js/angular/lang/lang-fr.ts b/apps/maarch_entreprise/js/angular/lang/lang-fr.ts index 8276730073b..a0b8825e020 100755 --- a/apps/maarch_entreprise/js/angular/lang/lang-fr.ts +++ b/apps/maarch_entreprise/js/angular/lang/lang-fr.ts @@ -17,7 +17,9 @@ export const LANG_FR = { "actionUpdated" : "Action modifiée", "activateAbs" : "Activer l'absence", "activateAbsence" : "Activer l'absence", + "activateNotification" : "Activer la notification", "active" : "Actif", + "activeCron" : "Tâche(s) active(s)", "add" : "Ajouter", "address" : "Adresse", "addStatus" : "Ajouter un statut", @@ -28,10 +30,13 @@ export const LANG_FR = { "administrationServices" : "Droits d'administration", "allActions" : "Toutes les actions", "application" : "Application", + "april" : "Avril", "archivalAgency" : "Convention d'archivage", "archivalAgreement" : "Service d'archive", "associatedStatus" : "Statut associé", + "attachment" : "Pièce jointe", "attachments" : "Pièces jointes", + "august" : "Août", "authorize" : "Autoriser", "autoLogoutAbsence" : "Vous allez être automatiquement déconnecté après avoir défini vos redirections de bannettes", "available" : "disponible", @@ -75,6 +80,9 @@ export const LANG_FR = { "currentPsw" : "Mot de passe actuel", "dataOfMonth" : "Données du mois", "date" : "Date", + "day" : "Jour", + "dayOfMonth" : "Jour du mois", + "december" : "Décembre", "default" : "par défaut", "defaultAction" : "Action par défaut", "delete" : "Supprimer", @@ -91,6 +99,10 @@ export const LANG_FR = { "display" : "affichage", "documents" : "document(s)", "doNotModifyUnlessExpert" : "Ne pas modifier cette section à moins de savoir ce que vous faites. Un mauvais paramètrage peut entrainer des dysfonctionnements de l'application!", + "eachDay" : "Chaque jour", + "eachHour" : "Toutes les heures", + "eachMinute" : "Toutes les minutes", + "eachMonth" : "Chaque mois", "email" : "Courriel", "emailSignatures" : "Signatures de courriel", "entities" : "Entités", @@ -104,6 +116,7 @@ export const LANG_FR = { "entries" : "entrée(s)", "event" : "Événement", "export_seda" : "Export seda", + "february" : "Février", "fileplan" : "Plan de classement personnel", "filterBy" : "Filtrer", "filteredFrom" : "filtré sur un ensemble de", @@ -112,6 +125,7 @@ export const LANG_FR = { "folder" : "Dossier", "folders" : "Dossiers", "for" : "pour", + "friday" : "Vendredi", "functionnalities" : "Fonctionnalités", "groupAdded" : "Groupe ajouté", "groupCreation" : "Création d'un groupe", @@ -123,6 +137,7 @@ export const LANG_FR = { "history" : "Historique", "historyBatch" : "Historique des batchs", "home" : "Accueil", + "hour" : "Heure", "id" : "Identifiant", "imgRelated" : "Image associée", "inactive" : "Inactif", @@ -142,6 +157,9 @@ export const LANG_FR = { "isLinkedTo" : "Est associé à ", "isSearchBasket" : "Bannette de recherche uniquement", "isSytemAction" : "Action système", + "january" : "Janvier", + "july" : "Juillet", + "june" : "Juin", "keyword" : "Mot-clé", "keywordHelp" : "Aide sur les mots-clés", "keywordHelpDesc_1" : "Identifiant de l'utilisateur connecté", @@ -165,11 +183,20 @@ export const LANG_FR = { "maarchApplication" : "Application Maarch", "manageAbsences" : "Rediriger mes bannettes", "manageSignatures" : "Gérer les signatures", + "march" : "Mars", + "may" : "Mai", + "memberAllUsers" : "Tout les utilisateurs membres", + "memberDiffTypeUsers" : "Personnes membres du type de diffusion", + "memberUserDest" : "Utilisateur destinataire membre", + "memberUsersCopy" : "Utilisateur(s) en copie membre(s)", "menus" : "Menus", + "minute" : "Minute", "modificationSaved" : "Modification enregistrée", "module" : "Module", "modules" : "Modules", "moreOptions" : "Plus d'options", + "monday" : "Lundi", + "month" : "Mois", "move" : "Déplacer", "myMenu" : "Menu personnel", "myProfile" : "Mon profil", @@ -179,26 +206,32 @@ export const LANG_FR = { "newSignature" : "Nouvelle signature", "next" : "Suivant", "no" : "Non", + "noAttachment" : "Sans pièce jointe", "noRecord" : "Aucun élément", "noReplacement" : "Aucun remplacement", "noResult" : "Aucun résultat", "notes" : "Annotations", - "NotificationAdded" : "Notification ajoutée", + "notificationAdded" : "Notification ajoutée", "notificationCreation" : "Création d'une notification", "notificationDeleted" : "Notification supprimée", "NotificationDiffusionType" : "Type de diffusion", "NotificationEnabled" : "Activée", "NotificationEvent" : "Evènement", - "NotificationJoinDocument" : "Joindre le document à la notification", - "NotificationModel" : "Modèle", + "notificationJoinDocument" : "Joindre le document principal", + "notificationModel" : "Modèle du mail d'envoi", "notificationModification" : "Modification de la notification", "notifications" : "Notification(s)", "notificationSchedule" : "Planifier les notifications", - "NotificationScheduleInfo" : "Cette partie permet de définir quand seront envoyées les notifications.\n\nSi vous choisissez * dans toutes les listes déroulantes, la notification sera envoyée toutes les minutes 365 jours par an.\n\nExemple de fréquence :\n14 30 * * * [courrier] Nouveaux courriers à traiter : La notification sera envoyée tous les jours à 14h30\n9 30 * * Lundi [courrier] Nouveaux courriers à traiter : La notification sera envoyée tous les lundi à 9h30", - "NotificationScheduleUpdated" : "Planification mise à jour", + "NotificationScheduleInfo" : "Pour Rappel,\n\nformat de la crontab : [minute] [heure] [jour dans le mois] [mois] [jour de la semaine]", + "notificationScheduleUpdated" : "Tâche(s) planifié(s) mise à jour", "notificationsSchedule" : "Planification des notifications", "NotificationToEnable" : "Activer", "notificationUpdated" : "Notification mise à jour", + "notUsed" : "Non utilisé", + "november" : "Novembre", + "october" : "Octobre", + "optional" : "Optionnel", + "others" : "Autre(s)", "otherActions" : "Action(s) supplémentaire(s)", "otherInformations" : "Information(s) complémentaire(s)", "otherParameters" : "Autre(s) paramètre(s)", @@ -238,14 +271,19 @@ export const LANG_FR = { "resId" : "Identifiant GED", "resultPages" : "Pages de résultat", "role" : "Rôle", + "saturday" : "Samedi", "save" : "Enregistrer", + "september" : "Septembre", "sbSignatures" : "Signatures de parapheur", - "ScriptCreated" : "Script créé", + "script" : "Script", + "scriptCreated" : "Script créé", "search" : "Chercher", "searchEntities" : "Rechercher une entité", "secondaryEntity" : "Entitté secondaire", "selectAll" : "Sélectionner tout", + "selectedDocumentStatus" : "Statut du document à prendre en compte", "sendmail" : "Envoi de courriels", + "sendTo" : "Envoyer à ", "shortLabel" : "Libellé court", "signAdded" : "Signature ajoutée", "signDeleted" : "Signature supprimée", @@ -260,12 +298,17 @@ export const LANG_FR = { "statusName" : "Nom du statut", "statusUpdated" : "Statut mis à jour", "string" : "Chaine de caratère", + "sunday" : "Dimanche", "suspend" : "Suspendre", + "suspended" : "Suspendu", + "suspendNotification" : "Susprendre la notification", "system" : "Système", "systemParameters" : "paramètres système", "tags" : "Mots clés", "templates" : "Modèles de documents", "thesaurus" : "Thésaurus", + "thuesday" : "Mardi", + "thursday" : "Jeudi", "to" : "vers", "toDefault" : "par défaut", "toEntities" : "Vers les services", @@ -279,6 +322,8 @@ export const LANG_FR = { "totalErrors" : "Élément(s) en erreur", "totalProcessed" : "Élément(s) analysé(s)", "toUsersEntities" : "Vers les utilisateurs des services", + "triggerAction" : "Action Déclencheur", + "triggerSystem" : "Déclenchement système", "type" : "Type", "unlinkAction" : "Dissocier l'action", "unlinkGroup" : "Dissocier le groupe", @@ -354,5 +399,5 @@ export const LANG_FR = { "tooltipPriorityDefault" : "Positionner cette priorité par défaut lors de l'enregistrement d'un courrier", "defaultPriority" : "Priorité par défaut", "chooseColor" : "Choisissez une couleur", - + "wednesday" : "Mercredi" }; diff --git a/apps/maarch_entreprise/js/angularFunctions.js b/apps/maarch_entreprise/js/angularFunctions.js index 038f6d458d2..66eb6409d38 100755 --- a/apps/maarch_entreprise/js/angularFunctions.js +++ b/apps/maarch_entreprise/js/angularFunctions.js @@ -27,7 +27,7 @@ function triggerAngular(prodmode, locationToGo) { if (i === 2) { setTimeout(function () { head.appendChild(script); - }, 600); + }, 400); } else { head.appendChild(script); } diff --git a/core/Test/NotificationControllerTest.php b/core/Test/NotificationControllerTest.php index e225eb326d1..e46d7a10bf6 100644 --- a/core/Test/NotificationControllerTest.php +++ b/core/Test/NotificationControllerTest.php @@ -4,11 +4,12 @@ * See LICENCE.txt file at the root folder for more details. * This file is part of Maarch software. +* * @brief NotificationsControllerTest +* * @author dev <dev@maarch.org> * @ingroup core */ - use PHPUnit\Framework\TestCase; class NotificationControllerTest extends TestCase @@ -20,27 +21,27 @@ class NotificationControllerTest extends TestCase $NotificationController = new \Notification\controllers\NotificationController(); // CREATE - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - 'notification_id' => 'testcreatetu', - 'description' => 'description de la notification', - 'is_enabled' => 'Y', - 'event_id' => 'users%', - 'notification_mode' => 'EMAIL', - 'template_id' => 4, - 'diffusion_type' => 'group', - 'diffusion_properties' => ['ADMINISTRATEUR','ARCHIVISTE','DIRECTEUR'], - 'attachfor_type' => 'entity', - 'attachfor_properties' => ['COU','PJS'] + 'notification_id' => 'testcreatetu', + 'description' => 'description de la notification', + 'is_enabled' => 'Y', + 'event_id' => 'users%', + 'notification_mode' => 'EMAIL', + 'template_id' => 4, + 'diffusion_type' => 'group', + 'diffusion_properties' => ['ADMINISTRATEUR', 'ARCHIVISTE', 'DIRECTEUR'], + 'attachfor_type' => 'entity', + 'attachfor_properties' => ['COU', 'PJS'], ]; - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationController->create($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationController->create($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); - $this->assertInternalType("int", $responseBody->notification_sid); + $this->assertInternalType('int', $responseBody->notification_sid); self::$id = $responseBody->notification_sid; $this->assertSame('testcreatetu', $responseBody->notification_id); @@ -59,26 +60,25 @@ class NotificationControllerTest extends TestCase { //Fail Create 1 $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - 'notification_id' => '', - 'description' => 'description de la notification', - 'is_enabled' => 'Y', - 'event_id' => '', - 'notification_mode' => 'EMAIL', - 'template_id' => '', - 'rss_url_template' => 'http://localhost/maarch_entreprise', - 'diffusion_type' => 'user', + 'notification_id' => '', + 'description' => 'description de la notification', + 'is_enabled' => 'Y', + 'event_id' => '', + 'notification_mode' => 'EMAIL', + 'template_id' => '', + 'diffusion_type' => 'user', 'diffusion_properties' => 'superadmin', - 'attachfor_type' => 'zz', - 'attachfor_properties' => 'cc' + 'attachfor_type' => 'zz', + 'attachfor_properties' => 'cc', ]; - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationController->create($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationController->create($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('notification_id is empty', $responseBody->errors[0]); $this->assertSame('wrong format for template_id', $responseBody->errors[1]); @@ -88,25 +88,24 @@ class NotificationControllerTest extends TestCase { //Fail Create 2 $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - 'notification_id' => 'testcreatetu', - 'description' => 'description de la notification', - 'is_enabled' => 'Y', - 'event_id' => 'users%', - 'notification_mode' => 'EMAIL', - 'template_id' => 4, - 'rss_url_template' => 'http://localhost/maarch_entreprise', - 'diffusion_type' => 'user', + 'notification_id' => 'testcreatetu', + 'description' => 'description de la notification', + 'is_enabled' => 'Y', + 'event_id' => 'users%', + 'notification_mode' => 'EMAIL', + 'template_id' => 4, + 'diffusion_type' => 'user', 'diffusion_properties' => 'superadmin', - 'attachfor_type' => 'zz', - 'attachfor_properties' => 'cc' + 'attachfor_type' => 'zz', + 'attachfor_properties' => 'cc', ]; - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationController->create($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationController->create($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('identifiant déjà existant', $responseBody->errors); } @@ -114,10 +113,10 @@ class NotificationControllerTest extends TestCase { //READ $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => self::$id]); - $responseBody = json_decode((string)$response->getBody()); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); + $request = \Slim\Http\Request::createFromEnvironment($environment); + $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => self::$id]); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame(self::$id, $responseBody->notification->notification_sid); $this->assertSame('testcreatetu', $responseBody->notification->notification_id); @@ -132,10 +131,10 @@ class NotificationControllerTest extends TestCase public function testReadFail() { $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => 'test']); - $responseBody = json_decode((string)$response->getBody()); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); + $request = \Slim\Http\Request::createFromEnvironment($environment); + $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => 'test']); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('Id is not a numeric', $responseBody->errors); } @@ -143,20 +142,20 @@ class NotificationControllerTest extends TestCase { //I CANT READ BECAUSE NO EXIST $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => '9999999999']); - $responseBody = json_decode((string)$response->getBody()); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); + $request = \Slim\Http\Request::createFromEnvironment($environment); + $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => '9999999999']); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('Notification not found', $responseBody->errors); } public function testReadAll() { $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationController->get($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); + $request = \Slim\Http\Request::createFromEnvironment($environment); + $response = $NotificationController->get($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertNotNull($responseBody->notifications); } @@ -165,23 +164,23 @@ class NotificationControllerTest extends TestCase { // UPDATE $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'PUT']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'PUT']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - 'notification_id' => 'testcreatetu', - 'description' => 'nouvelle description', - 'is_enabled' => 'N', - 'event_id' => 'users%', - 'notification_mode' => 'EMAIL', - 'template_id' => 3, - 'diffusion_type' => 'group', - 'diffusion_properties' => ['ADMINISTRATEUR','ARCHIVISTE','DIRECTEUR'], - 'attachfor_type' => 'entity', - 'attachfor_properties' => ['COU','PJS'] + 'notification_id' => 'testcreatetu', + 'description' => 'nouvelle description', + 'is_enabled' => 'N', + 'event_id' => 'users%', + 'notification_mode' => 'EMAIL', + 'template_id' => 3, + 'diffusion_type' => 'group', + 'diffusion_properties' => ['ADMINISTRATEUR', 'ARCHIVISTE', 'DIRECTEUR'], + 'attachfor_type' => 'entity', + 'attachfor_properties' => ['COU', 'PJS'], ]; - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationController->update($fullRequest, new \Slim\Http\Response(), ['id' => self::$id]); - $responseBody = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationController->update($fullRequest, new \Slim\Http\Response(), ['id' => self::$id]); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame(self::$id, $responseBody->notification->notification_sid); $this->assertSame('testcreatetu', $responseBody->notification->notification_id); @@ -200,23 +199,23 @@ class NotificationControllerTest extends TestCase { // UPDATE $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'PUT']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'PUT']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - 'notification_id' => 'testcreatetu', - 'description' => '', - 'is_enabled' => 'N', - 'event_id' => 'users%', - 'notification_mode' => 'EMAIL', - 'template_id' => '', - 'diffusion_type' => 'group', - 'diffusion_properties' => ['ADMINISTRATEUR','ARCHIVISTE','DIRECTEUR'], - 'attachfor_type' => 'entity', - 'attachfor_properties' => ['COU','PJS'] + 'notification_id' => 'testcreatetu', + 'description' => '', + 'is_enabled' => 'N', + 'event_id' => 'users%', + 'notification_mode' => 'EMAIL', + 'template_id' => '', + 'diffusion_type' => 'group', + 'diffusion_properties' => ['ADMINISTRATEUR', 'ARCHIVISTE', 'DIRECTEUR'], + 'attachfor_type' => 'entity', + 'attachfor_properties' => ['COU', 'PJS'], ]; - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationController->update($fullRequest, new \Slim\Http\Response(), ['id' => self::$id]); - $responseBody = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationController->update($fullRequest, new \Slim\Http\Response(), ['id' => self::$id]); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('wrong format for description', $responseBody->errors[0]); $this->assertSame('wrong format for template_id', $responseBody->errors[1]); @@ -226,23 +225,23 @@ class NotificationControllerTest extends TestCase { // UPDATE $NotificationController = new \Notification\controllers\NotificationController(); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'PUT']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'PUT']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - 'notification_id' => 'testcreatetu', - 'description' => 'description', - 'is_enabled' => 'N', - 'event_id' => 'users%', - 'notification_mode' => 'EMAIL', - 'template_id' => 4, - 'diffusion_type' => 'group', - 'diffusion_properties' => ['ADMINISTRATEUR','ARCHIVISTE','DIRECTEUR'], - 'attachfor_type' => 'entity', - 'attachfor_properties' => ['COU','PJS'] + 'notification_id' => 'testcreatetu', + 'description' => 'description', + 'is_enabled' => 'N', + 'event_id' => 'users%', + 'notification_mode' => 'EMAIL', + 'template_id' => 4, + 'diffusion_type' => 'group', + 'diffusion_properties' => ['ADMINISTRATEUR', 'ARCHIVISTE', 'DIRECTEUR'], + 'attachfor_type' => 'entity', + 'attachfor_properties' => ['COU', 'PJS'], ]; - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationController->update($fullRequest, new \Slim\Http\Response(), ['id' => 'fail']); - $responseBody = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationController->update($fullRequest, new \Slim\Http\Response(), ['id' => 'fail']); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('notification_sid is not a numeric', $responseBody->errors[0]); $this->assertSame('notification does not exists', $responseBody->errors[1]); @@ -253,24 +252,24 @@ class NotificationControllerTest extends TestCase $NotificationController = new \Notification\controllers\NotificationController(); // DELETE - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'DELETE']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'DELETE']); + $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationController->delete($request, new \Slim\Http\Response(), ['id' => self::$id]); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationController->delete($request, new \Slim\Http\Response(), ['id' => self::$id]); + $responseBody = json_decode((string) $response->getBody()); $this->assertNotNull($responseBody->notifications[0]); - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => self::$id]); - $responseBody = json_decode((string)$response->getBody()); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); + $request = \Slim\Http\Request::createFromEnvironment($environment); + $response = $NotificationController->getBySid($request, new \Slim\Http\Response(), ['id' => self::$id]); + $responseBody = json_decode((string) $response->getBody()); $this->assertNull($responseBody->notifications[0]); // FAIL DELETE - $response = $NotificationController->delete($request, new \Slim\Http\Response(), ['id' => 'gaz']); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationController->delete($request, new \Slim\Http\Response(), ['id' => 'gaz']); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame('Id is not a numeric', $responseBody->errors); } @@ -278,12 +277,12 @@ class NotificationControllerTest extends TestCase public function testGetInitNotification() { // InitAction - $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); + $request = \Slim\Http\Request::createFromEnvironment($environment); $NotificationController = new \Notification\controllers\NotificationController(); - $response = $NotificationController->initNotification($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationController->initNotification($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertNotNull($responseBody->notification->data->event); $this->assertNotNull($responseBody->notification->data->template); diff --git a/core/Test/NotificationScheduleControllerTest.php b/core/Test/NotificationScheduleControllerTest.php index 94cc4abb038..bba1ff30b9d 100644 --- a/core/Test/NotificationScheduleControllerTest.php +++ b/core/Test/NotificationScheduleControllerTest.php @@ -4,11 +4,12 @@ * See LICENCE.txt file at the root folder for more details. * This file is part of Maarch software. +* * @brief NotificationsScheduleControllerTest +* * @author dev <dev@maarch.org> * @ingroup core */ - use PHPUnit\Framework\TestCase; class NotificationScheduleControllerTest extends TestCase @@ -21,33 +22,32 @@ class NotificationScheduleControllerTest extends TestCase // CREATE FAIL $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - "notification_sid" => "gaz", - "notification_id" => "", + 'notification_sid' => 'gaz', + 'notification_id' => '', ]; $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->createScriptNotification($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); - - $this->assertSame("notification_sid is not a numeric", $responseBody->errors[0]); - $this->assertSame("one of arguments is empty", $responseBody->errors[1]); + $response = $NotificationScheduleController->createScriptNotification($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); + $this->assertSame('notification_sid is not a numeric', $responseBody->errors[0]); + $this->assertSame('one of arguments is empty', $responseBody->errors[1]); // CREATE $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = [ - "notification_sid" => 1, - "notification_id" => "USERS", + 'notification_sid' => 1, + 'notification_id' => 'USERS', ]; $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->createScriptNotification($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->createScriptNotification($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame(true, $responseBody); } @@ -57,55 +57,55 @@ class NotificationScheduleControllerTest extends TestCase $NotificationScheduleController = new \Notification\controllers\NotificationScheduleController(); $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); // CREATE FAIL $aArgs = []; $aArgs = $responseBody->crontab; - $corePath = dirname(__FILE__, 3) . '/'; + $corePath = dirname(__FILE__, 3).'/'; $newCrontab = [ - "m" => 12, - "h" => 23, - "dom" => "", - "mon" => "*", - "dow" => "*", - "cmd" => $corePath . "modules/notifications/batch/scripts/notification_testtu.sh", - "state" => "new", + 'm' => 12, + 'h' => 23, + 'dom' => '', + 'mon' => '*', + 'dow' => '*', + 'cmd' => $corePath.'modules/notifications/batch/scripts/notification_testtu.sh', + 'state' => 'normal', ]; array_push($aArgs, $newCrontab); - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); - $responseBodyFail = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); + $responseBodyFail = json_decode((string) $response->getBody()); - $this->assertSame("dom is empty", $responseBodyFail->errors[0]); + $this->assertSame('wrong format for dom', $responseBodyFail->errors[0]); // CREATE $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = []; $aArgs = $responseBody->crontab; - $corePath = dirname(__FILE__, 3) . '/'; + $corePath = dirname(__FILE__, 3).'/'; $newCrontab = [ - "m" => 12, - "h" => 23, - "dom" => "*", - "mon" => "*", - "dow" => "*", - "cmd" => $corePath . "modules/notifications/batch/scripts/notification_testtu.sh", - "state" => "new", + 'm' => 12, + 'h' => 23, + 'dom' => '*', + 'mon' => '*', + 'dow' => '*', + 'cmd' => $corePath.'modules/notifications/batch/scripts/notification_testtu.sh', + 'state' => 'normal', ]; array_push($aArgs, $newCrontab); - $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); - $responseBodyCreate = json_decode((string)$response->getBody()); + $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); + $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); + $responseBodyCreate = json_decode((string) $response->getBody()); $this->assertSame(true, $responseBodyCreate); } @@ -113,14 +113,14 @@ class NotificationScheduleControllerTest extends TestCase public function testReadAll() { $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); $NotificationScheduleController = new \Notification\controllers\NotificationScheduleController(); - $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertInternalType('array', $responseBody->crontab); - $this->assertInternalType('object', $responseBody->authorizedNotification); + $this->assertInternalType('array', $responseBody->authorizedNotification); $this->assertNotNull($responseBody->authorizedNotification); $this->assertNotNull($responseBody->crontab); } @@ -129,45 +129,45 @@ class NotificationScheduleControllerTest extends TestCase { $NotificationScheduleController = new \Notification\controllers\NotificationScheduleController(); $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); // UPDATE $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); $aArgs = []; $aArgs = $responseBody->crontab; - $corePath = dirname(__FILE__, 3) . '/'; + $corePath = dirname(__FILE__, 3).'/'; - $aArgs[count($aArgs)-1] = [ - "m" => 35, - "h" => 22, - "dom" => "*", - "mon" => "*", - "dow" => "*", - "cmd" => $corePath . "modules/notifications/batch/scripts/notification_testtu.sh", - "state" => "normal", + $aArgs[count($aArgs) - 1] = [ + 'm' => 35, + 'h' => 22, + 'dom' => '*', + 'mon' => '*', + 'dow' => '*', + 'cmd' => $corePath.'modules/notifications/batch/scripts/notification_testtu.sh', + 'state' => 'normal', ]; $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame(true, $responseBody); $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); - $this->assertSame('35', $responseBody->crontab[count($responseBody->crontab)-1]->m); - $this->assertSame('22', $responseBody->crontab[count($responseBody->crontab)-1]->h); + $this->assertSame('35', $responseBody->crontab[count($responseBody->crontab) - 1]->m); + $this->assertSame('22', $responseBody->crontab[count($responseBody->crontab) - 1]->h); } public function testDelete() @@ -176,43 +176,43 @@ class NotificationScheduleControllerTest extends TestCase $NotificationScheduleController = new \Notification\controllers\NotificationScheduleController(); $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); - $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->get($request, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $aArgs = []; $aArgs = $responseBody->crontab; foreach ($aArgs as $id => $value) { - if ($value->cmd == dirname(__FILE__, 3) . '/' . "modules/notifications/batch/scripts/notification_testtu.sh") { - $aArgs[$id]->state = "hidden"; + if ($value->cmd == dirname(__FILE__, 3).'/'.'modules/notifications/batch/scripts/notification_testtu.sh') { + $aArgs[$id]->state = 'hidden'; } } $environment = \Slim\Http\Environment::mock(['REQUEST_METHOD' => 'POST']); - $request = \Slim\Http\Request::createFromEnvironment($environment); + $request = \Slim\Http\Request::createFromEnvironment($environment); $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); - $responseBodyFail = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); + $responseBodyFail = json_decode((string) $response->getBody()); - $this->assertSame("Problem with crontab", $responseBodyFail->errors); + $this->assertSame('Problem with crontab', $responseBodyFail->errors); // DELETE $aArgs = []; $aArgs = $responseBody->crontab; foreach ($aArgs as $id => $value) { - if ($value->cmd == dirname(__FILE__, 3) . '/' . "modules/notifications/batch/scripts/notification_testtu.sh") { - $aArgs[$id]->state = "deleted"; + if ($value->cmd == dirname(__FILE__, 3).'/'.'modules/notifications/batch/scripts/notification_testtu.sh') { + $aArgs[$id]->state = 'deleted'; } } $fullRequest = \httpRequestCustom::addContentInBody($aArgs, $request); - $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); - $responseBody = json_decode((string)$response->getBody()); + $response = $NotificationScheduleController->create($fullRequest, new \Slim\Http\Response()); + $responseBody = json_decode((string) $response->getBody()); $this->assertSame(true, $responseBody); } diff --git a/modules/notifications/batch/basket_event_stack.php b/modules/notifications/batch/basket_event_stack.php index 6b8f4c4b482..912d3e48bd2 100755 --- a/modules/notifications/batch/basket_event_stack.php +++ b/modules/notifications/batch/basket_event_stack.php @@ -14,287 +14,291 @@ /* begin */ // load the config and prepare to process -include('load_basket_event_stack.php'); +include 'load_basket_event_stack.php'; $state = 'LOAD_NOTIFICATIONS'; -while ($state <> 'END') { +while ($state != 'END') { if (isset($logger)) { - $logger->write('STATE:' . $state, 'INFO'); + $logger->write('STATE:'.$state, 'INFO'); } switch ($state) { - - /**********************************************************************/ - /* LOAD_NOTIFICATIONS */ - /* Load notification defsidentified with notification id */ - /**********************************************************************/ - case 'LOAD_NOTIFICATIONS': - $logger->write("Loading configuration for notification id " . $notificationId, 'INFO'); - $notification = $notifications_controler->getByNotificationId($notificationId); - if ($notification === false) { - Bt_exitBatch(1, "Notification '".$notificationId."' not found"); - } - if ($notification->is_enabled === 'N') { - Bt_exitBatch(100, "Notification '".$notificationId."' is disabled"); - } - $state = 'ADD_EVENTS'; - break; - - /**********************************************************************/ - /* LOAD_EVENTS */ - /* Checking if the stack has notifications to proceed */ - /**********************************************************************/ - case 'ADD_EVENTS': - $db = new Database(); - $secCtrl = new SecurityControler(); - $entities = new entities(); + /**********************************************************************/ + /* LOAD_NOTIFICATIONS */ + /* Load notification defsidentified with notification id */ + /**********************************************************************/ + case 'LOAD_NOTIFICATIONS': + $logger->write('Loading configuration for notification id '.$notificationId, 'INFO'); + $notification = $notifications_controler->getByNotificationId($notificationId); + if ($notification === false) { + Bt_exitBatch(1, "Notification '".$notificationId."' not found"); + } + if ($notification->is_enabled === 'N') { + Bt_exitBatch(100, "Notification '".$notificationId."' is disabled"); + } + //Attach Mode ? + if (!empty($notification->attachfor_type) || $notification->attachfor_type != null) { + $attachMode = true; + $logger->write('The document will be attached for each recipient', 'INFO'); + } else { + $attachMode = false; + } + $state = 'ADD_EVENTS'; + break; - $stmt = $db->query("SELECT basket_id, except_notif, basket_clause FROM baskets WHERE flag_notif = 'Y'"); + /**********************************************************************/ + /* LOAD_EVENTS */ + /* Checking if the stack has notifications to proceed */ + /**********************************************************************/ + case 'ADD_EVENTS': + $db = new Database(); + $secCtrl = new SecurityControler(); + $entities = new entities(); - while ($line = $stmt->fetchObject()) { - $logger->write("BASKET: " . $line->basket_id . " in progess ...", 'INFO'); - $exceptUsers[$line->basket_id] = array(); - if ($line->except_notif != '' || $line->except_notif != null) { - $arrayExceptNotif = explode(',', $line->except_notif); - $exceptUsers[$line->basket_id]=$arrayExceptNotif; - } - $stmt2 = $db->query("SELECT group_id FROM groupbasket WHERE basket_id = ?", array($line->basket_id)); + $stmt = $db->query("SELECT basket_id, except_notif, basket_clause FROM baskets WHERE flag_notif = 'Y'"); - $u=1; - while ($line2 = $stmt2->fetchObject()) { - if ($notification->diffusion_type == "groups"){ - $recipients = array(); - $recipients = $diffusion_type_controler->getRecipients($notification, ''); - $aRecipients = []; - foreach ($recipients as $itemRecipient) { - array_push($aRecipients, $itemRecipient->user_id); - } - if(empty($aRecipients)){ - $aRecipients = "0=1"; - } - $stmt3 = $db->query("SELECT usergroup_content.user_id,users.status FROM usergroup_content, users WHERE group_id = ? and users.status in ('OK') and usergroup_content.user_id=users.user_id and users.user_id in (?)", array($line2->group_id, $aRecipients)); - } else { - $stmt3 = $db->query("SELECT usergroup_content.user_id,users.status FROM usergroup_content, users WHERE group_id = ? and users.status in ('OK') and usergroup_content.user_id=users.user_id",array($line2->group_id)); + while ($line = $stmt->fetchObject()) { + $logger->write('BASKET: '.$line->basket_id.' in progess ...', 'INFO'); + $exceptUsers[$line->basket_id] = array(); + if ($line->except_notif != '' || $line->except_notif != null) { + $arrayExceptNotif = explode(',', $line->except_notif); + $exceptUsers[$line->basket_id] = $arrayExceptNotif; } + $stmt2 = $db->query('SELECT group_id FROM groupbasket WHERE basket_id = ?', array($line->basket_id)); - $baskets_notif = array(); - $rowCount3 = $stmt3->rowCount(); - $logger->write("GROUP: " . $line2->group_id . " ... " . $rowCount3 . " user(s) to notify", 'INFO'); - $z=1; - while ($line3 = $stmt3->fetchObject()) { - $whereClause = $secCtrl->process_security_where_clause($line->basket_clause, $line3->user_id); - $whereClause = $entities->process_where_clause($whereClause, $line3->user_id); - $user_id = $line3->user_id; - if ($line3->status == 'ABS') { - $query = "SELECT new_user FROM user_abs WHERE user_abs = ?"; - $testStmt = $db->query($query, array($line3->user_id)); - $abs_user = $testStmt->fetchObject(); - $user_id = $abs_user->new_user; + $u = 1; + while ($line2 = $stmt2->fetchObject()) { + if ($notification->diffusion_type == 'groups') { + $recipients = array(); + $recipients = $diffusion_type_controler->getRecipients($notification, ''); + $aRecipients = []; + foreach ($recipients as $itemRecipient) { + array_push($aRecipients, $itemRecipient->user_id); + } + if (empty($aRecipients)) { + $aRecipients = '0=1'; + } + $stmt3 = $db->query("SELECT usergroup_content.user_id,users.status FROM usergroup_content, users WHERE group_id = ? and users.status in ('OK') and usergroup_content.user_id=users.user_id and users.user_id in (?)", array($line2->group_id, $aRecipients)); + } else { + $stmt3 = $db->query("SELECT usergroup_content.user_id,users.status FROM usergroup_content, users WHERE group_id = ? and users.status in ('OK') and usergroup_content.user_id=users.user_id", array($line2->group_id)); } - - $stmt4 = $db->query("SELECT res_id FROM res_view_letterbox ".$whereClause); - if(!empty($stmt4)){ - $userNbDoc = $stmt4->rowCount(); - $logger->write($userNbDoc . " document(s) to process for ".$line3->user_id, 'INFO'); - $i=1; - $info = "Notification [".$line->basket_id."] pour ".$line3->user_id; - $stmt6 = $db->query("SELECT record_id FROM notif_event_stack WHERE event_info = ? and user_id = ?", array($info, $line3->user_id)); - $aRecordId = []; - while($line6 = $stmt6->fetchObject()){ - $aRecordId[$line6->record_id] = $line6->record_id; + + $baskets_notif = array(); + $rowCount3 = $stmt3->rowCount(); + $logger->write('GROUP: '.$line2->group_id.' ... '.$rowCount3.' user(s) to notify', 'INFO'); + $z = 1; + while ($line3 = $stmt3->fetchObject()) { + $whereClause = $secCtrl->process_security_where_clause($line->basket_clause, $line3->user_id); + $whereClause = $entities->process_where_clause($whereClause, $line3->user_id); + $user_id = $line3->user_id; + if ($line3->status == 'ABS') { + $query = 'SELECT new_user FROM user_abs WHERE user_abs = ?'; + $testStmt = $db->query($query, array($line3->user_id)); + $abs_user = $testStmt->fetchObject(); + $user_id = $abs_user->new_user; } - $queryValues = ""; - while ($line4 = $stmt4->fetchObject()) { - echo "DOCUMENT " . $i . "/" . $userNbDoc . " for USER " . $z . "/" . $rowCount3." and GROUP ".$u."/".$stmt2->rowCount()."\n"; - if (empty($aRecordId[$line4->res_id])) { - $queryValues .= "('res_letterbox','500','".$line4->res_id."','".$user_id."','".$info."',CURRENT_DATE),"; - preg_match_all('#\[(\w+)]#', $info, $result); - $basket_id = $result[1]; - if (!in_array($basket_id[0], $baskets_notif)) { - $baskets_notif[] = $basket_id[0]; + + $stmt4 = $db->query('SELECT res_id FROM res_view_letterbox '.$whereClause); + if (!empty($stmt4)) { + $userNbDoc = $stmt4->rowCount(); + $logger->write($userNbDoc.' document(s) to process for '.$line3->user_id, 'INFO'); + $i = 1; + $info = 'Notification ['.$line->basket_id.'] pour '.$line3->user_id; + $stmt6 = $db->query('SELECT record_id FROM notif_event_stack WHERE event_info = ? and user_id = ?', array($info, $line3->user_id)); + $aRecordId = []; + while ($line6 = $stmt6->fetchObject()) { + $aRecordId[$line6->record_id] = $line6->record_id; + } + $queryValues = ''; + while ($line4 = $stmt4->fetchObject()) { + echo 'DOCUMENT '.$i.'/'.$userNbDoc.' for USER '.$z.'/'.$rowCount3.' and GROUP '.$u.'/'.$stmt2->rowCount()."\n"; + if (empty($aRecordId[$line4->res_id])) { + $queryValues .= "('res_letterbox','500','".$line4->res_id."','".$user_id."','".$info."',CURRENT_DATE),"; + preg_match_all('#\[(\w+)]#', $info, $result); + $basket_id = $result[1]; + if (!in_array($basket_id[0], $baskets_notif)) { + $baskets_notif[] = $basket_id[0]; + } } + ++$i; + } + if (!empty($queryValues)) { + $db->query('INSERT INTO notif_event_stack (table_name, notification_sid, record_id, user_id, event_info, event_date) VALUES '.substr($queryValues, 0, -1)); } - $i++; - } - if(!empty($queryValues)){ - $db->query("INSERT INTO notif_event_stack (table_name, notification_sid, record_id, user_id, event_info, event_date) VALUES " . substr($queryValues, 0, -1)); } + ++$z; } - $z++; + ++$u; } - $u++; } - } - $logger->write("Scanning events for notification sid " . $notification->notification_sid, 'INFO'); - $events = $events_controler->getEventsByNotificationSid('500'); - $totalEventsToProcess = count($events); - $currentEvent = 0; - if ($totalEventsToProcess === 0) { - Bt_exitBatch(0, 'No event to process'); - } - $logger->write($totalEventsToProcess . ' event(s) to scan', 'INFO'); - $tmpNotifs = array(); - $state = 'SCAN_EVENT'; - break; - - /**********************************************************************/ - /* MERGE_EVENT */ - /* Process event stack to get recipients */ - /**********************************************************************/ - case 'SCAN_EVENT': - $i = 1; - - foreach ($events as $event) { - $logger->write("scanning EVENT : " .$i."/".$totalEventsToProcess." (BASKET => ".$basket_id[0].", DOCUMENT => ".$res_id.", RECIPIENT => ".$user_id.")", 'INFO'); - preg_match_all('#\[(\w+)]#', $event->event_info, $result); - $basket_id = $result[1]; - //$logger->write("Basket => " .$basket_id[0], 'INFO'); - - // Diffusion type specific res_id - $res_id = false; - if ($event->table_name == $coll_table || $event->table_name == $coll_view) { - $res_id = $event->record_id; - } else { - $res_id = $diffusion_type_controler->getResId($notification, $event); + $logger->write('Scanning events for notification sid '.$notification->notification_sid, 'INFO'); + $events = $events_controler->getEventsByNotificationSid('500'); + $totalEventsToProcess = count($events); + $currentEvent = 0; + if ($totalEventsToProcess === 0) { + Bt_exitBatch(0, 'No event to process'); } - $event->res_id = $res_id; - - //$logger->write('Document => ' . $res_id, 'INFO'); - $user_id = $event->user_id; - //$logger->write('Recipient => ' . $user_id, 'INFO'); + $logger->write($totalEventsToProcess.' event(s) to scan', 'INFO'); + $tmpNotifs = array(); + $state = 'SCAN_EVENT'; + break; + + /**********************************************************************/ + /* MERGE_EVENT */ + /* Process event stack to get recipients */ + /**********************************************************************/ + case 'SCAN_EVENT': + $i = 1; + + foreach ($events as $event) { + $logger->write('scanning EVENT : '.$i.'/'.$totalEventsToProcess.' (BASKET => '.$basket_id[0].', DOCUMENT => '.$res_id.', RECIPIENT => '.$user_id.')', 'INFO'); + preg_match_all('#\[(\w+)]#', $event->event_info, $result); + $basket_id = $result[1]; + //$logger->write("Basket => " .$basket_id[0], 'INFO'); + + // Diffusion type specific res_id + $res_id = false; + if ($event->table_name == $coll_table || $event->table_name == $coll_view) { + $res_id = $event->record_id; + } else { + $res_id = $diffusion_type_controler->getResId($notification, $event); + } + $event->res_id = $res_id; + + //$logger->write('Document => ' . $res_id, 'INFO'); + $user_id = $event->user_id; + //$logger->write('Recipient => ' . $user_id, 'INFO'); + + if (!isset($tmpNotifs[$user_id])) { + $query = 'SELECT * FROM users WHERE user_id = ?'; + $arrayPDO = array($user_id); + $stmt = $db->query($query, $arrayPDO); + $tmpNotifs[$user_id]['recipient'] = $stmt->fetchObject(); + //$tmpNotifs[$user_id]['recipient'] = $user_id; + } + preg_match_all('#\[(\w+)]#', $event->event_info, $result); + $basket_id = $result[1]; + $tmpNotifs[$user_id]['baskets'][$basket_id[0]]['events'][] = $event; - if (!isset($tmpNotifs[$user_id])) { - $query = "SELECT * FROM users WHERE user_id = ?"; - $arrayPDO = array($user_id); - $stmt = $db->query($query, $arrayPDO); - $tmpNotifs[$user_id]['recipient'] = $stmt->fetchObject(); - //$tmpNotifs[$user_id]['recipient'] = $user_id; - $tmpNotifs[$user_id]['attach'] = $diffusion_type_controler->getAttachFor($notification, $user_id); - //$logger->write('Checking if attachment required for ' . $user_id . ': ' . $tmpNotifs[$user_id]['attach'], 'INFO'); + ++$i; } - preg_match_all('#\[(\w+)]#', $event->event_info, $result); - $basket_id = $result[1]; - $tmpNotifs[$user_id]['baskets'][$basket_id[0]]['events'][] = $event; + $totalNotificationsToProcess = count($tmpNotifs); + $logger->write($totalNotificationsToProcess.' notifications to process', 'INFO'); + + /**********************************************************************/ + /* FILL_EMAIL_STACK */ + /* Merge template and fill notif_email_stack */ + /**********************************************************************/ + $logger->write('STATE:MERGE NOTIF', 'INFO'); + $i = 1; + foreach ($tmpNotifs as $user_id => $tmpNotif) { + foreach ($tmpNotif['baskets'] as $key => $basket_list) { + $basketId = $key; + $stmt6 = $db->query('SELECT basket_name FROM baskets WHERE basket_id = ?', array($key)); + $line6 = $stmt6->fetchObject(); + $subject = $line6->basket_name; + + // Merge template with data and style + $logger->write('generate e-mail '.$i.'/'.$totalNotificationsToProcess.' (TEMPLATE =>'.$notification->template_id.', SUBJECT => '.$subject.', RECIPIENT => '.$user_id.', DOCUMENT(S) => '.count($basket_list['events']), 'INFO'); - $i++; - } - $totalNotificationsToProcess = count($tmpNotifs); - $logger->write($totalNotificationsToProcess .' notifications to process', 'INFO'); + //$logger->write('Merging template #' . $notification->template_id + // . ' to basket '.$subject.' for user ' . $user_id . ' ('.count($basket_list['events']).' documents)', 'INFO'); - /**********************************************************************/ - /* FILL_EMAIL_STACK */ - /* Merge template and fill notif_email_stack */ - /**********************************************************************/ - $logger->write('STATE:MERGE NOTIF', 'INFO'); - $i=1; - foreach ($tmpNotifs as $user_id => $tmpNotif) { - foreach ($tmpNotif['baskets'] as $key => $basket_list) { - $basketId = $key; - $stmt6 = $db->query("SELECT basket_name FROM baskets WHERE basket_id = ?", array($key)); - $line6 = $stmt6->fetchObject(); - $subject = $line6->basket_name; - - // Merge template with data and style - $logger->write('generate e-mail '.$i.'/'.$totalNotificationsToProcess.' (TEMPLATE =>' . $notification->template_id .', SUBJECT => '.$subject.', RECIPIENT => '.$user_id.', DOCUMENT(S) => '.count($basket_list['events']), 'INFO'); + $params = array( + 'recipient' => $tmpNotif['recipient'], + 'events' => $basket_list['events'], + 'notification' => $notification, + 'maarchUrl' => $maarchUrl, + 'maarchApps' => $maarchApps, + 'coll_id' => $coll_id, + 'res_table' => $coll_table, + 'res_view' => $coll_view, + ); + $html = $templates_controler->merge($notification->template_id, $params, 'content'); - //$logger->write('Merging template #' . $notification->template_id - // . ' to basket '.$subject.' for user ' . $user_id . ' ('.count($basket_list['events']).' documents)', 'INFO'); - - $params = array( - 'recipient' => $tmpNotif['recipient'], - 'events' => $basket_list['events'], - 'notification' => $notification, - 'maarchUrl' => $maarchUrl, - 'maarchApps' => $maarchApps, - 'coll_id' => $coll_id, - 'res_table' => $coll_table, - 'res_view' => $coll_view - ); - $html = $templates_controler->merge($notification->template_id, $params, 'content'); - - if (strlen($html) === 0) { - foreach ($tmpNotif['events'] as $event) { - $events_controler->commitEvent($event->event_stack_sid, "FAILED: Error when merging template"); + if (strlen($html) === 0) { + foreach ($tmpNotif['events'] as $event) { + $events_controler->commitEvent($event->event_stack_sid, 'FAILED: Error when merging template'); + } + Bt_exitBatch(8, 'Could not merge template with the data'); } - Bt_exitBatch(8, "Could not merge template with the data"); - } - - // Prepare e-mail for stack - $sender = (string)$mailerParams->mailfrom; - $recipient_mail = $tmpNotif['recipient']->mail; - //$subject = $notification->description; - $html = $func->protect_string_db($html, '', 'no'); - $html = str_replace('&', '&', $html); - $html = str_replace('&', '#and#', $html); - - // Attachments - $attachments = array(); - if ($tmpNotif['attach']) { - $logger->write('Adding attachments', 'INFO'); - foreach ($basket_list['events'] as $event) { - // Check if event is related to document in collection - if ($event->res_id != '') { - $query = "SELECT " - . "ds.path_template ," - . "mlb.path, " - . "mlb.filename " - . "FROM ".$coll_view." mlb LEFT JOIN docservers ds ON mlb.docserver_id = ds.docserver_id " - . "WHERE mlb.res_id = ?"; - $stmt = Bt_doQuery($db, $query, array($event->res_id)); - $path_parts = $stmt->fetchObject(); - $path = $path_parts->path_template . str_replace('#', '/', $path_parts->path) . $path_parts->filename; - $path = str_replace('//', '/', $path); - $path = str_replace('\\', '/', $path); - $attachments[] = $path; + // Prepare e-mail for stack + $sender = (string) $mailerParams->mailfrom; + $recipient_mail = $tmpNotif['recipient']->mail; + + //$subject = $notification->description; + $html = $func->protect_string_db($html, '', 'no'); + $html = str_replace('&', '&', $html); + $html = str_replace('&', '#and#', $html); + + // Attachments + $attachments = array(); + if ($attachMode) { + $logger->write('Adding attachments', 'INFO'); + foreach ($basket_list['events'] as $event) { + // Check if event is related to document in collection + if ($event->res_id != '') { + $query = 'SELECT ' + .'ds.path_template ,' + .'mlb.path, ' + .'mlb.filename ' + .'FROM '.$coll_view.' mlb LEFT JOIN docservers ds ON mlb.docserver_id = ds.docserver_id ' + .'WHERE mlb.res_id = ?'; + $stmt = Bt_doQuery($db, $query, array($event->res_id)); + $path_parts = $stmt->fetchObject(); + $path = $path_parts->path_template.str_replace('#', '/', $path_parts->path).$path_parts->filename; + $path = str_replace('//', '/', $path); + $path = str_replace('\\', '/', $path); + $attachments[] = $path; + } } + $logger->write(count($attachments).' attachment(s) added', 'INFO'); } - $logger->write(count($attachments) . ' attachment(s) added', 'INFO'); - } - if (in_array($user_id, $exceptUsers[$basketId])) { - $logger->write('Notification disabled for '.$user_id, 'WARNING'); - } else { - $logger->write('... adding e-mail to email stack', 'INFO'); - if ($_SESSION['config']['databasetype'] == 'ORACLE') { - $query = "DECLARE - vString notif_email_stack.html_body%type; - BEGIN - vString := '" . $html ."'; - INSERT INTO " . _NOTIF_EMAIL_STACK_TABLE_NAME . " - (sender, recipient, subject, html_body, charset, attachments, module) - VALUES (?, ?, ?, vString, ?, '".implode(',', $attachments)."', 'notifications'); - END;"; - $arrayPDO = array($sender, $recipient_mail, $subject, $mailerParams->charset); + if (in_array($user_id, $exceptUsers[$basketId])) { + $logger->write('Notification disabled for '.$user_id, 'WARNING'); } else { - if (count($attachments) > 0) { - $query = "INSERT INTO " . _NOTIF_EMAIL_STACK_TABLE_NAME - . " (sender, recipient, subject, html_body, charset, attachments, module) " - . "VALUES (?, ?, ?, ?, ?, '".implode(',', $attachments)."', 'notifications')"; + $logger->write('... adding e-mail to email stack', 'INFO'); + if ($_SESSION['config']['databasetype'] == 'ORACLE') { + $query = "DECLARE + vString notif_email_stack.html_body%type; + BEGIN + vString := '".$html."'; + INSERT INTO "._NOTIF_EMAIL_STACK_TABLE_NAME." + (sender, recipient, subject, html_body, charset, attachments, module) + VALUES (?, ?, ?, vString, ?, '".implode(',', $attachments)."', 'notifications'); + END;"; + $arrayPDO = array($sender, $recipient_mail, $subject, $mailerParams->charset); } else { - $query = "INSERT INTO " . _NOTIF_EMAIL_STACK_TABLE_NAME - . " (sender, recipient, subject, html_body, charset, module) " - . "VALUES (?, ?, ?, ?, ?, 'notifications')"; + if (count($attachments) > 0) { + $query = 'INSERT INTO '._NOTIF_EMAIL_STACK_TABLE_NAME + .' (sender, recipient, subject, html_body, charset, attachments, module) ' + ."VALUES (?, ?, ?, ?, ?, '".implode(',', $attachments)."', 'notifications')"; + } else { + $query = 'INSERT INTO '._NOTIF_EMAIL_STACK_TABLE_NAME + .' (sender, recipient, subject, html_body, charset, module) ' + ."VALUES (?, ?, ?, ?, ?, 'notifications')"; + } + $arrayPDO = array($sender, $recipient_mail, $subject, $html, $mailerParams->charset); } - $arrayPDO = array($sender, $recipient_mail, $subject, $html, $mailerParams->charset); - } - $db->query($query, $arrayPDO); - } - foreach ($basket_list['events'] as $event) { - if (in_array($event->user_id, $exceptUsers[$basketId])) { - $events_controler->commitEvent($event->event_stack_sid, "WARNING : Notification disabled for ".$event->user_id); - } else { - $events_controler->commitEvent($event->event_stack_sid, "SUCCESS"); + $db->query($query, $arrayPDO); + } + foreach ($basket_list['events'] as $event) { + if (in_array($event->user_id, $exceptUsers[$basketId])) { + $events_controler->commitEvent($event->event_stack_sid, 'WARNING : Notification disabled for '.$event->user_id); + } else { + $events_controler->commitEvent($event->event_stack_sid, 'SUCCESS'); + } } } + ++$i; } - $i++; - } - $state = 'END'; + $state = 'END'; } } //clean tmp directory echo "clean tmp path ....\n"; -array_map('unlink', glob($_SESSION['config']['tmppath']."/*.html")); +array_map('unlink', glob($_SESSION['config']['tmppath'].'/*.html')); $logger->write('End of process', 'INFO'); Bt_logInDataBase( diff --git a/modules/notifications/batch/process_event_stack.php b/modules/notifications/batch/process_event_stack.php index 2c348204ccf..4de3343fbcb 100755 --- a/modules/notifications/batch/process_event_stack.php +++ b/modules/notifications/batch/process_event_stack.php @@ -3,292 +3,260 @@ BATCH PROCESS EVENT STACK Processes events from table event_stack - - 1 - Groups events by + + 1 - Groups events by * Recipient * Event 2 - Merge template for each recipient / event - + 3 - Prepare e-mail and add to e-mail stack - + ******************************************************************************/ /* begin */ // load the config and prepare to process -include('load_process_event_stack.php'); +include 'load_process_event_stack.php'; $state = 'LOAD_NOTIFICATIONS'; -while ($state <> 'END') { +while ($state != 'END') { if (isset($logger)) { - $logger->write('STATE:' . $state, 'INFO'); + $logger->write('STATE:'.$state, 'INFO'); } switch ($state) { - - /**********************************************************************/ - /* LOAD_NOTIFICATIONS */ - /* Load notification defsidentified with notification id */ - /**********************************************************************/ - case 'LOAD_NOTIFICATIONS' : - $logger->write("Loading configuration for notification id " . $notificationId, 'INFO'); - $notification = $notifications_controler->getByNotificationId($notificationId); - if ($notification === FALSE) { - Bt_exitBatch(1, "Notification '".$notificationId."' not found"); - } - if ($notification->is_enabled === 'N') { - Bt_exitBatch(100, "Notification '".$notificationId."' is disabled"); - } - $state = 'LOAD_EVENTS'; - break; - - /**********************************************************************/ - /* LOAD_EVENTS */ - /* Checking if the stack has notifications to proceed */ - /**********************************************************************/ - case 'LOAD_EVENTS' : - $logger->write("Loading events for notification sid " . $notification->notification_sid, 'INFO'); - $events = $events_controler->getEventsByNotificationSid($notification->notification_sid); - $totalEventsToProcess = count($events); - $currentEvent = 0; - if ($totalEventsToProcess === 0) { - Bt_exitBatch(0, 'No event to process'); - } - $logger->write($totalEventsToProcess . ' events to process', 'INFO'); - $tmpNotifs = array(); - $state = 'MERGE_EVENT'; - break; - - /**********************************************************************/ - /* MERGE_EVENT */ - /* Process event stack to get recipients */ - /**********************************************************************/ - case 'MERGE_EVENT' : - foreach($events as $event) { - $logger->write("Getting recipients using diffusion type '" .$notification->diffusion_type . "'", 'INFO'); - // Diffusion type specific recipients - $recipients = array(); - $recipients = $diffusion_type_controler->getRecipients($notification, $event); - // Diffusion type specific res_id - $logger->write("Getting document ids using diffusion type '" .$notification->diffusion_type . "'", 'INFO'); - $res_id = false; - if($event->table_name == $coll_table || $event->table_name == $coll_view) { - $res_id = $event->record_id; - } else { - $res_id = $diffusion_type_controler->getResId($notification, $event); - } - $event->res_id = $res_id; - - $nbRecipients = count($recipients); - - $logger->write($nbRecipients .' recipients found, checking active and absences', 'INFO'); + /**********************************************************************/ + /* LOAD_NOTIFICATIONS */ + /* Load notification defsidentified with notification id */ + /**********************************************************************/ + case 'LOAD_NOTIFICATIONS': + $logger->write('Loading configuration for notification id '.$notificationId, 'INFO'); + $notification = $notifications_controler->getByNotificationId($notificationId); + if ($notification === false) { + Bt_exitBatch(1, "Notification '".$notificationId."' not found"); + } + if ($notification->is_enabled === 'N') { + Bt_exitBatch(100, "Notification '".$notificationId."' is disabled"); + } + $state = 'LOAD_EVENTS'; + break; - if ($notification->diffusion_type === 'dest_entity') { + /**********************************************************************/ + /* LOAD_EVENTS */ + /* Checking if the stack has notifications to proceed */ + /**********************************************************************/ + case 'LOAD_EVENTS': + $logger->write('Loading events for notification sid '.$notification->notification_sid, 'INFO'); + $events = $events_controler->getEventsByNotificationSid($notification->notification_sid); + $totalEventsToProcess = count($events); + $currentEvent = 0; + if ($totalEventsToProcess === 0) { + Bt_exitBatch(0, 'No event to process'); + } + $logger->write($totalEventsToProcess.' events to process', 'INFO'); + $tmpNotifs = array(); + $state = 'MERGE_EVENT'; + break; - for($i=0; $i<$nbRecipients; $i++) { - $recipient = $recipients[$i]; - $entity_id = $recipient->entity_id; - $logger->write('Recipient entity ' . $entity_id, 'INFO'); - if($recipient->enabled != 'Y' || $recipient->mail == '') { - $logger->write($entity_id .' is disabled or mail is invalid, this notification will not be send', 'INFO'); - unset($recipients[$i]); - continue; - } + /**********************************************************************/ + /* MERGE_EVENT */ + /* Process event stack to get recipients */ + /**********************************************************************/ + case 'MERGE_EVENT': + foreach ($events as $event) { + $logger->write("Getting recipients using diffusion type '".$notification->diffusion_type."'", 'INFO'); + // Diffusion type specific recipients + $recipients = array(); + $recipients = $diffusion_type_controler->getRecipients($notification, $event); + // Diffusion type specific res_id + $logger->write("Getting document ids using diffusion type '".$notification->diffusion_type."'", 'INFO'); + $res_id = false; + if ($event->table_name == $coll_table || $event->table_name == $coll_view) { + $res_id = $event->record_id; + } else { + $res_id = $diffusion_type_controler->getResId($notification, $event); + } + $event->res_id = $res_id; - if(!isset($tmpNotifs[$entity_id])) { - $tmpNotifs[$entity_id]['recipient'] = $recipient; - $tmpNotifs[$entity_id]['attach'] = $diffusion_type_controler->getAttachFor($notification, $entity_id); - $logger->write('Checking if attachment required for ' . $entity_id . ': ' . $tmpNotifs[$entity_id]['attach'], 'INFO'); - } - $tmpNotifs[$entity_id]['events'][] = $event; + //Attach Mode ? + if (!empty($notification->attachfor_type) || $notification->attachfor_type != null) { + $attachMode = true; + $logger->write('The document will be attached for each recipient', 'INFO'); + } else { + $attachMode = false; } - } else { + $nbRecipients = count($recipients); - for($i=0; $i<$nbRecipients; $i++) { - $recipient = $recipients[$i]; - $user_id = $recipient->user_id; - $logger->write('Recipient ' . $user_id, 'INFO'); - if($recipient->enabled == 'N' || $recipient->status == 'DEL') { - $logger->write($user_id .' is disabled or deleted, this notification will not be send', 'INFO'); - unset($recipients[$i]); - continue; - } + $logger->write($nbRecipients.' recipients found, checking active and absences', 'INFO'); - if($recipient->status == 'ABS') { - $logger->write($user_id .' is absent, routing to replacent', 'INFO'); - unset($recipients[$i]); - $query = "SELECT us.* FROM users us" - . " JOIN user_abs abs ON us.user_id = abs.new_user " - . " WHERE abs.user_abs = ? AND us.enabled='Y'"; - $dbAbs = new Database(); - $stmt = $dbAbs->query($query, array($user_id)); - if($stmt->rowCount() > 0) { - //$recipient = $dbAbs->fetchObject($user_id); - $recipient = $stmt->fetchObject(); - $user_id = $recipient->user_id; - $logger->write($user_id .' is the replacent', 'INFO'); - $recipients[] = $recipient; - } else { - $logger->write('No replacent found (probably disabled)', 'INFO'); + if ($notification->diffusion_type === 'dest_entity') { + for ($i = 0; $i < $nbRecipients; ++$i) { + $recipient = $recipients[$i]; + $entity_id = $recipient->entity_id; + $logger->write('Recipient entity '.$entity_id, 'INFO'); + if ($recipient->enabled != 'Y' || $recipient->mail == '') { + $logger->write($entity_id.' is disabled or mail is invalid, this notification will not be send', 'INFO'); + unset($recipients[$i]); continue; } + + if (!isset($tmpNotifs[$entity_id])) { + $tmpNotifs[$entity_id]['recipient'] = $recipient; + } + $tmpNotifs[$entity_id]['events'][] = $event; } - if(!isset($tmpNotifs[$user_id])) { - $tmpNotifs[$user_id]['recipient'] = $recipient; - $tmpNotifs[$user_id]['attach'] = $diffusion_type_controler->getAttachFor($notification, $user_id); - $logger->write('Checking if attachment required for ' . $user_id . ': ' . $tmpNotifs[$user_id]['attach'], 'INFO'); + } else { + for ($i = 0; $i < $nbRecipients; ++$i) { + $recipient = $recipients[$i]; + $user_id = $recipient->user_id; + $logger->write('Recipient '.$user_id, 'INFO'); + if ($recipient->enabled == 'N' || $recipient->status == 'DEL') { + $logger->write($user_id.' is disabled or deleted, this notification will not be send', 'INFO'); + unset($recipients[$i]); + continue; + } + + if ($recipient->status == 'ABS') { + $logger->write($user_id.' is absent, routing to replacent', 'INFO'); + unset($recipients[$i]); + $query = 'SELECT us.* FROM users us' + .' JOIN user_abs abs ON us.user_id = abs.new_user ' + ." WHERE abs.user_abs = ? AND us.enabled='Y'"; + $dbAbs = new Database(); + $stmt = $dbAbs->query($query, array($user_id)); + if ($stmt->rowCount() > 0) { + //$recipient = $dbAbs->fetchObject($user_id); + $recipient = $stmt->fetchObject(); + $user_id = $recipient->user_id; + $logger->write($user_id.' is the replacent', 'INFO'); + $recipients[] = $recipient; + } else { + $logger->write('No replacent found (probably disabled)', 'INFO'); + continue; + } + } + if (!isset($tmpNotifs[$user_id])) { + $tmpNotifs[$user_id]['recipient'] = $recipient; + } + $tmpNotifs[$user_id]['events'][] = $event; } - $tmpNotifs[$user_id]['events'][] = $event; } + if (count($recipients) === 0) { + $logger->write('No recipient found', 'WARNING'); + $events_controler->commitEvent($event->event_stack_sid, 'INFO: no recipient found'); + } + } + $totalNotificationsToProcess = count($tmpNotifs); + $logger->write($totalNotificationsToProcess.' notifications to process', 'INFO'); + switch ($notification->notification_mode) { + case 'EMAIL': + $state = 'FILL_EMAIL_STACK'; + break; + case 'RSS': + $state = 'FILL_RSS_STACK'; + break; } - - if (count($recipients) === 0) { - $logger->write('No recipient found' , 'WARNING'); - $events_controler->commitEvent($event->event_stack_sid, "INFO: no recipient found"); - } - } - $totalNotificationsToProcess = count($tmpNotifs); - $logger->write($totalNotificationsToProcess .' notifications to process', 'INFO'); - switch($notification->notification_mode) { - case 'EMAIL': - $state = 'FILL_EMAIL_STACK'; - break; - case 'RSS': - $state = 'FILL_RSS_STACK'; break; - } - break; - - /**********************************************************************/ - /* FILL_EMAIL_STACK */ - /* Merge template and fill notif_email_stack */ - /**********************************************************************/ - case 'FILL_EMAIL_STACK' : - foreach($tmpNotifs as $user_id => $tmpNotif) { - // Merge template with data and style - $logger->write('Merging template #' . $notification->template_id - . ' ('.count($tmpNotif['events']).' events) for user ' . $user_id, 'INFO'); - - $params = array( - 'recipient' => $tmpNotif['recipient'], - 'events' => $tmpNotif['events'], - 'notification' => $notification, - 'maarchUrl' => $maarchUrl, - 'maarchApps' => $maarchApps, - 'coll_id' => $coll_id, - 'res_table' => $coll_table, - 'res_view' => $coll_view - ); - $html = $templates_controler->merge($notification->template_id, $params, 'content'); - if(strlen($html) === 0) { - foreach($tmpNotif['events'] as $event) { - $events_controler->commitEvent($event->event_stack_sid, "FAILED: Error when merging template"); + + /**********************************************************************/ + /* FILL_EMAIL_STACK */ + /* Merge template and fill notif_email_stack */ + /**********************************************************************/ + case 'FILL_EMAIL_STACK': + foreach ($tmpNotifs as $user_id => $tmpNotif) { + // Merge template with data and style + $logger->write('Merging template #'.$notification->template_id + .' ('.count($tmpNotif['events']).' events) for user '.$user_id, 'INFO'); + + $params = array( + 'recipient' => $tmpNotif['recipient'], + 'events' => $tmpNotif['events'], + 'notification' => $notification, + 'maarchUrl' => $maarchUrl, + 'maarchApps' => $maarchApps, + 'coll_id' => $coll_id, + 'res_table' => $coll_table, + 'res_view' => $coll_view, + ); + $html = $templates_controler->merge($notification->template_id, $params, 'content'); + if (strlen($html) === 0) { + foreach ($tmpNotif['events'] as $event) { + $events_controler->commitEvent($event->event_stack_sid, 'FAILED: Error when merging template'); + } + Bt_exitBatch(8, 'Could not merge template with the data'); } - Bt_exitBatch(8, "Could not merge template with the data"); - } - - // Prepare e-mail for stack - $sender = (string)$mailerParams->mailfrom; - $recipient_mail = $tmpNotif['recipient']->mail; - $subject = $notification->description; - $html = $func->protect_string_db($html, '', 'no'); - $html = str_replace('&', '&', $html); - $html = str_replace('&', '#and#', $html); - - // Attachments - $attachments = array(); - if($tmpNotif['attach']) { - $logger->write('Adding attachments', 'INFO'); - foreach($tmpNotif['events'] as $event) { - // Check if event is related to document in collection - if($event->res_id != '') { - $query = "SELECT " - . "ds.path_template ," - . "mlb.path, " - . "mlb.filename " - . "FROM ".$coll_view." mlb LEFT JOIN docservers ds ON mlb.docserver_id = ds.docserver_id " - . "WHERE mlb.res_id = ?"; - $stmt = Bt_doQuery($db, $query, array($event->res_id)); - $path_parts = $stmt->fetchObject(); - $path = $path_parts->path_template . str_replace('#', '/', $path_parts->path) . $path_parts->filename; - $path = str_replace('//', '/', $path); - $path = str_replace('\\', '/', $path); - $attachments[] = $path; + + // Prepare e-mail for stack + $sender = (string) $mailerParams->mailfrom; + $recipient_mail = $tmpNotif['recipient']->mail; + $subject = $notification->description; + $html = $func->protect_string_db($html, '', 'no'); + $html = str_replace('&', '&', $html); + $html = str_replace('&', '#and#', $html); + + // Attachments + $attachments = array(); + if ($attachMode) { + $logger->write('Adding attachments', 'INFO'); + foreach ($tmpNotif['events'] as $event) { + // Check if event is related to document in collection + if ($event->res_id != '') { + $query = 'SELECT ' + .'ds.path_template ,' + .'mlb.path, ' + .'mlb.filename ' + .'FROM '.$coll_view.' mlb LEFT JOIN docservers ds ON mlb.docserver_id = ds.docserver_id ' + .'WHERE mlb.res_id = ?'; + $stmt = Bt_doQuery($db, $query, array($event->res_id)); + $path_parts = $stmt->fetchObject(); + $path = $path_parts->path_template.str_replace('#', '/', $path_parts->path).$path_parts->filename; + $path = str_replace('//', '/', $path); + $path = str_replace('\\', '/', $path); + $attachments[] = $path; + } } + $logger->write(count($attachments).' attachment(s) added', 'INFO'); } - $logger->write(count($attachments) . ' attachment(s) added', 'INFO'); - } - - $logger->write('Adding e-mail to email stack', 'INFO'); - if ($_SESSION['config']['databasetype'] == 'ORACLE') { - $query = "DECLARE - vString notif_email_stack.html_body%type; - BEGIN - vString := '" . $html ."'; - INSERT INTO " . _NOTIF_EMAIL_STACK_TABLE_NAME . " - (sender, recipient, subject, html_body, charset, attachments, module) - VALUES (?, ?, ?, vString, ?, '".implode(',', $attachments)."', 'notifications'); - END;"; - $arrayPDO = array($sender, $recipient_mail, $subject, $mailerParams->charset); - } else { - if(count($attachments) > 0) { - $query = "INSERT INTO " . _NOTIF_EMAIL_STACK_TABLE_NAME - . " (sender, recipient, subject, html_body, charset, attachments, module) " - . "VALUES (?, ?, ?, ?, ?, '".implode(',', $attachments)."', 'notifications')"; + $logger->write('Adding e-mail to email stack', 'INFO'); + if ($_SESSION['config']['databasetype'] == 'ORACLE') { + $query = "DECLARE + vString notif_email_stack.html_body%type; + BEGIN + vString := '".$html."'; + INSERT INTO "._NOTIF_EMAIL_STACK_TABLE_NAME." + (sender, recipient, subject, html_body, charset, attachments, module) + VALUES (?, ?, ?, vString, ?, '".implode(',', $attachments)."', 'notifications'); + END;"; + $arrayPDO = array($sender, $recipient_mail, $subject, $mailerParams->charset); } else { - $query = "INSERT INTO " . _NOTIF_EMAIL_STACK_TABLE_NAME - . " (sender, recipient, subject, html_body, charset, module) " - . "VALUES (?, ?, ?, ?, ?, 'notifications')"; + if (count($attachments) > 0) { + $query = 'INSERT INTO '._NOTIF_EMAIL_STACK_TABLE_NAME + .' (sender, recipient, subject, html_body, charset, attachments, module) ' + ."VALUES (?, ?, ?, ?, ?, '".implode(',', $attachments)."', 'notifications')"; + } else { + $query = 'INSERT INTO '._NOTIF_EMAIL_STACK_TABLE_NAME + .' (sender, recipient, subject, html_body, charset, module) ' + ."VALUES (?, ?, ?, ?, ?, 'notifications')"; + } + $arrayPDO = array($sender, $recipient_mail, $subject, $html, $mailerParams->charset); } - $arrayPDO = array($sender, $recipient_mail, $subject, $html, $mailerParams->charset); - - } - //$logger->write('SQL query:' . $query, 'DEBUG'); - $db2 = new Database(); - $db2->query($query, $arrayPDO); - - foreach($tmpNotif['events'] as $event) { - $events_controler->commitEvent($event->event_stack_sid, "SUCCESS"); - } - } - $state = 'END'; - break; - - /**********************************************************************/ - /* FILL_EMAIL_STACK */ - /* Merge template and fill notif_email_stack */ - /**********************************************************************/ - case 'FILL_RSS_STACK' : - foreach($tmpNotifs as $user_id => $tmpNotif) { - // Merge template with data and style - $logger->write('Adding RSS item ('.count($tmpNotif['events']).' events) for user ' . $user_id, 'INFO'); - - foreach($tmpNotif['events'] as $event) { - // Get dynamic url - $url = str_replace('$id', $event->record_id, $notification->rss_url_template); - - // Inser into stack - $query = "INSERT INTO " . _NOTIF_RSS_STACK_TABLE_NAME - . " (rss_user_id, rss_event_stack_sid, rss_event_url) " - . "VALUES (?, ?, ?)"; //$logger->write('SQL query:' . $query, 'DEBUG'); $db2 = new Database(); - $db2->query($query, array($user_id, $event->event_stack_sid, $url)); - $events_controler->commitEvent($event->event_stack_sid, "SUCCESS"); + $db2->query($query, $arrayPDO); + + foreach ($tmpNotif['events'] as $event) { + $events_controler->commitEvent($event->event_stack_sid, 'SUCCESS'); + } } - - - } - $state = 'END'; - break; + $state = 'END'; + break; } - } $logger->write('End of process', 'INFO'); Bt_logInDataBase( $totalEventsToProcess, 0, 'process without error' -); +); //unlink($GLOBALS['lckFile']); exit($GLOBALS['exitCode']); diff --git a/modules/notifications/diffusion_types/contact.php b/modules/notifications/diffusion_types/contact.php index 1beb1f12bf6..981c7cce19c 100755 --- a/modules/notifications/diffusion_types/contact.php +++ b/modules/notifications/diffusion_types/contact.php @@ -1,51 +1,37 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2015 Maarch * -* This file is part of Maarch Framework. +* @brief contact * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - switch ($request) { -case 'form_content': - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_CONTACT_DIFF_TYPE . '</p>'; - $form_content .= '<input type="hidden" name="'.$formId.'" id="'.$formId.'" value="contact">'; - break; - -case 'recipients': - $query = "SELECT contact_id as user_id, contact_email as mail" - . " FROM res_view_letterbox " - . " WHERE (contact_email is not null or contact_email <> '') and res_id = ?"; - $dbRecipients = new Database(); - $stmt = $dbRecipients->query($query, array($event->record_id)); - $recipients = array(); - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; + case 'recipients': + $query = 'SELECT contact_id as user_id, contact_email as mail' + .' FROM res_view_letterbox ' + ." WHERE (contact_email is not null or contact_email <> '') and res_id = ?"; + $dbRecipients = new Database(); + $stmt = $dbRecipients->query($query, array($event->record_id)); + $recipients = array(); + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; + } + break; -case 'attach': - $query = "SELECT contact_id as user_id, contact_email as mail" - . " FROM res_view_letterbox " - . " WHERE (contact_email is not null or contact_email <> '') and res_id = ?"; - $attach = false; - $dbAttach = new Database(); - $stmt = $dbAttach->query($query, array($event->record_id)); - if($stmt->rowCount() > 0) { - $attach = true; - } - break; + case 'attach': + $query = 'SELECT contact_id as user_id, contact_email as mail' + .' FROM res_view_letterbox ' + ." WHERE (contact_email is not null or contact_email <> '') and res_id = ?"; + $attach = false; + $dbAttach = new Database(); + $stmt = $dbAttach->query($query, array($event->record_id)); + if ($stmt->rowCount() > 0) { + $attach = true; + } + break; } diff --git a/modules/notifications/diffusion_types/copy_list.php b/modules/notifications/diffusion_types/copy_list.php index 5676e44671f..10af5934d9e 100755 --- a/modules/notifications/diffusion_types/copy_list.php +++ b/modules/notifications/diffusion_types/copy_list.php @@ -1,161 +1,145 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2015 Maarch * -* This file is part of Maarch Framework. +* @brief copy_list * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notification */ - switch ($request) { -case 'form_content': -//Affichage du formulaire/interface dans l'administration des notification => Envoi Ajax - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_COPY_LIST_DIFF_TYPE . '</p>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - - // Copy to users - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li " - . " JOIN users us ON li.item_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'cc'" - . " AND item_type='user_id'"; - - $arrayPDO = array(":recordid" => $event->record_id); - - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")" - ; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid AND lb.status not in ('INIT', 'AVAL') AND li.item_id <> :userid"; - $arrayPDO = array_merge($arrayPDO, array(":userid" => $event->user_id)); - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - - $arrayPDO = array(":recordid" => $event->record_id); - // Copy to entities - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li " - . " LEFT JOIN users_entities ue ON li.item_id = ue.entity_id " - . " JOIN users us ON ue.user_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'cc'" - . " AND item_type='entity_id'"; - - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")" - ; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - break; - - case 'listinstance': - default: - $where .= " AND listinstance_id = :recordid"; - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - $arrayPDO = array(":recordid" => $event->record_id); - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; + case 'recipients': + $recipients = array(); + $dbRecipients = new Database(); + + // Copy to users + $select = 'SELECT distinct us.*'; + $from = ' FROM listinstance li ' + .' JOIN users us ON li.item_id = us.user_id'; + $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'cc'" + ." AND item_type='user_id'"; + + $arrayPDO = array(':recordid' => $event->record_id); + + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id' + .' AND (' + .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) ' + .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)' + .')' + ; + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= " AND listinstance_id = :recordid AND lb.status not in ('INIT', 'AVAL') AND li.item_id <> :userid"; + $arrayPDO = array_merge($arrayPDO, array(':userid' => $event->user_id)); + } + + $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); + } + + $stmt = $dbRecipients->query($query, $arrayPDO); + + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; + } + + $arrayPDO = array(':recordid' => $event->record_id); + // Copy to entities + $select = 'SELECT distinct us.*'; + $from = ' FROM listinstance li ' + .' LEFT JOIN users_entities ue ON li.item_id = ue.entity_id ' + .' JOIN users us ON ue.user_id = us.user_id'; + $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'cc'" + ." AND item_type='entity_id'"; + + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id' + .' AND (' + .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) ' + .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)' + .')' + ; + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + break; + + case 'listinstance': + default: + $where .= ' AND listinstance_id = :recordid'; + } + + $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); + } + + $stmt = $dbRecipients->query($query, $arrayPDO); + + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; + } break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; + + case 'attach': + $attach = false; break; - - case 'listinstance': - default: - $where .= " AND listinstance_id = :recordid"; - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; + case 'res_id': + $arrayPDO = array(':recordid' => $event->record_id); + $select = 'SELECT li.res_id'; + $from = ' FROM listinstance li'; + $where = " WHERE li.coll_id = 'letterbox_coll' "; + + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'; + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + break; + + case 'listinstance': + default: + $where .= ' AND listinstance_id = :recordid'; + } + + $query = $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); + } + + $dbResId = new Database(); + $stmt = $dbResId->query($query, $arrayPDO); + $res_id_record = $stmt->fetchObject(); + $res_id = $res_id_record->res_id; + break; } -?> diff --git a/modules/notifications/diffusion_types/copy_list_sample.php b/modules/notifications/diffusion_types/copy_list_sample.php deleted file mode 100755 index 84e7d0f47fc..00000000000 --- a/modules/notifications/diffusion_types/copy_list_sample.php +++ /dev/null @@ -1,165 +0,0 @@ -<?php - -/* -* Copyright 2008-2015 Maarch -* -* This file is part of Maarch Framework. -* -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. -*/ - -switch ($request) { -case 'form_content': -//Affichage du formulaire/interface dans l'administration des notification => Envoi Ajax - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_COPY_LIST_DIFF_TYPE . '</p>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - $arrayPDO = array(":recordid" => $event->record_id); - - // Copy to users - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li " - . " JOIN users us ON li.item_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'cc'" - . " AND item_type='user_id'"; - - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")"; - $where .= " AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - - $arrayPDO = array(":recordid" => $event->record_id); - // Copy to entities - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li " - . " LEFT JOIN users_entities ue ON li.item_id = ue.entity_id " - . " JOIN users us ON ue.user_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'cc'" - . " AND item_type='entity_id'"; - - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")"; - $where .= " AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - $arrayPDO = array(":recordid" => $event->record_id); - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; - $where .= " AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; - -} -?> diff --git a/modules/notifications/diffusion_types/dest_entity.php b/modules/notifications/diffusion_types/dest_entity.php index e100a5e4ca4..fe470f4501b 100755 --- a/modules/notifications/diffusion_types/dest_entity.php +++ b/modules/notifications/diffusion_types/dest_entity.php @@ -1,200 +1,134 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2015 Maarch * -* This file is part of Maarch Framework. +* @brief dest_entity * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - switch ($request) { -case 'form_content': - require_once 'core/class/class_request.php' ; - - if($_SESSION['m_admin']['notification']['diffusion_type']!='dest_entity'){$_SESSION['m_admin']['notification']['diffusion_properties']='';} - //Get list of selected status - $choosen_status_tab = explode(",",$_SESSION['m_admin']['notification']['diffusion_properties']); - $choosen_status_sring = "'" . implode("','", $choosen_status_tab) . "'"; - - - //Get list of aff availables status - $select["status"] = array(); - array_push($select["status"], 'id', 'label_status'); - $request = new request(); - $where = 'id NOT IN (?)'; - $what = ''; - $tab = $request->PDOselect( - $select, $where, array($choosen_status_tab), $orderstr, $_SESSION['config']['databasetype'] - ); - var_dump($choosen_status_tab);exit; - $status_list = $tab; - - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_DEST_ENTITY_DIFF_TYPE_WITH_STATUS . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="statuseslist[]" id="statuseslist" size="7" ondblclick=\'moveclick(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' multiple="multiple" >'; - foreach ($status_list as $this_status) { - $form_content .= '<option value="'.$this_status[0]['value'].'" selected="selected" >'.$this_status[0]['value'].'</option>'; - } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["statuseslist[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist[]"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="diffusion_properties[]" id="diffusion_properties" size="7" ondblclick=\'moveclick(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' multiple="multiple" >'; - - foreach ($choosen_status_tab as $this_status) { - if($this_status!=''){ - $form_content .= '<option value="'.$this_status.'" selected="selected" >'.$this_status.'</option>'; - } - } - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - - $select = "SELECT distinct en.entity_id, en.enabled, en.email AS mail"; - $from = " FROM res_view_letterbox rvl JOIN entities en ON rvl.destination = en.entity_id"; - $where = " WHERE rvl.res_id = :recordid"; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { -// case 'notes': -// $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; -// $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; -// $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" -// . " AND (" -// . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " -// . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" -// . ")"; -// if($notification->diffusion_properties!=''){ -// $status_tab=explode(",",$notification->diffusion_properties); -// // $status_str=implode("','",$status_tab); -// $where .= " AND lb.status in (:statustab)"; -// $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); -// } -// -// break; - -// case 'res_letterbox': -// case 'res_view_letterbox': -// $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; -// $where .= " AND lb.res_id = :recordid"; -// if($notification->diffusion_properties!=''){ -// $status_tab=explode(",",$notification->diffusion_properties); -// // $status_str=implode("','",$status_tab); -// $where .= " AND lb.status in (:statustab)"; -// $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); -// } -// break; - -// case 'listinstance': -// default: -// $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; -// $where .= " AND listinstance_id = :recordid"; -// if($notification->diffusion_properties!=''){ -// $status_tab=explode(",",$notification->diffusion_properties); -// // $status_str=implode("','",$status_tab); -// $where .= " AND lb.status in (:statustab)"; -// $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); -// } - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + case 'recipients': + $recipients = array(); + $dbRecipients = new Database(); + + $select = 'SELECT distinct en.entity_id, en.enabled, en.email AS mail'; + $from = ' FROM res_view_letterbox rvl JOIN entities en ON rvl.destination = en.entity_id'; + $where = ' WHERE rvl.res_id = :recordid'; + + $arrayPDO = array(':recordid' => $event->record_id); + /*switch($event->table_name) { + case 'notes': + $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; + $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; + $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" + . " AND (" + . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " + . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" + . ")"; + if($notification->diffusion_properties!=''){ + $status_tab=explode(",",$notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= " AND lb.status in (:statustab)"; + $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + } + + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; + $where .= " AND lb.res_id = :recordid"; + if($notification->diffusion_properties!=''){ + $status_tab=explode(",",$notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= " AND lb.status in (:statustab)"; + $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; + $where .= " AND listinstance_id = :recordid"; + if($notification->diffusion_properties!=''){ + $status_tab=explode(",",$notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= " AND lb.status in (:statustab)"; + $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + } + }*/ + + $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); } - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + $stmt = $dbRecipients->query($query, $arrayPDO); + + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; } break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + case 'attach': + $attach = false; + break; + + case 'res_id': + $select = 'SELECT li.res_id'; + $from = ' FROM listinstance li'; + $where = " WHERE li.coll_id = 'letterbox_coll' "; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + } + + $query = $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); } - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; - + $dbResId = new Database(); + $stmt = $dbResId->query($query, $arrayPDO); + $res_id_record = $stmt->fetchObject(); + $res_id = $res_id_record->res_id; + break; } -?> diff --git a/modules/notifications/diffusion_types/dest_user.php b/modules/notifications/diffusion_types/dest_user.php index f6320486bf7..16552725b6f 100755 --- a/modules/notifications/diffusion_types/dest_user.php +++ b/modules/notifications/diffusion_types/dest_user.php @@ -1,199 +1,134 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2015 Maarch * -* This file is part of Maarch Framework. +* @brief dest_user * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - switch ($request) { -case 'form_content': - require_once 'core/class/class_request.php' ; - - if($_SESSION['m_admin']['notification']['diffusion_type']!='dest_user'){$_SESSION['m_admin']['notification']['diffusion_properties']='';} - //Get list of selected status - $choosen_status_tab = explode(",",$_SESSION['m_admin']['notification']['diffusion_properties']); - $choosen_status_sring = "'" . implode("','", $choosen_status_tab) . "'"; - - - //Get list of aff availables status - $select["status"] = array(); - array_push($select["status"], 'id', 'label_status'); - $request = new request(); - $where = 'id NOT IN (?)'; - $what = ''; - $tab = $request->PDOselect( - $select, $where, array($choosen_status_tab), $orderstr, $_SESSION['config']['databasetype'] - ); - $status_list = $tab; - - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_DEST_USER_DIFF_TYPE_WITH_STATUS . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="statuseslist[]" id="statuseslist" size="7" ondblclick=\'moveclick(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' multiple="multiple" >'; - foreach ($status_list as $this_status) { - $form_content .= '<option value="'.$this_status[0]['value'].'" selected="selected" >'.$this_status[0]['value'].'</option>'; + case 'recipients': + $recipients = array(); + $dbRecipients = new Database(); + + $select = 'SELECT distinct us.*'; + $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id'; + $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'dest'"; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id' + .' AND (' + .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) ' + .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)' + .')'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["statuseslist[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist[]"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="diffusion_properties[]" id="diffusion_properties" size="7" ondblclick=\'moveclick(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' multiple="multiple" >'; - - foreach ($choosen_status_tab as $this_status) { - if($this_status!=''){ - $form_content .= '<option value="'.$this_status.'" selected="selected" >'.$this_status.'</option>'; - } - } - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li JOIN users us ON li.item_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'dest'"; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); - } - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } } - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); } - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + $stmt = $dbRecipients->query($query, $arrayPDO); + + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; } break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); - } + + case 'attach': + $attach = false; break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + case 'res_id': + $select = 'SELECT li.res_id'; + $from = ' FROM listinstance li'; + $where = " WHERE li.coll_id = 'letterbox_coll' "; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } } - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; - + + $query = $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); + } + $dbResId = new Database(); + $stmt = $dbResId->query($query, $arrayPDO); + $res_id_record = $stmt->fetchObject(); + $res_id = $res_id_record->res_id; + break; } -?> diff --git a/modules/notifications/diffusion_types/dest_user_sample.php b/modules/notifications/diffusion_types/dest_user_sample.php deleted file mode 100755 index 966dcadb632..00000000000 --- a/modules/notifications/diffusion_types/dest_user_sample.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php - -/* -* Copyright 2008-2015 Maarch -* -* This file is part of Maarch Framework. -* -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. -*/ - -switch ($request) { -case 'form_content': - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_DEST_USER_DIFF_TYPE . '</p>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li JOIN users us ON li.item_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'dest'"; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")"; - $where .= " AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'listinstance': - default: - //$where .= " AND listinstance_id = " . $event->record_id; - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; - $where .= " AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid AND lb.status not in ('VAL', 'VAL1', 'VAL2', 'QUAL', 'INIT', 'RET', 'DEL', 'END')"; - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; - -} -?> diff --git a/modules/notifications/diffusion_types/dest_user_sign.php b/modules/notifications/diffusion_types/dest_user_sign.php index b05b7f9074f..c0c03ae20f8 100755 --- a/modules/notifications/diffusion_types/dest_user_sign.php +++ b/modules/notifications/diffusion_types/dest_user_sign.php @@ -1,202 +1,136 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2016 Maarch * -* This file is part of Maarch Framework. +* @brief dest_user_sign * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - switch ($request) { -case 'form_content': - require_once 'core/class/class_request.php' ; - - if($_SESSION['m_admin']['notification']['diffusion_type'] != 'dest_user_sign') { - $_SESSION['m_admin']['notification']['diffusion_properties'] = ''; - } - //Get list of selected status - $choosen_status_tab = explode(",",$_SESSION['m_admin']['notification']['diffusion_properties']); - $choosen_status_sring = "'" . implode("','", $choosen_status_tab) . "'"; - - - //Get list of aff availables status - $select["status"] = array(); - array_push($select["status"], 'id', 'label_status'); - $request = new request(); - $where = 'id NOT IN (?)'; - $what = ''; - $tab = $request->PDOselect( - $select, $where, array($choosen_status_tab), $orderstr, $_SESSION['config']['databasetype'] - ); - $status_list = $tab; - - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_DEST_USER_SIGN_DIFF_TYPE_WITH_STATUS . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="statuseslist[]" id="statuseslist" size="7" ondblclick=\'moveclick(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' multiple="multiple" >'; - foreach ($status_list as $this_status) { - $form_content .= '<option value="'.$this_status[0]['value'].'" selected="selected" >'.$this_status[0]['value'].'</option>'; + case 'recipients': + $recipients = array(); + $dbRecipients = new Database(); + + $select = 'SELECT distinct us.*'; + $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id'; + $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'sign' " + .'and process_date IS NULL '; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id' + .' AND (' + .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) ' + .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN ' + .' users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)' + .')'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["statuseslist[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist[]"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="diffusion_properties[]" id="diffusion_properties" size="7" ondblclick=\'moveclick(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' multiple="multiple" >'; - - foreach ($choosen_status_tab as $this_status) { - if($this_status!=''){ - $form_content .= '<option value="'.$this_status.'" selected="selected" >'.$this_status.'</option>'; - } - } - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li JOIN users us ON li.item_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'sign' " - . "and process_date IS NULL "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN " - . " users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")"; - if($notification->diffusion_properties!='') { - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); - } - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } } - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); } - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + $stmt = $dbRecipients->query($query, $arrayPDO); + + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; } break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); - } + + case 'attach': + $attach = false; break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + case 'res_id': + $select = 'SELECT li.res_id'; + $from = ' FROM listinstance li'; + $where = " WHERE li.coll_id = 'letterbox_coll' "; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } } - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; - + + $query = $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); + } + $dbResId = new Database(); + $stmt = $dbResId->query($query, $arrayPDO); + $res_id_record = $stmt->fetchObject(); + $res_id = $res_id_record->res_id; + break; } diff --git a/modules/notifications/diffusion_types/dest_user_visa.php b/modules/notifications/diffusion_types/dest_user_visa.php index 8e88ac12b4f..d0d656b4fc3 100755 --- a/modules/notifications/diffusion_types/dest_user_visa.php +++ b/modules/notifications/diffusion_types/dest_user_visa.php @@ -1,202 +1,136 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2016 Maarch * -* This file is part of Maarch Framework. +* @brief dest_user_visa * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - switch ($request) { -case 'form_content': - require_once 'core/class/class_request.php' ; - - if($_SESSION['m_admin']['notification']['diffusion_type'] != 'dest_user_visa') { - $_SESSION['m_admin']['notification']['diffusion_properties'] = ''; - } - //Get list of selected status - $choosen_status_tab = explode(",",$_SESSION['m_admin']['notification']['diffusion_properties']); - $choosen_status_sring = "'" . implode("','", $choosen_status_tab) . "'"; - - - //Get list of aff availables status - $select["status"] = array(); - array_push($select["status"], 'id', 'label_status'); - $request = new request(); - $where = 'id NOT IN (?)'; - $what = ''; - $tab = $request->PDOselect( - $select, $where, array($choosen_status_tab), $orderstr, $_SESSION['config']['databasetype'] - ); - $status_list = $tab; - - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_DEST_USER_VISA_DIFF_TYPE_WITH_STATUS . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="statuseslist[]" id="statuseslist" size="7" ondblclick=\'moveclick(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' multiple="multiple" >'; - foreach ($status_list as $this_status) { - $form_content .= '<option value="'.$this_status[0]['value'].'" selected="selected" >'.$this_status[0]['value'].'</option>'; + case 'recipients': + $recipients = array(); + $dbRecipients = new Database(); + + $select = 'SELECT distinct us.*'; + $from = ' FROM listinstance li JOIN users us ON li.item_id = us.user_id'; + $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'visa' " + .'and process_date IS NULL '; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id' + .' AND (' + .' notes.id not in (SELECT DISTINCT note_id FROM note_entities) ' + .' OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN ' + .' users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)' + .')'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["statuseslist[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["statuseslist[]"],document.frmevent.elements["diffusion_properties[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist[]"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="diffusion_properties[]" id="diffusion_properties" size="7" ondblclick=\'moveclick(document.frmevent.elements["diffusion_properties[]"],document.frmevent.elements["statuseslist"]);selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' multiple="multiple" >'; - - foreach ($choosen_status_tab as $this_status) { - if($this_status!=''){ - $form_content .= '<option value="'.$this_status.'" selected="selected" >'.$this_status.'</option>'; - } - } - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["diffusion_properties[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - break; - -case 'recipients': - $recipients = array(); - $dbRecipients = new Database(); - - $select = "SELECT distinct us.*"; - $from = " FROM listinstance li JOIN users us ON li.item_id = us.user_id"; - $where = " WHERE li.coll_id = 'letterbox_coll' AND li.item_mode = 'visa' " - . "and process_date IS NULL "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id" - . " AND (" - . " notes.id not in (SELECT DISTINCT note_id FROM note_entities) " - . " OR us.user_id IN (SELECT ue.user_id FROM note_entities ne JOIN " - . " users_entities ue ON ne.item_id = ue.entity_id WHERE ne.note_id = :recordid)" - . ")"; - if($notification->diffusion_properties!='') { - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); - } - break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } } - break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); } - } - - $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $stmt = $dbRecipients->query($query, $arrayPDO); - - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -case 'res_id': - - $select = "SELECT li.res_id"; - $from = " FROM listinstance li"; - $where = " WHERE li.coll_id = 'letterbox_coll' "; - - $arrayPDO = array(":recordid" => $event->record_id); - switch($event->table_name) { - case 'notes': - $from .= " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id"; - $from .= " JOIN res_letterbox lb ON lb.res_id = notes.identifier"; - $where .= " AND notes.id = :recordid AND li.item_id != notes.user_id"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + $stmt = $dbRecipients->query($query, $arrayPDO); + + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; } break; - - case 'res_letterbox': - case 'res_view_letterbox': - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND lb.res_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); - } + + case 'attach': + $attach = false; break; - - case 'listinstance': - default: - $from .= " JOIN res_letterbox lb ON lb.res_id = li.res_id"; - $where .= " AND listinstance_id = :recordid"; - if($notification->diffusion_properties!=''){ - $status_tab=explode(",",$notification->diffusion_properties); - // $status_str=implode("','",$status_tab); - $where .= " AND lb.status in (:statustab)"; - $arrayPDO = array_merge($arrayPDO, array(":statustab" => $status_tab)); + + case 'res_id': + $select = 'SELECT li.res_id'; + $from = ' FROM listinstance li'; + $where = " WHERE li.coll_id = 'letterbox_coll' "; + + $arrayPDO = array(':recordid' => $event->record_id); + switch ($event->table_name) { + case 'notes': + $from .= ' JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id'; + $from .= ' JOIN res_letterbox lb ON lb.res_id = notes.identifier'; + $where .= ' AND notes.id = :recordid AND li.item_id != notes.user_id'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'res_letterbox': + case 'res_view_letterbox': + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND lb.res_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } + break; + + case 'listinstance': + default: + $from .= ' JOIN res_letterbox lb ON lb.res_id = li.res_id'; + $where .= ' AND listinstance_id = :recordid'; + if ($notification->diffusion_properties != '') { + $status_tab = explode(',', $notification->diffusion_properties); + // $status_str=implode("','",$status_tab); + $where .= ' AND lb.status in (:statustab)'; + $arrayPDO = array_merge($arrayPDO, array(':statustab' => $status_tab)); + } } - } - - $query = $query = $select . $from . $where; - - if($GLOBALS['logger']) { - $GLOBALS['logger']->write($query , 'DEBUG'); - } - $dbResId = new Database(); - $stmt = $dbResId->query($query, $arrayPDO); - $res_id_record = $stmt->fetchObject(); - $res_id = $res_id_record->res_id; - break; - + + $query = $query = $select.$from.$where; + + if ($GLOBALS['logger']) { + $GLOBALS['logger']->write($query, 'DEBUG'); + } + $dbResId = new Database(); + $stmt = $dbResId->query($query, $arrayPDO); + $res_id_record = $stmt->fetchObject(); + $res_id = $res_id_record->res_id; + break; } diff --git a/modules/notifications/diffusion_types/entity.php b/modules/notifications/diffusion_types/entity.php index c5e7b423b4e..cc40a9ae4b9 100755 --- a/modules/notifications/diffusion_types/entity.php +++ b/modules/notifications/diffusion_types/entity.php @@ -1,94 +1,50 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2015 Maarch * -* This file is part of Maarch Framework. +* @brief entity * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - require_once 'core/core_tables.php'; require_once 'core/class/class_request.php'; require_once 'modules/entities/class/EntityControler.php'; -switch($request) { -case 'form_content': - $entities = new EntityControler(); - $entitylist = $entities->getAllEntities(); - - $form_content .= '<input type="hidden" name="'.$formId.'" id="'.$formId.'" value="entity">'; - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_ENTITY_DIFF_TYPE . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="'.$leftList.'[]" id="'.$leftList.'" size="7" ondblclick=\'moveclick(document.frmevent.elements["'.$leftList.'[]"],document.frmevent.elements["'.$rightList.'[]"]);\' multiple="multiple" >'; - foreach ($entitylist as $entity){ - $form_content .= '<option value="'.$entity->entity_id.'" selected="selected" >'.$entity->entity_label.'</option>'; - } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["'.$leftList.'[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["'.$leftList.'[]"],document.frmevent.elements["'.$rightList.'[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["'.$rightList.'[]"],document.frmevent.elements["'.$leftList.'[]"]);selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="'.$rightList.'[]" id="'.$rightList.'" size="7" ondblclick=\'moveclick(document.frmevent.elements["'.$rightList.'[]"],document.frmevent.elements["'.$leftList.'"]);selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' multiple="multiple" >'; - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - break; - -case 'recipients': - $entities = "'". str_replace(",", "','", $notification->diffusion_properties) . "'"; - $query = "SELECT distinct us.*" - . " FROM users_entities ue " - . " LEFT JOIN users us ON us.user_id = ue.user_id " - . " WHERE ue.entity_id in (".$entities.")"; - $dbRecipients = new Database(); - $stmt = $dbRecipients->query($query); - $recipients = array(); - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; +switch ($request) { + case 'recipients': + $entities = "'".str_replace(',', "','", $notification->diffusion_properties)."'"; + $query = 'SELECT distinct us.*' + .' FROM users_entities ue ' + .' LEFT JOIN users us ON us.user_id = ue.user_id ' + .' WHERE ue.entity_id in ('.$entities.')'; + $dbRecipients = new Database(); + $stmt = $dbRecipients->query($query); + $recipients = array(); + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; + } + break; -case 'attach': - - $attach = false; - if ($notification->diffusion_type === 'dest_entity') { - $tmp_entities = explode(',', $notification->attachfor_properties); - $attach = in_array($user_id, $tmp_entities); - } else { - $entities = "'". str_replace(",", "','", $notification->attachfor_properties) . "'"; - $query = "SELECT user_id" - . " FROM users_entities" - . " WHERE entity_id in (".$entities.")" - . " AND user_id = ?"; - $dbAttach = new Database(); - $stmt = $dbAttach->query($query, array($user_id)); - if($stmt->rowCount() > 0) { - $attach = true; - } - } - break; + case 'attach': + $attach = false; + if ($notification->diffusion_type === 'dest_entity') { + $tmp_entities = explode(',', $notification->attachfor_properties); + $attach = in_array($user_id, $tmp_entities); + } else { + $entities = "'".str_replace(',', "','", $notification->attachfor_properties)."'"; + $query = 'SELECT user_id' + .' FROM users_entities' + .' WHERE entity_id in ('.$entities.')' + .' AND user_id = ?'; + $dbAttach = new Database(); + $stmt = $dbAttach->query($query, array($user_id)); + if ($stmt->rowCount() > 0) { + $attach = true; + } + } + break; } - -?> \ No newline at end of file diff --git a/modules/notifications/diffusion_types/group.php b/modules/notifications/diffusion_types/group.php index 3b4d4e4472e..25c96fe78d7 100755 --- a/modules/notifications/diffusion_types/group.php +++ b/modules/notifications/diffusion_types/group.php @@ -23,67 +23,32 @@ require_once 'core/core_tables.php'; require_once 'core/class/class_request.php'; require_once 'core/class/usergroups_controler.php'; -switch($request) { -case 'form_content': - $UsrGrpCtl = new usergroups_controler(); - $usergrouplist = $UsrGrpCtl->getAllUsergroups(); - - $form_content .= '<input type="hidden" name="'.$formId.'" id="'.$formId.'" value="group">'; - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_GROUP_DIFF_TYPE . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="'.$leftList.'[]" id="'.$leftList.'" size="7" ondblclick=\'moveclick(document.frmevent.elements["'.$leftList.'[]"],document.frmevent.elements["'.$rightList.'[]"]);\' multiple="multiple" >'; - foreach ($usergrouplist as $usergroup) { - $form_content .= '<option value="'.$usergroup->group_id.'" selected="selected" >'.$usergroup->group_desc.'</option>'; - } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["'.$leftList.'[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["'.$leftList.'[]"],document.frmevent.elements["'.$rightList.'[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["'.$rightList.'[]"],document.frmevent.elements["'.$leftList.'[]"]);selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="'.$rightList.'[]" id="'.$rightList.'" size="7" ondblclick=\'moveclick(document.frmevent.elements["'.$rightList.'[]"],document.frmevent.elements["'.$leftList.'"]);selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' multiple="multiple" >'; - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - break; - -case 'recipients': - $groups = "'". str_replace(",", "','", $notification->diffusion_properties) . "'"; - $query = "SELECT distinct us.*" - . " FROM usergroup_content ug " - . " LEFT JOIN users us ON us.user_id = ug.user_id" - . " WHERE ug.group_id in (".$groups.")"; - $dbRecipients = new Database(); - $stmt = $dbRecipients->query($query); - $recipients = array(); - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $groups = "'". str_replace(",", "','", $notification->attachfor_properties) . "'"; - $query = "SELECT user_id" - . " FROM usergroup_content" - . " WHERE group_id in (".$groups.")" - . " AND user_id = ?"; - $attach = false; - $dbAttach = new Database(); - $stmt = $dbAttach->query($query, array($user_id)); - if($stmt->rowCount() > 0) { - $attach = true; - } - break; +switch ($request) { + case 'recipients': + $groups = "'".str_replace(',', "','", $notification->diffusion_properties)."'"; + $query = 'SELECT distinct us.*' + .' FROM usergroup_content ug ' + .' LEFT JOIN users us ON us.user_id = ug.user_id' + .' WHERE ug.group_id in ('.$groups.')'; + $dbRecipients = new Database(); + $stmt = $dbRecipients->query($query); + $recipients = array(); + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; + } + break; + case 'attach': + $groups = "'".str_replace(',', "','", $notification->attachfor_properties)."'"; + $query = 'SELECT user_id' + .' FROM usergroup_content' + .' WHERE group_id in ('.$groups.')' + .' AND user_id = ?'; + $attach = false; + $dbAttach = new Database(); + $stmt = $dbAttach->query($query, array($user_id)); + if ($stmt->rowCount() > 0) { + $attach = true; + } + break; } - - diff --git a/modules/notifications/diffusion_types/note_copy_list.php b/modules/notifications/diffusion_types/note_copy_list.php deleted file mode 100755 index 4751fb31094..00000000000 --- a/modules/notifications/diffusion_types/note_copy_list.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php - -/* -* Copyright 2008-2015 Maarch -* -* This file is part of Maarch Framework. -* -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. -*/ - -switch ($request) { -case 'form_content': -//Affichage du formulaire/interface dans l'administration des notification => Envoi Ajax - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_COPY_LIST_DIFF_TYPE . '</p>'; - break; - -case 'recipients': - $query = "SELECT distinct us.* " - . " FROM listinstance li JOIN users us ON li.item_id = us.user_id " - . " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id " - . " WHERE notes.coll_id = 'letterbox_coll' AND notes.id = ? AND item_type='user_id' AND item_mode = 'cc'" - . " AND li.item_id != notes.user_id"; - - $dbRecipients = new Database(); - $stmt = $dbRecipients->query($query, array($event->record_id)); - $recipients = array(); - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; -} -?> diff --git a/modules/notifications/diffusion_types/note_dest_user.php b/modules/notifications/diffusion_types/note_dest_user.php deleted file mode 100755 index d8340f5088d..00000000000 --- a/modules/notifications/diffusion_types/note_dest_user.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php - -/* -* Copyright 2008-2015 Maarch -* -* This file is part of Maarch Framework. -* -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. -*/ - -switch ($request) { -case 'form_content': - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_DEST_USER_DIFF_TYPE . '</p>'; - break; - -case 'recipients': - $query = "SELECT distinct us.* " - . " FROM listinstance li JOIN users us ON li.item_id = us.user_id " - . " JOIN notes ON notes.coll_id = li.coll_id AND notes.identifier = li.res_id " - . " WHERE notes.coll_id = 'letterbox_coll' AND notes.id = ? AND li.item_mode = 'dest'" - . " AND li.item_id != notes.user_id"; - $dbRecipients = new Database(); - $stmt = $dbRecipients->query($query, array($event->record_id)); - $recipients = array(); - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; - -case 'attach': - $attach = false; - break; - -} -?> diff --git a/modules/notifications/diffusion_types/user.php b/modules/notifications/diffusion_types/user.php index d66e0574a9e..bf2e2369322 100755 --- a/modules/notifications/diffusion_types/user.php +++ b/modules/notifications/diffusion_types/user.php @@ -1,86 +1,43 @@ <?php +/** +* Copyright Maarch since 2008 under licence GPLv3. +* See LICENCE.txt file at the root folder for more details. +* This file is part of Maarch software. -/* -* Copyright 2008-2015 Maarch * -* This file is part of Maarch Framework. +* @brief user * -* Maarch Framework is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* Maarch Framework is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with Maarch Framework. If not, see <http://www.gnu.org/licenses/>. +* @author dev <dev@maarch.org> +* @ingroup notifications */ - require_once 'core/core_tables.php'; require_once 'core/class/class_request.php'; require_once 'core/class/users_controler.php'; -switch($request) { -case 'form_content': - //Recuperer l ensemble des utilisateurs valides - $usrCtl = new users_controler(); - $userslist = $usrCtl->getAllUsers('order by lastname'); - - $form_content .= '<input type="hidden" name="'.$formId.'" id="'.$formId.'" value="user">'; - $form_content .= '<p class="sstit">' . _NOTIFICATIONS_USER_DIFF_TYPE . '</p>'; - $form_content .= '<table>'; - $form_content .= '<tr>'; - $form_content .= '<td>'; - $form_content .= '<select name="'.$leftList.'[]" id="'.$leftList.'" size="7" ondblclick=\'moveclick(document.frmevent.elements["'.$leftList.'[]"],document.frmevent.elements["'.$rightList.'[]"]);\' multiple="multiple" >'; - foreach ($userslist as $user){ - $form_content .= '<option value="'.$user->user_id.'" selected="selected" >'.$user->lastname.' '.$user->firstname.'</option>'; - } - - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["'.$leftList.'[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<input type="button" class="button" value="'._ADD.'>>" onclick=\'Move(document.frmevent.elements["'.$leftList.'[]"],document.frmevent.elements["'.$rightList.'[]"]);\' />'; - $form_content .= '<br />'; - $form_content .= '<br />'; - $form_content .= '<input type="button" class="button" value="<<'._REMOVE.'" onclick=\'Move(document.frmevent.elements["'.$rightList.'[]"],document.frmevent.elements["'.$leftList.'[]"]);selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' />'; - $form_content .= '</td>'; - $form_content .= '<td>'; - $form_content .= '<select name="'.$rightList.'[]" id="'.$rightList.'" size="7" ondblclick=\'moveclick(document.frmevent.elements["'.$rightList.'[]"],document.frmevent.elements["'.$leftList.'"]);selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' multiple="multiple" >'; - $form_content .= '</select><br/>'; - $form_content .= '<em><a href=\'javascript:selectall(document.forms["frmevent"].elements["'.$rightList.'[]"]);\' >'._SELECT_ALL.'</a></em>'; - $form_content .= '</td>'; - $form_content .= '</tr>'; - $form_content .= '</table>'; - - break; - -case 'recipients': - $users = "'". str_replace(",", "','", $notification->diffusion_properties) . "'"; - $query = "SELECT us.*" - . " FROM users us" - . " WHERE us.user_id in (".$users.")"; - $dbRecipients = new Database(); - $stmt = $dbRecipients->query($query); - $recipients = array(); - while($recipient = $stmt->fetchObject()) { - $recipients[] = $recipient; - } - break; +switch ($request) { + case 'recipients': + $users = "'".str_replace(',', "','", $notification->diffusion_properties)."'"; + $query = 'SELECT us.*' + .' FROM users us' + .' WHERE us.user_id in ('.$users.')'; + $dbRecipients = new Database(); + $stmt = $dbRecipients->query($query); + $recipients = array(); + while ($recipient = $stmt->fetchObject()) { + $recipients[] = $recipient; + } + break; -case 'attach': - $users = "'". str_replace(",", "','", (string)$notification->attachfor_properties) . "'"; - $query = "SELECT user_id" - . " FROM users" - . " WHERE '".$user_id."' in (".$users.")"; - $attach = false; - $dbAttach = new Database(); - $stmt = $dbAttach->query($query); - if($stmt->rowCount() > 0) { - $attach = true; - } - break; + case 'attach': + $users = "'".str_replace(',', "','", (string) $notification->attachfor_properties)."'"; + $query = 'SELECT user_id' + .' FROM users' + ." WHERE '".$user_id."' in (".$users.')'; + $attach = false; + $dbAttach = new Database(); + $stmt = $dbAttach->query($query); + if ($stmt->rowCount() > 0) { + $attach = true; + } + break; } diff --git a/modules/notifications/manage_notifications.php b/modules/notifications/manage_notifications.php index 36f288d35d6..c38ad01bedf 100755 --- a/modules/notifications/manage_notifications.php +++ b/modules/notifications/manage_notifications.php @@ -8,7 +8,7 @@ if ($mode == 'list') { $notifsList['title'], 'notification_sid', 'manage_notifications_controler&mode=list', - 'notifications','notification_sid', + 'notifications', 'notification_sid', true, $notifsList['page_name_up'], $notifsList['page_name_val'], @@ -36,175 +36,158 @@ if ($mode == 'list') { echo _MODIFY_NOTIF; } elseif ($mode == 'add') { echo _ADD_NOTIF; - }?> + } ?> </h1> <div id="inner_content" class="clearfix" align="center"> <?php if ($state == false) { - echo '<br /><br /><br /><br />' . _NOTIFICATION_ID . ' ' . $_SESSION['m_admin']['notification']['notification_sid'] . ' ' . _UNKNOWN - . '<br /><br /><br /><br />'; - } else {?> + echo '<br /><br /><br /><br />'._NOTIFICATION_ID.' '.$_SESSION['m_admin']['notification']['notification_sid'].' '._UNKNOWN + .'<br /><br /><br /><br />'; + } else { + ?> <div class="block"> <form name="frmevent" id="frmevent" method="post" action="<?php - echo $_SESSION['config']['businessappurl'] . 'index.php?display=true' - . '&module=notifications&page=manage_notifications_controler&mode=' - . $mode;?>" class="forms addforms"> + echo $_SESSION['config']['businessappurl'].'index.php?display=true' + .'&module=notifications&page=manage_notifications_controler&mode=' + .$mode; ?>" class="forms addforms"> <input type="hidden" name="display" value="true" /> <input type="hidden" name="admin" value="notifications" /> <input type="hidden" name="page" value="manage_notifications_controler" /> - <input type="hidden" name="mode" value="<?php functions::xecho($mode);?>" /> + <input type="hidden" name="mode" value="<?php functions::xecho($mode); ?>" /> - <input type="hidden" name="notification_sid" id="notification_sid" value="<?php functions::xecho($_SESSION['m_admin']['notification']['notification_sid']);?>" /> + <input type="hidden" name="notification_sid" id="notification_sid" value="<?php functions::xecho($_SESSION['m_admin']['notification']['notification_sid']); ?>" /> <input type="hidden" name="order" id="order" value="<?php - functions::xecho($_REQUEST['order']);?>" /> + functions::xecho($_REQUEST['order']); ?>" /> <input type="hidden" name="order_field" id="order_field" value="<?php - functions::xecho($_REQUEST['order_field']);?>" /> + functions::xecho($_REQUEST['order_field']); ?>" /> <input type="hidden" name="what" id="what" value="<?php - functions::xecho($_REQUEST['what']);?>" /> + functions::xecho($_REQUEST['what']); ?>" /> <input type="hidden" name="start" id="start" value="<?php - functions::xecho($_REQUEST['start']);?>" /> + functions::xecho($_REQUEST['start']); ?>" /> <p> - <label for="label"><?php echo _NOTIFICATION_ID;?> : </label> + <label for="label"><?php echo _NOTIFICATION_ID; ?> : </label> <input name="notification_id" type="text" id="notification_id" value="<?php echo functions::show_str( $_SESSION['m_admin']['notification']['notification_id'] - );?>"/> + ); ?>"/> </p> <p> - <label for="label"><?php echo _DESC;?> : </label> + <label for="label"><?php echo _DESC; ?> : </label> <textarea name="description" cols="80" rows="2" id="description"><?php echo functions::show_str( $_SESSION['m_admin']['notification']['description'] - );?></textarea> + ); ?></textarea> </p> <p> - <label><?php echo _ENABLED;?> : </label> + <label><?php echo _ENABLED; ?> : </label> <input type="radio" class="check" name="is_enabled" value="true" <?php if (isset($_SESSION['m_admin']['notification']['is_enabled']) - && $_SESSION['m_admin']['notification']['is_enabled'] == "Y" + && $_SESSION['m_admin']['notification']['is_enabled'] == 'Y' ) { ?> checked="checked"<?php - } - ?> /><?php echo _YES;?> + } ?> /><?php echo _YES; ?> <input type="radio" class="check" name="is_enabled" value="false" <?php if (!isset($_SESSION['m_admin']['notification']['is_enabled']) - || (!($_SESSION['m_admin']['notification']['is_enabled'] == "Y") + || (!($_SESSION['m_admin']['notification']['is_enabled'] == 'Y') || $_SESSION['m_admin']['notification']['is_enabled'] == '') ) { ?> checked="checked"<?php - } - ?> /><?php echo _NO;?> + } ?> /><?php echo _NO; ?> </p> <p> - <label for="label"><?php echo _EVENT;?> : </label> + <label for="label"><?php echo _EVENT; ?> : </label> <select name="event_id" id="event_id"> - <option value=""><?php echo _SELECT_EVENT_TYPE;?></option> - <optgroup label="<?php echo _ACTIONS;?>"> + <option value=""><?php echo _SELECT_EVENT_TYPE; ?></option> + <optgroup label="<?php echo _ACTIONS; ?>"> <?php - foreach($actions_list as $this_action){ - ?><option value="<?php functions::xecho($this_action->id);?>" + foreach ($actions_list as $this_action) { + ?><option value="<?php functions::xecho($this_action->id); ?>" <?php - if($_SESSION['m_admin']['notification']['event_id'] + if ($_SESSION['m_admin']['notification']['event_id'] == $this_action->id) { echo 'selected="selected"'; - }?>><?php functions::xecho($this_action->label_action); - ?></option><?php + } ?>><?php functions::xecho($this_action->label_action); ?></option><?php } - //Récupération des éléments systèmes - ?></optgroup><?php - $newarray = array_keys($_SESSION['notif_events']); - ?><optgroup label="<?php echo _SYSTEM;?>"><?php - foreach($_SESSION['notif_events'] as $event_type_id => $event_type_label){ - ?><option value="<?php functions::xecho($event_type_id);?>" + //Récupération des éléments systèmes ?></optgroup><?php + $newarray = array_keys($_SESSION['notif_events']); ?><optgroup label="<?php echo _SYSTEM; ?>"><?php + foreach ($_SESSION['notif_events'] as $event_type_id => $event_type_label) { + ?><option value="<?php functions::xecho($event_type_id); ?>" <?php - if($_SESSION['m_admin']['notification']['event_id'] + if ($_SESSION['m_admin']['notification']['event_id'] == $event_type_id) { echo 'selected="selected"'; - }?>><?php functions::xecho($event_type_label); - ?></option><?php - } - ?> + } ?>><?php functions::xecho($event_type_label); ?></option><?php + } ?> </optgroup> </select> </p> <p style="display:none"> - <label><?php echo _NOTIFICATION_MODE;?> :</label> + <label><?php echo _NOTIFICATION_MODE; ?> :</label> <input type="radio" name="notification_mode" value="EMAIL" onClick="javascript:window.document.getElementById('template_div').style.display = 'block'; window.document.getElementById('rss_url_div').style.display = 'none';" <?php - if ($_SESSION['m_admin']['notification']['notification_mode'] == '' + if ($_SESSION['m_admin']['notification']['notification_mode'] == '' || $_SESSION['m_admin']['notification']['notification_mode'] == 'EMAIL' ) { - echo 'checked="checked"'; - }?>/> <?php echo _EMAIL;?> + echo 'checked="checked"'; + } ?>/> <?php echo _EMAIL; ?> <input type="radio" name="notification_mode" value="RSS" onClick="javascript:window.document.getElementById('rss_url_div').style.display = 'block'; window.document.getElementById('template_div').style.display = 'none';" <?php if ($_SESSION['m_admin']['notification']['notification_mode'] == 'RSS' ) { - echo 'checked="checked"'; - }?>/> <?php echo _RSS;?> + echo 'checked="checked"'; + } ?>/> <?php echo _RSS; ?> </p> <div id="template_div" name="template_div"> <p> - <label for="label"><?php echo _TEMPLATE;?> : </label> + <label for="label"><?php echo _TEMPLATE; ?> : </label> <select name="template_id" id="template_id"> - <option value=""><?php echo _SELECT_TEMPLATE;?></option> + <option value=""><?php echo _SELECT_TEMPLATE; ?></option> <?php - foreach($templates_list as $template){ + foreach ($templates_list as $template) { if ($template['TYPE'] === 'HTML' && ($template['TARGET'] == 'notifications' || $template['TARGET'] == '')) { - ?><option value="<?php functions::xecho($template['ID']);?>" + ?><option value="<?php functions::xecho($template['ID']); ?>" <?php - if($_SESSION['m_admin']['notification']['template_id'] + if ($_SESSION['m_admin']['notification']['template_id'] == $template['ID']) { echo 'selected="selected"'; - }?>><?php functions::xecho($template['LABEL']); - ?></option><?php + } ?>><?php functions::xecho($template['LABEL']); ?></option><?php } - } - ?> + } ?> </select> </p> </div> - <div id="rss_url_div" name="rss_url_div" style="width:600px; align=left; display:none;" > - <p> - <label for="label"><?php echo _RSS_URL_TEMPLATE;?> : </label> - <textarea name="rss_url_template" type="text" id="rss_url_template" style="width:340px; height=60px"> - <?php - echo functions::show_str( - $_SESSION['m_admin']['notification']['rss_url_template'] - ); - ?></textarea> - </p> - </div> <p> - <label for="status"><?php echo _DIFFUSION_TYPE;?> : </label> + <label for="status"><?php echo _DIFFUSION_TYPE; ?> : </label> <select name="diffusion_type" id="status" onchange="change_properties_box( this.options[this.selectedIndex].value, - '<?php echo $_SESSION['config']['businessappurl'];?>index.php?display=true&module=notifications&page=load_diffusiontype_formcontent', + '<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=notifications&page=load_diffusiontype_formcontent', 'diff_type_div', 'notifications', '');clear_attach_type();set_attach_type(this.options[this.selectedIndex].value)"> - <option value=""><?php echo _SELECT_DIFFUSION_TYPE;?></option> + <option value=""><?php echo _SELECT_DIFFUSION_TYPE; ?></option> <?php - foreach($diffusion_types as $this_diffusion){ ?> - <option value="<?php functions::xecho($this_diffusion->id);?>" + foreach ($diffusion_types as $this_diffusion) { + ?> + <option value="<?php functions::xecho($this_diffusion->id); ?>" <?php - if(trim($_SESSION['m_admin']['notification']['diffusion_type']) == trim($this_diffusion->id)) { + if (trim($_SESSION['m_admin']['notification']['diffusion_type']) == trim($this_diffusion->id)) { echo 'selected="selected"'; - }?> + } ?> > <?php functions::xecho($this_diffusion->label); ?> </option> - <?php } ?> + <?php + } ?> </select> </p> @@ -216,165 +199,153 @@ if ($mode == 'list') { </div> <p></p> <p> - <label for="attach_for_type"><?php echo _ATTACH_MAIL_FILE;?> : </label> + <label for="attach_for_type"><?php echo _ATTACH_MAIL_FILE; ?> : </label> <select name="attach_for_type" id="status" onchange="change_properties_box( this.options[this.selectedIndex].value, - '<?php echo $_SESSION['config']['businessappurl'];?>index.php?display=true&module=notifications&page=load_attachfortype_formcontent', + '<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=notifications&page=load_attachfortype_formcontent', 'attach_for_div', 'notifications', '');"> - <option tag="voidAttach" value=""><?php echo _NEVER;?></option> + <option tag="voidAttach" value=""><?php echo _NEVER; ?></option> <?php - foreach($diffusion_types as $this_diffusion){ - if( - $this_diffusion->id != 'dest_user' + foreach ($diffusion_types as $this_diffusion) { + if ( + $this_diffusion->id != 'dest_user' && $this_diffusion->id != 'copy_list' && $this_diffusion->id != 'dest_entity' && $this_diffusion->id != 'note_dest_user' && $this_diffusion->id != 'note_copy_list' ) { - ?><option tag="attach" value="<?php functions::xecho($this_diffusion->id);?>" + ?><option tag="attach" value="<?php functions::xecho($this_diffusion->id); ?>" <?php - if(trim($_SESSION['m_admin']['notification']['attachfor_type']) - == trim($this_diffusion->id)) { - echo 'selected="selected"'; - }?>><?php functions::xecho($this_diffusion->label); - ?></option><?php - } - } - ?> + if (trim($_SESSION['m_admin']['notification']['attachfor_type']) + == trim($this_diffusion->id)) { + echo 'selected="selected"'; + } ?>><?php functions::xecho($this_diffusion->label); ?></option><?php + } + } ?> </select> </p> <div id="attach_for_div" class="scroll_div" style="height:200px;width:600px;border:1px solid;"> <!-- div for attachment options --> - <p class="sstit"> <?php echo _NO_ATTACHMENT_WITH_NOTIFICATION;?></p> + <p class="sstit"> <?php echo _NO_ATTACHMENT_WITH_NOTIFICATION; ?></p> </div> <p class="buttons"> <?php - if ($mode == 'up') {?> + if ($mode == 'up') { + ?> <input type="submit" class="button" name="notif_submit" value= - "<?php echo _VALIDATE;?>" /> + "<?php echo _VALIDATE; ?>" /> <?php - } elseif ($mode == 'add') {?> + } elseif ($mode == 'add') { + ?> <input type="submit" class="button" name="notif_submit" value= - "<?php echo _ADD;?>" /> + "<?php echo _ADD; ?>" /> <?php - } - ?> + } ?> <input type="button" class="button" name="cancel" value="<?php - echo _CANCEL;?>" onclick="javascript:window.location.href='<?php - echo $_SESSION['config']['businessappurl']; - ?>index.php?page=manage_notifications_controler&mode=list&module=notifications'"/> + echo _CANCEL; ?>" onclick="javascript:window.location.href='<?php + echo $_SESSION['config']['businessappurl']; ?>index.php?page=manage_notifications_controler&mode=list&module=notifications'"/> <?php - $filename = "notification"; - if (isset($_SESSION['custom_override_id']) && $_SESSION['custom_override_id']<>"") { - $filename.="_".str_replace(" ", "", $_SESSION['custom_override_id']); + $filename = 'notification'; + if (isset($_SESSION['custom_override_id']) && $_SESSION['custom_override_id'] != '') { + $filename .= '_'.str_replace(' ', '', $_SESSION['custom_override_id']); } - $filename.="_".$notification_sid.".sh"; - - if ($_SESSION['custom_override_id'] <> '') { - $pathToFolow = $_SESSION['config']['corepath'] . 'custom/'.$_SESSION['custom_override_id'] . '/'; + $filename .= '_'.$notification_sid.'.sh'; + + if ($_SESSION['custom_override_id'] != '') { + $pathToFolow = $_SESSION['config']['corepath'].'custom/'.$_SESSION['custom_override_id'].'/'; } else { $pathToFolow = $_SESSION['config']['corepath']; } - - if ($mode == 'up' && PHP_OS == "Linux" && !file_exists($pathToFolow.'modules/notifications/batch/scripts/'.$filename)) {?> - <input class="button" type="button" name="create_notif_script" id="create_notif_script" value="<?php echo _CREATE_NOTIF_SCRIPT;?>" - onclick="createNotifScript('<?php echo $_SESSION['config']['businessappurl']; - ?>index.php?display=true&page=create_notif_script&module=notifications', '<?php functions::xecho($_SESSION['m_admin']['notification']['notification_sid']);?>', '<?php echo $_SESSION['m_admin']['notification']['notification_id'];?>')"/> + + if ($mode == 'up' && PHP_OS == 'Linux' && !file_exists($pathToFolow.'modules/notifications/batch/scripts/'.$filename)) { + ?> + <input class="button" type="button" name="create_notif_script" id="create_notif_script" value="<?php echo _CREATE_NOTIF_SCRIPT; ?>" + onclick="createNotifScript('<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&page=create_notif_script&module=notifications', '<?php functions::xecho($_SESSION['m_admin']['notification']['notification_sid']); ?>', '<?php echo $_SESSION['m_admin']['notification']['notification_id']; ?>')"/> <?php - } - ?> + } ?> </p> </form > </div> <?php - } - ?></div><?php - - // Manage notification mode - if ($_SESSION['m_admin']['notification']['notification_mode'] == 'EMAIL' - || $_SESSION['m_admin']['notification']['notification_mode'] == '') { - ?> + } ?></div><?php + + // Manage notification mode + if ($_SESSION['m_admin']['notification']['notification_mode'] == 'EMAIL' + || $_SESSION['m_admin']['notification']['notification_mode'] == '') { + ?> <script language="javascript"> window.document.getElementById('rss_url_div').style.display = 'none'; window.document.getElementById('template_div').style.display = 'block'; </script> - <?php - } elseif ($_SESSION['m_admin']['notification']['notification_mode'] == 'RSS') { - ?> + <?php + } elseif ($_SESSION['m_admin']['notification']['notification_mode'] == 'RSS') { + ?> <script language="javascript"> window.document.getElementById('rss_url_div').style.display = 'block'; window.document.getElementById('template_div').style.display = 'none'; </script> <?php - } - // Manage Diffusion type Div & content - if ($_SESSION['m_admin']['notification']['diffusion_type'] <> '') - { - /*First Launch */ - ?> + } + // Manage Diffusion type Div & content + if ($_SESSION['m_admin']['notification']['diffusion_type'] != '') { + /*First Launch */ ?> <script language="javascript"> change_properties_box( - '<?php functions::xecho($_SESSION['m_admin']['notification']['diffusion_type']);?>', - '<?php echo $_SESSION['config']['businessappurl'];?>index.php?display=true&module=notifications&page=load_diffusiontype_formcontent', + '<?php functions::xecho($_SESSION['m_admin']['notification']['diffusion_type']); ?>', + '<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=notifications&page=load_diffusiontype_formcontent', 'diff_type_div', 'notifications', ''); </script> <?php - if ($_SESSION['m_admin']['notification']['diffusion_type'] <> '') - { + if ($_SESSION['m_admin']['notification']['diffusion_type'] != '') { //Loading Extra Javascript : - require_once 'modules' . DIRECTORY_SEPARATOR . 'notifications' . DIRECTORY_SEPARATOR - . 'class' . DIRECTORY_SEPARATOR . 'diffusion_type_controler.php'; + require_once 'modules'.DIRECTORY_SEPARATOR.'notifications'.DIRECTORY_SEPARATOR + .'class'.DIRECTORY_SEPARATOR.'diffusion_type_controler.php'; $Type = new diffusion_type_controler(); - $dType = $Type->get($_SESSION['m_admin']['notification']['diffusion_type']); - ?> + $dType = $Type->get($_SESSION['m_admin']['notification']['diffusion_type']); ?> <script language="javascript"> setTimeout(function(){loadDiffusionProperties( - '<?php functions::xecho($_SESSION['m_admin']['notification']['diffusion_type']);?>', - '<?php echo $_SESSION['config']['businessappurl'];?>index.php?display=true&module=notifications&page=load_diffusionproperties_formcontent' + '<?php functions::xecho($_SESSION['m_admin']['notification']['diffusion_type']); ?>', + '<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=notifications&page=load_diffusionproperties_formcontent' )},500); </script> <?php } } - - // Manage Attachment Div & content - if ($_SESSION['m_admin']['notification']['attachfor_type'] <> '') - { - /*First Launch */ - ?> + + // Manage Attachment Div & content + if ($_SESSION['m_admin']['notification']['attachfor_type'] != '') { + /*First Launch */ ?> <script language="javascript"> change_properties_box( - '<?php functions::xecho($_SESSION['m_admin']['notification']['attachfor_type']);?>', - '<?php echo $_SESSION['config']['businessappurl'];?>index.php?display=true&module=notifications&page=load_attachfortype_formcontent', + '<?php functions::xecho($_SESSION['m_admin']['notification']['attachfor_type']); ?>', + '<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=notifications&page=load_attachfortype_formcontent', 'attach_for_div', 'notifications', ''); </script> <?php - if ($_SESSION['m_admin']['notification']['attachfor_type'] <> '') - { + if ($_SESSION['m_admin']['notification']['attachfor_type'] != '') { //Loading Extra Javascript : - require_once 'modules' . DIRECTORY_SEPARATOR . 'notifications' . DIRECTORY_SEPARATOR - . 'class' . DIRECTORY_SEPARATOR . 'diffusion_type_controler.php'; + require_once 'modules'.DIRECTORY_SEPARATOR.'notifications'.DIRECTORY_SEPARATOR + .'class'.DIRECTORY_SEPARATOR.'diffusion_type_controler.php'; $Type = new diffusion_type_controler(); $dType = $Type->get($_SESSION['m_admin']['notification']['diffusion_type']); - //include_once ($dType->script); - ?> + //include_once ($dType->script); ?> <script language="javascript"> setTimeout(function () {loadAttachforProperties( - '<?php functions::xecho($_SESSION['m_admin']['notification']['attachfor_type']);?>', - '<?php echo $_SESSION['config']['businessappurl'];?>index.php?display=true&module=notifications&page=load_attachforproperties_formcontent', + '<?php functions::xecho($_SESSION['m_admin']['notification']['attachfor_type']); ?>', + '<?php echo $_SESSION['config']['businessappurl']; ?>index.php?display=true&module=notifications&page=load_attachforproperties_formcontent', 'attach_for_div' )},500); </script> diff --git a/modules/notifications/manage_notifications_controler.php b/modules/notifications/manage_notifications_controler.php index cdddbdc11d2..c4c36dcd628 100755 --- a/modules/notifications/manage_notifications_controler.php +++ b/modules/notifications/manage_notifications_controler.php @@ -9,24 +9,22 @@ if (isset($_REQUEST['mode']) && !empty($_REQUEST['mode'])) { $mode = $_REQUEST['mode']; } - - -try{ +try { require_once 'core/class/ActionControler.php'; require_once 'core/class/ObjectControlerAbstract.php'; require_once 'core/class/ObjectControlerIF.php'; - require_once 'modules/templates/class/templates_controler.php' ; + require_once 'modules/templates/class/templates_controler.php'; require_once 'modules/notifications/class/notifications_controler.php'; require_once 'modules/notifications/class/diffusion_type_controler.php'; require_once 'modules/notifications/class/class_schedule_notifications.php'; - + if ($mode == 'list') { - require_once 'core/class/class_request.php' ; - require_once 'apps' . DIRECTORY_SEPARATOR - . $_SESSION['config']['app_id'] . DIRECTORY_SEPARATOR - . 'class' . DIRECTORY_SEPARATOR . 'class_list_show.php' ; - }else if($mode == 'add' || $mode == 'up' || $mode == 'del'){ - require_once 'core/class/class_request.php' ; + require_once 'core/class/class_request.php'; + require_once 'apps'.DIRECTORY_SEPARATOR + .$_SESSION['config']['app_id'].DIRECTORY_SEPARATOR + .'class'.DIRECTORY_SEPARATOR.'class_list_show.php'; + } elseif ($mode == 'add' || $mode == 'up' || $mode == 'del') { + require_once 'core/class/class_request.php'; } } catch (Exception $e) { functions::xecho($e->getMessage()); @@ -38,7 +36,7 @@ $actions_list = $al->getAllActions(); //Get list of aff availables status $select[STATUS_TABLE] = array(); - array_push($select[STATUS_TABLE], 'id', 'label_status','img_filename'); + array_push($select[STATUS_TABLE], 'id', 'label_status', 'img_filename'); $request = new request(); $where = ''; $what = ''; @@ -55,21 +53,18 @@ $diffusion_types = $dt->getAllDiffusion(); $tp = new templates_controler(); $templates_list = $tp->getAllTemplatesForSelect(); - if (isset($_REQUEST['id']) && !empty($_REQUEST['id'])) { $notification_sid = $_REQUEST['id']; } - if (isset($_REQUEST['notif_submit'])) { // Action to do with db validate_notif_submit(); - } else { // Display to do $state = true; switch ($mode) { - case 'up' : + case 'up': $state = display_up($notification_sid); $_SESSION['service_tag'] = 'notif_init'; core_tools::execute_modules_services( @@ -77,7 +72,7 @@ if (isset($_REQUEST['notif_submit'])) { ); location_bar_management($mode); break; - case 'add' : + case 'add': display_add(); $_SESSION['service_tag'] = 'notif_init'; core_tools::execute_modules_services( @@ -85,30 +80,30 @@ if (isset($_REQUEST['notif_submit'])) { ); location_bar_management($mode); break; - case 'del' : + case 'del': display_del($notification_sid); break; - case 'list' : + case 'list': $notifsList = display_list(); location_bar_management($mode); // print_r($statusList); exit(); break; } - include('manage_notifications.php'); + include 'manage_notifications.php'; } /** - * Management of the location bar + * Management of the location bar. */ function location_bar_management($mode) { - $pageLabels = array('add' => _ADDITION, - 'up' => _MODIFICATION, - 'list' => _MANAGE_NOTIFS + $pageLabels = array('add' => _ADDITION, + 'up' => _MODIFICATION, + 'list' => _MANAGE_NOTIFS, ); $pageIds = array('add' => 'notif_add', 'up' => 'notif_up', - 'list' => 'notif_list' + 'list' => 'notif_list', ); $init = false; if (isset($_REQUEST['reinit']) && $_REQUEST['reinit'] == 'true') { @@ -122,8 +117,8 @@ function location_bar_management($mode) $level = $_REQUEST['level']; } - $pagePath = $_SESSION['config']['businessappurl'] . 'index.php?page=' - . 'manage_notifications_controler&module=notifications&mode=' . $mode ; + $pagePath = $_SESSION['config']['businessappurl'].'index.php?page=' + .'manage_notifications_controler&module=notifications&mode='.$mode; $pageLabel = $pageLabels[$mode]; $pageId = $pageIds[$mode]; $ct = new core_tools(); @@ -131,12 +126,12 @@ function location_bar_management($mode) } /** - * Initialize session parameters for update display - * @param String $statusId + * Initialize session parameters for update display. + * + * @param string $statusId */ function display_up($notification_sid) { - $notifCtrl = new notifications_controler(); $state = true; $notif = $notifCtrl->get($notification_sid); @@ -144,14 +139,15 @@ function display_up($notification_sid) if (empty($notif)) { $state = false; } else { - //var_dump($notif); + //var_dump($notif); put_in_session('notification', $notif->getArray()); } + return $state; } /** - * Initialize session parameters for add display + * Initialize session parameters for add display. */ function display_add() { @@ -161,18 +157,18 @@ function display_add() } /** - * Initialize session parameters for list display + * Initialize session parameters for list display. */ -function display_list() { - - if (PHP_OS == "Linux") { - ?> +function display_list() +{ + if (PHP_OS == 'Linux') { + ?> <table> </table> <table width="100%"> <tr> <td align="right"> - <input class="button" type="button" value="<?php echo _SCHEDULE_NOTIFICATIONS;?>" onclick="window.location.href='<?php echo $_SESSION['config']['businessappurl'] . 'index.php?page=schedule_notifications&module=notifications'?>'"/> + <input class="button" type="button" value="<?php echo _SCHEDULE_NOTIFICATIONS; ?>" onclick="window.location.href='<?php echo $_SESSION['config']['businessappurl'].'index.php?page=schedule_notifications&module=notifications'; ?>'"/> </td> </tr> </table> @@ -194,8 +190,8 @@ function display_list() { if (isset($_REQUEST['what'])) { $what = $_REQUEST['what']; } - $where .= " (lower(description) like lower(:what) or lower(notification_id) like lower(:what)) "; - $arrayPDO = array(":what" => $what."%"); + $where .= ' (lower(description) like lower(:what) or lower(notification_id) like lower(:what)) '; + $arrayPDO = array(':what' => $what.'%'); // Checking order and order_field values $order = 'asc'; @@ -213,9 +209,9 @@ function display_list() { $tab = $request->PDOselect( $select, $where, $arrayPDO, $orderstr, $_SESSION['config']['databasetype'] ); - //$request->show(); - - for ($i=0;$i<count($tab);$i++) { + //$request->show(); + + for ($i = 0; $i < count($tab); ++$i) { foreach ($tab[$i] as &$item) { switch ($item['column']) { case 'notification_sid': @@ -238,68 +234,69 @@ function display_list() { } $_SESSION['m_admin']['init'] = true; $result = array( - 'tab' => $tab, - 'what' => $what, - 'page_name' => 'manage_notifications_controler&mode=list', - 'page_name_add' => 'manage_notifications_controler&mode=add', - 'page_name_up' => 'manage_notifications_controler&mode=up', - 'page_name_del' => 'manage_notifications_controler&mode=del', - 'page_name_val' => '', - 'page_name_ban' => '', - 'label_add' => _ADD_NOTIF, - 'title' => _NOTIFS_LIST . ' : ' . $i, + 'tab' => $tab, + 'what' => $what, + 'page_name' => 'manage_notifications_controler&mode=list', + 'page_name_add' => 'manage_notifications_controler&mode=add', + 'page_name_up' => 'manage_notifications_controler&mode=up', + 'page_name_del' => 'manage_notifications_controler&mode=del', + 'page_name_val' => '', + 'page_name_ban' => '', + 'label_add' => _ADD_NOTIF, + 'title' => _NOTIFS_LIST.' : '.$i, 'autoCompletionArray' => array( - 'list_script_url' => - $_SESSION['config']['businessappurl'] - . 'index.php?display=true&module=notifications' - . '&page=manage_notifs_list_by_name', - 'number_to_begin' => 1 + 'list_script_url' => $_SESSION['config']['businessappurl'] + .'index.php?display=true&module=notifications' + .'&page=manage_notifs_list_by_name', + 'number_to_begin' => 1, ), - ); + return $result; } /** - * Delete given status if exists and initialize session parameters + * Delete given status if exists and initialize session parameters. + * * @param string $statusId */ -function display_del($notification_sid) { +function display_del($notification_sid) +{ $notifCtrl = new notifications_controler(); $notif = $notifCtrl->get($notification_sid); if (isset($notif)) { // Deletion $control = array(); - $params = array( 'log_status_del' => $_SESSION['history']['eventdel'], - 'databasetype' => $_SESSION['config']['databasetype'] + $params = array('log_status_del' => $_SESSION['history']['eventdel'], + 'databasetype' => $_SESSION['config']['databasetype'], ); $control = $notifCtrl->delete($notif, $params); - if (!empty($control['error']) && $control['error'] <> 1) { - $_SESSION['error'] = str_replace("#", "<br />", $control['error']); + if (!empty($control['error']) && $control['error'] != 1) { + $_SESSION['error'] = str_replace('#', '<br />', $control['error']); } else { $_SESSION['info'] = _NOTIF_DELETED.' : '.$notification_sid; - if (PHP_OS == "Linux") { + if (PHP_OS == 'Linux') { // delete scheduled notification - $filename = "notification"; - if (isset($_SESSION['custom_override_id']) && $_SESSION['custom_override_id']<>"") { - $filename.="_".str_replace(" ", "", $_SESSION['custom_override_id']); + $filename = 'notification'; + if (isset($_SESSION['custom_override_id']) && $_SESSION['custom_override_id'] != '') { + $filename .= '_'.str_replace(' ', '', $_SESSION['custom_override_id']); } - $filename.="_".$notification_sid.".sh"; + $filename .= '_'.$notification_sid.'.sh'; $scheduleNotification = new ScheduleNotifications(); $cronTab = $scheduleNotification->getCrontab(); $flagCron = false; - if ($_SESSION['custom_override_id'] <> '') { - $pathToFolow = $_SESSION['config']['corepath'] . 'custom/'.$_SESSION['custom_override_id'] . '/'; + if ($_SESSION['custom_override_id'] != '') { + $pathToFolow = $_SESSION['config']['corepath'].'custom/'.$_SESSION['custom_override_id'].'/'; } else { $pathToFolow = $_SESSION['config']['corepath']; } foreach ($cronTab as $key => $value) { - if($value['cmd'] == $pathToFolow.'modules/notifications/batch/scripts/'.$filename){ + if ($value['cmd'] == $pathToFolow.'modules/notifications/batch/scripts/'.$filename) { $cronTab[$key]['state'] = 'deleted'; $flagCron = true; break; @@ -309,17 +306,15 @@ function display_del($notification_sid) { if ($flagCron) { $scheduleNotification->saveCrontab($cronTab, true); } - - unlink($pathToFolow . 'modules/notifications/batch/scripts/' . $filename); + + unlink($pathToFolow.'modules/notifications/batch/scripts/'.$filename); } - } - ?><script type="text/javascript">window.top.location='<?php + } ?><script type="text/javascript">window.top.location='<?php echo $_SESSION['config']['businessappurl'] - . 'index.php?page=manage_notifications_controler&mode=list&module=' - . 'notifications&order=' . $_REQUEST['order'] . '&order_field=' - . $_REQUEST['order_field'] . '&start=' . $_REQUEST['start'] - . '&what=' . $_REQUEST['what']; - ?>';</script> + .'index.php?page=manage_notifications_controler&mode=list&module=' + .'notifications&order='.$_REQUEST['order'].'&order_field=' + .$_REQUEST['order_field'].'&start='.$_REQUEST['start'] + .'&what='.$_REQUEST['what']; ?>';</script> <?php exit(); } else { @@ -333,6 +328,7 @@ function display_del($notification_sid) { * NOTE: given item needs to be an array with at least 2 keys: * 'column' and 'value'. * NOTE: given item is modified consequently. + * * @param $item * @param $label * @param $size @@ -362,82 +358,82 @@ function format_item( /** * Validate a submit (add or up), - * up to saving object + * up to saving object. */ -function validate_notif_submit() { - $dType = new diffusion_type_controler(); - $diffType = array(); - $diffType = $dType->getAllDiffusion(); - +function validate_notif_submit() +{ + $dType = new diffusion_type_controler(); + $diffType = array(); + $diffType = $dType->getAllDiffusion(); + $notifCtrl = new notifications_controler(); $pageName = 'manage_notifications_controler'; $mode = $_REQUEST['mode']; $notifObj = new notifications(); - - if ($mode <> 'add'){ - $notifObj->notification_sid = $_REQUEST['notification_sid']; - } + + if ($mode != 'add') { + $notifObj->notification_sid = $_REQUEST['notification_sid']; + } $notifObj->notification_id = $_REQUEST['notification_id']; - $notifObj->description = $_REQUEST['description']; + $notifObj->description = $_REQUEST['description']; $notifObj->notification_mode = $_REQUEST['notification_mode']; $notifObj->event_id = $_REQUEST['event_id']; - $notifObj->rss_url_template = $_REQUEST['rss_url_template']; $notifObj->template_id = $_REQUEST['template_id']; $notifObj->is_enabled = $_REQUEST['is_enabled']; $notifObj->diffusion_type = $_REQUEST['diffusion_type']; $notifObj->attachfor_type = $_REQUEST['attachfor_type']; - - foreach($diffType as $loadedType) { - if ($loadedType->id == $notifObj->diffusion_type){ - if ($loadedType -> script <> '' && !empty($_REQUEST['diffusion_properties'])) { - $diffusion_properties_string = implode(',', $_REQUEST['diffusion_properties']); - } else { - $error .= 'System : Unable to load Require Script'; - } - } - if ($loadedType->id == $notifObj->attachfor_type){ - if ($loadedType -> script <> '' && !empty($_REQUEST['attachfor_properties'])) { - $attachfor_properties_string = implode(',', $_REQUEST['attachfor_properties']); - } else { - $error .= 'System : Unable to load Require Script'; - } - } - } - - $notifObj->diffusion_properties = (string)$diffusion_properties_string; - $notifObj->attachfor_properties = (string)$attachfor_properties_string; - + + foreach ($diffType as $loadedType) { + if ($loadedType->id == $notifObj->diffusion_type) { + if ($loadedType->script != '' && !empty($_REQUEST['diffusion_properties'])) { + $diffusion_properties_string = implode(',', $_REQUEST['diffusion_properties']); + } else { + $error .= 'System : Unable to load Require Script'; + } + } + if ($loadedType->id == $notifObj->attachfor_type) { + if ($loadedType->script != '' && !empty($_REQUEST['attachfor_properties'])) { + $attachfor_properties_string = implode(',', $_REQUEST['attachfor_properties']); + } else { + $error .= 'System : Unable to load Require Script'; + } + } + } + + $notifObj->diffusion_properties = (string) $diffusion_properties_string; + $notifObj->attachfor_properties = (string) $attachfor_properties_string; + $control = $notifCtrl->save($notifObj, $mode, $params); - if (!empty($control['error']) && $control['error'] <> 1) { + if (!empty($control['error']) && $control['error'] != 1) { // Error management depending of mode - $_SESSION['error'] = str_replace("#", "<br />", $control['error']); + $_SESSION['error'] = str_replace('#', '<br />', $control['error']); //put_in_session('event', $notif); - put_in_session('notification', $notifObj->getArray()); + put_in_session('notification', $notifObj->getArray()); switch ($mode) { case 'up': if (!empty($notifObj->notification_sid)) { header( - 'location: ' . $_SESSION['config']['businessappurl'] - . 'index.php?page=' . $pageName . '&mode=up&id=' - . $notifObj->notification_sid . '&module=notifications' + 'location: '.$_SESSION['config']['businessappurl'] + .'index.php?page='.$pageName.'&mode=up&id=' + .$notifObj->notification_sid.'&module=notifications' ); } else { header( - 'location: ' . $_SESSION['config']['businessappurl'] - . 'index.php?page=' . $pageName . '&mode=list&module=' - .'notifications&order=' . $status['order'] . '&order_field=' - . $status['order_field'] . '&start=' . $status['start'] - . '&what=' . $status['what'] + 'location: '.$_SESSION['config']['businessappurl'] + .'index.php?page='.$pageName.'&mode=list&module=' + .'notifications&order='.$status['order'].'&order_field=' + .$status['order_field'].'&start='.$status['start'] + .'&what='.$status['what'] ); } exit(); case 'add': header( - 'location: ' . $_SESSION['config']['businessappurl'] - . 'index.php?page=' . $pageName . '&mode=add&module=notifications' + 'location: '.$_SESSION['config']['businessappurl'] + .'index.php?page='.$pageName.'&mode=add&module=notifications' ); exit(); } @@ -447,57 +443,56 @@ function validate_notif_submit() { } else { $_SESSION['info'] = _NOTIF_MODIFIED; } - - if (PHP_OS == "Linux") { + + if (PHP_OS == 'Linux') { $ScheduleNotifications = new ScheduleNotifications(); $ScheduleNotifications->createScriptNotification($control['value'], $notifObj->notification_id); } unset($_SESSION['m_admin']); header( - 'location: ' . $_SESSION['config']['businessappurl'] - . 'index.php?page=' . $pageName . '&mode=list&module=notifications&order=' - . $status['order'] . '&order_field=' . $status['order_field'] - . '&start=' . $status['start'] . '&what=' . $status['what'] + 'location: '.$_SESSION['config']['businessappurl'] + .'index.php?page='.$pageName.'&mode=list&module=notifications&order=' + .$status['order'].'&order_field='.$status['order_field'] + .'&start='.$status['start'].'&what='.$status['what'] ); } - } function init_session() { $_SESSION['m_admin']['notification'] = array( - 'notification_sid' => '', - 'notification_id' => '', - 'event_id' => '', - 'description' => '', - 'notification_mode' => '', - 'rss_url_template' => '', - 'template_id' => '', - 'is_enabled' => 'Y', - 'diffusion_type' => '', - 'diffusion_properties' => '', - //'diffusion_content' => '', - 'attachfor_type' => '', - 'attachfor_properties' => '', + 'notification_sid' => '', + 'notification_id' => '', + 'event_id' => '', + 'description' => '', + 'notification_mode' => '', + 'template_id' => '', + 'is_enabled' => 'Y', + 'diffusion_type' => '', + 'diffusion_properties' => '', + //'diffusion_content' => '', + 'attachfor_type' => '', + 'attachfor_properties' => '', ); } /** * Put given object in session, according with given type - * NOTE: given object needs to be at least hashable - * @param string $type + * NOTE: given object needs to be at least hashable. + * + * @param string $type * @param hashable $hashable */ function put_in_session($type, $hashable, $showString = true) { $func = new functions(); - foreach ($hashable as $key=>$value) { - if ($showString) { - $_SESSION['m_admin'][$type][$key]=$func->show_string($value); - } else { - $_SESSION['m_admin'][$type][$key]=$value; - } - } + foreach ($hashable as $key => $value) { + if ($showString) { + $_SESSION['m_admin'][$type][$key] = $func->show_string($value); + } else { + $_SESSION['m_admin'][$type][$key] = $value; + } + } //print_r($_SESSION['m_admin']); } diff --git a/modules/notifications/xml/IVS/validation_rules.xml b/modules/notifications/xml/IVS/validation_rules.xml index 0f6f843e51f..3f2993a248e 100755 --- a/modules/notifications/xml/IVS/validation_rules.xml +++ b/modules/notifications/xml/IVS/validation_rules.xml @@ -12,7 +12,6 @@ <parameter name="description" type="string" /> <parameter name="event_id" type="integer" /> <parameter name="notification_mode" type="string" /> - <parameter name="rss_url_template" type="string" /> <parameter name="template_id" type="integer" /> <parameter name="is_enabled" type="YN" /> <parameter name="diffusion_type" type="string" /> diff --git a/modules/notifications/xml/diffusion_type.xml b/modules/notifications/xml/diffusion_type.xml deleted file mode 100755 index c19c906c301..00000000000 --- a/modules/notifications/xml/diffusion_type.xml +++ /dev/null @@ -1,135 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<root> - <diffusion_type> - <id>group</id> - <label>_GROUP</label> - <script>modules/notifications/diffusion_types/group.php</script> - <use_email>true</use_email> - <use_rss>true</use_rss> - <add_attachment>true</add_attachment> - <select>id, group_id, group_desc</select> - <from>usergroups</from> - <where>enabled = ?</where> - <data>Y</data> - </diffusion_type> - <diffusion_type> - <id>entity</id> - <label>_ENTITY</label> - <script>modules/notifications/diffusion_types/entity.php</script> - <use_email>true</use_email> - <use_rss>true</use_rss> - <add_attachment>true</add_attachment> - <select>entity_id, entity_label</select> - <from>entities</from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>dest_entity</id> - <label>_DEST_ENTITY</label> - <script>modules/notifications/diffusion_types/dest_entity.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>false</add_attachment> - <select>id, label_status</select> - <from>status</from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>user</id> - <label>_USER</label> - <script>modules/notifications/diffusion_types/user.php</script> - <use_email>true</use_email> - <use_rss>true</use_rss> - <add_attachment>true</add_attachment> - <select>user_id, firstname, lastname</select> - <from>users</from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>dest_user</id> - <label>_DEST_USER</label> - <script>modules/notifications/diffusion_types/dest_user.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>false</add_attachment> - <select>id, label_status</select> - <from>status</from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>copy_list</id> - <label>_COPYLIST</label> - <script>modules/notifications/diffusion_types/copy_list.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>false</add_attachment> - <select></select> - <from></from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>note_dest_user</id> - <label>_NOTE_DEST_USER</label> - <script>modules/notifications/diffusion_types/note_dest_user.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>false</add_attachment> - <select></select> - <from></from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>note_copy_list</id> - <label>_NOTE_COPY_LIST</label> - <script>modules/notifications/diffusion_types/note_copy_list.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>false</add_attachment> - <select></select> - <from></from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>contact</id> - <label>_CONTACT</label> - <script>modules/notifications/diffusion_types/contact.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>true</add_attachment> - <select></select> - <from></from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>dest_user_visa</id> - <label>_DEST_USER_VISA</label> - <script>modules/notifications/diffusion_types/dest_user_visa.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>true</add_attachment> - <select>id, label_status</select> - <from>status</from> - <where></where> - <data></data> - </diffusion_type> - <diffusion_type> - <id>dest_user_sign</id> - <label>_DEST_USER_SIGN</label> - <script>modules/notifications/diffusion_types/dest_user_sign.php</script> - <use_email>true</use_email> - <use_rss>false</use_rss> - <add_attachment>true</add_attachment> - <select>id, label_status</select> - <from>status</from> - <where></where> - <data></data> - </diffusion_type> -</root> diff --git a/modules/notifications/xml/event_type.xml b/modules/notifications/xml/event_type.xml index 87468d1fe0f..cc6e3ff56cb 100755 --- a/modules/notifications/xml/event_type.xml +++ b/modules/notifications/xml/event_type.xml @@ -1,24 +1,20 @@ <?xml version="1.0" encoding="utf-8"?> <root> <event_type> - <id>usersup</id> - <label>Modification d'un utilisateur</label> + <id>baskets</id> + <label>Workflow bannettes</label> </event_type> <event_type> - <id>users%</id> - <label>Actions sur utilisateur</label> + <id>noteadd</id> + <label>Ajout de notes</label> </event_type> <event_type> <id>alert1</id> - <label>Alerte courrier 1</label> + <label>Relance courrier avant échéance</label> </event_type> <event_type> <id>alert2</id> - <label>Relance courrier 2 avant échéance</label> - </event_type> - <event_type> - <id>noteadd</id> - <label>Ajout de notes</label> + <label>Relance courrier après échéance</label> </event_type> <event_type> <id>diffdest%</id> @@ -29,8 +25,12 @@ <label>Courrier en copie</label> </event_type> <event_type> - <id>stepWF%</id> - <label>Etape Workflow</label> + <id>usersup</id> + <label>Modification d'un utilisateur</label> + </event_type> + <event_type> + <id>users%</id> + <label>Actions sur utilisateur</label> </event_type> <event_type> <id>diffvisauser</id> diff --git a/sql/data_fr.sql b/sql/data_fr.sql index 9021ea7fd90..9850804029e 100755 --- a/sql/data_fr.sql +++ b/sql/data_fr.sql @@ -1519,36 +1519,35 @@ VALUES (7, '[notification courrier] Diffusion de courrier', 'Alerte de courriers <p> ###</p> <p style="font-family: Trebuchet MS, Arial, Helvetica, sans-serif### width: 100%### text-align: center### font-size: 9px### font-style: italic### opacity: 0.5###">Message gé###né###ré### via l''application MaarchCourrier</p>', 'HTML', NULL, NULL, 'ODP: open_office_presentation', 'letterbox_events', 'notifications'); INSERT INTO templates (template_id, template_label, template_comment, template_content, template_type, template_path, template_file_name, template_style, template_datasource, template_target) -VALUES (8, '[notification courrier] Nouvelle annotation', '[notification] Nouvelle annotation', '<p><font face="verdana,geneva" size="2">Bonjour [recipient.firstname] [recipient.lastname], [recipient.text]</font></p> +VALUES (8, '[notification courrier] Nouvelle annotation', '[notification] Nouvelle annotation', '<p style="font-family: Trebuchet MS, Arial, Helvetica, sans-serif###">Bonjour <strong>[recipient.firstname] [recipient.lastname]</strong>,</p> <p> ###</p> -<p><font face="verdana,geneva" size="2"> </font></p> -<p> ###</p> -<p><font face="verdana,geneva" size="2">Voici la liste des notes pour les courriers suivants :</font></p> -<p> ###</p> -<table style="width: 982px### height: 77px###" border="1" cellspacing="3" cellpadding="3" frame="box"> +<p style="font-family: Trebuchet MS, Arial, Helvetica, sans-serif###">Voici les nouvelles annotations sur les courriers suivants :</p> +<table style="font-family: Trebuchet MS, Arial, Helvetica, sans-serif### border-collapse: collapse### width: 100%###"> <tbody> <tr> -<td><strong>Reference</strong></td> -<td><strong>Num</strong></td> -<td><strong>Date</strong></td> -<td><strong>Objet</strong></td> -<td><strong>Note</strong></td> -<td><strong>Ajouté### par</strong></td> -<td><strong>Contact</strong></td> -<td><strong>Liens</strong></td> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Ré###fé###rence</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Num</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Date</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Objet</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Note</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Ajouté### par</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###">Contact</th> +<th style="border: 1px solid #ddd### padding: 8px### padding-top: 12px### padding-bottom: 12px### text-align: left### background-color: #135f7f### color: white###"> ###</th> </tr> <tr> -<td>[notes.identifier]</td> -<td>[notes.# ###frm=0000]</td> -<td>[notes.doc_date###block=tr###frm=dd/mm/yyyy]</td> -<td>[notes.subject]</td> -<td>[notes.note_text]</td> -<td>[notes.user_id]</td> -<td>[notes.contact_society] [notes.contact_firstname] [notes.contact_lastname]</td> -<td><a href="[notes.linktodetail]" name="detail">dé###tail</a> <a href="[notes.linktodoc]" name="doc">doc</a></td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.identifier]</td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.# ###frm=0000]</td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.doc_date###block=tr###frm=dd/mm/yyyy]</td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.subject]</td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.note_text]</td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.user_id]</td> +<td style="border: 1px solid #ddd### padding: 8px###">[notes.contact_society] [notes.contact_firstname] [notes.contact_lastname]</td> +<td style="border: 1px solid #ddd### padding: 8px### text-align: right###"><a style="text-decoration: none### background: #135f7f### padding: 5px### color: white### -webkit-box-shadow: 6px 4px 5px 0px rgba(0,0,0,0.75)### -moz-box-shadow: 6px 4px 5px 0px rgba(0,0,0,0.75)### box-shadow: 6px 4px 5px 0px rgba(0,0,0,0.75)###" href="[res_letterbox.linktodetail]" name="detail">Dé###tail</a> <a style="text-decoration: none### background: #135f7f### padding: 5px### color: white### -webkit-box-shadow: 6px 4px 5px 0px rgba(0,0,0,0.75)### -moz-box-shadow: 6px 4px 5px 0px rgba(0,0,0,0.75)### box-shadow: 6px 4px 5px 0px rgba(0,0,0,0.75)###" href="[res_letterbox.linktodoc]" name="doc">Afficher</a></td> </tr> </tbody> -</table>', 'HTML', NULL, NULL, 'ODP: open_office_presentation', 'notes', 'notifications'); +</table> +<p> ###</p> +<p style="font-family: Trebuchet MS, Arial, Helvetica, sans-serif### width: 100%### text-align: center### font-size: 9px### font-style: italic### opacity: 0.5###">Message gé###né###ré### via l''application MaarchCourrier</p>', 'HTML', NULL, NULL, 'ODP: open_office_presentation', 'notes', 'notifications'); INSERT INTO templates (template_id, template_label, template_comment, template_content, template_type, template_path, template_file_name, template_style, template_datasource, template_target, template_attachment_type) VALUES (9, 'Demande - Voirie', 'Demande - Voirie', '<h2>Demande Intervention VOIRIE</h2> <hr /> <table style="border: 1pt solid #000000### width: 597px### background-color: #f0f0f0### height: 172px###" border="1" cellspacing="1" cellpadding="5"><caption> ###</caption> @@ -1697,19 +1696,19 @@ Select setval('templates_seq', (select max(template_id)+1 from templates), false --NOTIFICATIONS ------------ TRUNCATE TABLE notifications; -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, rss_url_template) +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties) VALUES (1, 'USERS', '[administration] Actions sur les utilisateurs de l''application', 'users%', 'EMAIL', 2, 'user', 'superadmin', '', '', 'http://localhost/maarch_entreprise'); -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, rss_url_template, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) -VALUES (2, 'RET2', '2ie alerte sur courriers en retard', 'alert2', 'EMAIL', 5, '', 'dest_user', '', '', '', 'Y'); -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, rss_url_template, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) -VALUES (3, 'RET1', '1ère alerte sur courriers en retard', 'alert1', 'EMAIL', 6, '', 'dest_user', '', '', '', 'Y'); -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, rss_url_template, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) -VALUES (4, 'BASKETS', 'Notification de bannettes', '', 'EMAIL', 7, '', 'dest_user', '', '', '', 'Y'); -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, rss_url_template, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) +VALUES (2, 'RET2', 'Courriers en retard de traitement', 'alert2', 'EMAIL', 5, '', 'dest_user', '', '', '', 'Y'); +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) +VALUES (3, 'RET1', 'Courriers arrivant à échéance', 'alert1', 'EMAIL', 6, '', 'dest_user', '', '', '', 'Y'); +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) +VALUES (4, 'BASKETS', 'Notification de bannettes', 'baskets', 'EMAIL', 7, '', 'dest_user', '', '', '', 'Y'); +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) VALUES (5, 'ANC', 'Nouvelle annotation sur courrier en copie', 'noteadd', 'EMAIL', 8, '', 'copy_list', '', '', '', 'Y'); -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, rss_url_template, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) VALUES (6, 'AND', 'Nouvelle annotation sur courrier destinataire', 'noteadd', 'EMAIL', 8, '', 'dest_user', '', '', '', 'Y'); -INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, rss_url_template, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) +INSERT INTO notifications (notification_sid, notification_id, description, event_id, notification_mode, template_id, diffusion_type, diffusion_properties, attachfor_type, attachfor_properties, is_enabled) VALUES (7, 'RED', 'Redirection de courrier', '1', 'EMAIL', 7, '', 'dest_user', '', '', '', 'Y'); Select setval('notifications_seq', (select max(notification_sid)+1 from notifications), false); diff --git a/sql/develop.sql b/sql/develop.sql index 0301119563f..6214b6327ff 100755 --- a/sql/develop.sql +++ b/sql/develop.sql @@ -719,3 +719,6 @@ INSERT INTO docserver_types (docserver_type_id, docserver_type_label, enabled, i VALUES ('ARCHIVETRANSFER', 'Archive Transfer', 'Y', 'N', 0, 'N', 'NONE', 'N', 'NONE', 'N', 'NONE', 'Y', 'SHA256'); ALTER TABLE sendmail ALTER COLUMN res_id DROP NOT NULL; + +ALTER TABLE notifications DROP COLUMN IF EXISTS rss_url_template; +UPDATE notifications SET event_id = 'baskets' WHERE notification_id = 'BASKETS'; \ No newline at end of file diff --git a/sql/structure.sql b/sql/structure.sql index 5a48169b30e..aedf33edf67 100755 --- a/sql/structure.sql +++ b/sql/structure.sql @@ -948,7 +948,6 @@ CREATE TABLE notifications event_id character varying(255) NOT NULL, notification_mode character varying(30) NOT NULL, template_id bigint, - rss_url_template text, diffusion_type character varying(50) NOT NULL, diffusion_properties text, attachfor_type character varying(50), diff --git a/src/app/notification/controllers/NotificationController.php b/src/app/notification/controllers/NotificationController.php index 3c45e59ed6a..758a17fcb6b 100644 --- a/src/app/notification/controllers/NotificationController.php +++ b/src/app/notification/controllers/NotificationController.php @@ -1,17 +1,17 @@ <?php /** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ + * Copyright Maarch since 2008 under licence GPLv3. + * See LICENCE.txt file at the root folder for more details. + * This file is part of Maarch software. + */ /** -* @brief Notifications Controller -* @author dev@maarch.org -* @ingroup notifications -*/ + * @brief Notifications Controller + * + * @author dev@maarch.org + * @ingroup notifications + */ namespace Notification\controllers; @@ -52,51 +52,46 @@ class NotificationController return $response->withStatus(400)->withJson(['errors' => 'Notification not found']); } - $notification['diffusion_properties'] = explode(",", $notification['diffusion_properties']); - - foreach ($notification['diffusion_properties'] as $key => $value) { - $notification['diffusion_properties'][$value] = $value; - unset($notification['diffusion_properties'][$key]); - } + $notification['diffusion_properties'] = explode(',', $notification['diffusion_properties']); + + $notification['attachfor_properties'] = explode(',', $notification['attachfor_properties']); - $notification['attachfor_properties'] = explode(",", $notification['attachfor_properties']); - foreach ($notification['attachfor_properties'] as $key => $value) { $notification['attachfor_properties'][$value] = $value; unset($notification['attachfor_properties'][$key]); } - + $data = []; - $data['event'] = NotificationModel::getEvent(); - $data['template'] = NotificationModel::getTemplate(); + $data['event'] = NotificationModel::getEvent(); + $data['template'] = NotificationModel::getTemplate(); $data['diffusionType'] = NotificationModel::getDiffusionType(); - $data['groups'] = NotificationModel::getDiffusionTypeGroups(); - $data['users'] = NotificationModel::getDiffusionTypesUsers(); - $data['entities'] = NotificationModel::getDiffusionTypeEntities(); - $data['status'] = NotificationModel::getDiffusionTypeStatus(); + $data['groups'] = NotificationModel::getDiffusionTypeGroups(); + $data['users'] = NotificationModel::getDiffusionTypesUsers(); + $data['entities'] = NotificationModel::getDiffusionTypeEntities(); + $data['status'] = NotificationModel::getDiffusionTypeStatus(); $notification['data'] = $data; - $filename = "notification"; + $filename = 'notification'; $customId = CoreConfigModel::getCustomId(); - if ($customId <> "") { - $filename.="_".str_replace(" ", "", $customId); + if ($customId != '') { + $filename .= '_'.str_replace(' ', '', $customId); } - $filename .= "_".$notification['notification_sid'].".sh"; + $filename .= '_'.$notification['notification_id'].'.sh'; - $corePath = str_replace("custom/".$customId."/src/app/notification/controllers", "", __DIR__); - $corePath = str_replace("src/app/notification/controllers", "", $corePath); - if ($customId <> '') { - $pathToFolow = $corePath . 'custom/'.$customId. '/'; + $corePath = str_replace('custom/'.$customId.'/src/app/notification/controllers', '', __DIR__); + $corePath = str_replace('src/app/notification/controllers', '', $corePath); + if ($customId != '') { + $pathToFolow = $corePath.'custom/'.$customId.'/'; } else { $pathToFolow = $corePath; } - $notification["scriptcreated"] = false; + $notification['scriptcreated'] = false; if (file_exists($pathToFolow.'modules/notifications/batch/scripts/'.$filename)) { - $notification["scriptcreated"] = true; + $notification['scriptcreated'] = true; } return $response->withJson(['notification' => $notification]); @@ -116,42 +111,39 @@ class NotificationController } $notificationInDb = NotificationModel::getByNotificationId(['notificationId' => $data['notification_id'], 'select' => ['notification_sid']]); - + if (Validator::notEmpty()->validate($notificationInDb)) { return $response->withStatus(400)->withJson(['errors' => _NOTIF_ALREADY_EXIST]); } - if ($data['is_enabled'] == true) { - $data['is_enabled'] = 'Y'; - } else { - $data['is_enabled'] = 'N'; - } - $data['notification_mode'] = 'EMAIL'; - + if ($data['diffusion_properties']) { - $data['diffusion_properties'] = implode(",", $data['diffusion_properties']); + $data['diffusion_properties'] = implode(',', $data['diffusion_properties']); + } else { + $data['diffusion_properties'] = ''; } - + if ($data['attachfor_properties']) { - $data['attachfor_properties'] = implode(",", $data['attachfor_properties']); + $data['attachfor_properties'] = implode(',', $data['attachfor_properties']); } else { $data['attachfor_properties'] = ''; } if (NotificationModel::create($data)) { - if (PHP_OS == "Linux") { + if (PHP_OS == 'Linux') { $notificationAdded = NotificationModel::getByNotificationId(['notificationId' => $data['notification_id'], 'select' => ['notification_sid']]); NotificationScheduleModel::createScriptNotification(['notification_sid' => $notificationAdded['notification_sid'], 'notification_id' => $data['notification_id']]); } HistoryController::add([ 'tableName' => 'notifications', - 'recordId' => $data['notification_id'], + 'recordId' => $data['notification_id'], 'eventType' => 'ADD', - 'eventId' => 'notificationsadd', - 'info' => _ADD_NOTIFICATIONS . ' : ' . $data['notification_id'] + 'eventId' => 'notificationsadd', + 'info' => _ADD_NOTIFICATIONS.' : '.$data['notification_id'], ]); + return $response->withJson(NotificationModel::getByNotificationId(['notificationId' => $data['notification_id']])); } else { return $response->withStatus(400)->withJson(['errors' => 'Notification Create Error']); @@ -164,37 +156,37 @@ class NotificationController return $response->withStatus(403)->withJson(['errors' => 'Service forbidden']); } - $data = $request->getParams(); + $data = $request->getParams(); $data['notification_sid'] = $aArgs['id']; unset($data['scriptcreated']); $errors = $this->control($data, 'update'); - + if (!empty($errors)) { return $response ->withStatus(500)->withJson(['errors' => $errors]); } - $data['diffusion_properties'] = implode(",", $data['diffusion_properties']); - $data['attachfor_properties'] = implode(",", $data['attachfor_properties']); + $data['diffusion_properties'] = implode(',', $data['diffusion_properties']); + $data['attachfor_properties'] = implode(',', $data['attachfor_properties']); NotificationModel::update($data); $notification = NotificationModel::getById(['notification_sid' => $data['notification_sid']]); - if (PHP_OS == "Linux") { + if (PHP_OS == 'Linux') { NotificationScheduleModel::createScriptNotification(['notification_sid' => $data['notification_sid'], 'notification_id' => $notification['notification_id']]); } HistoryController::add([ 'tableName' => 'notifications', - 'recordId' => $data['notification_sid'], + 'recordId' => $data['notification_sid'], 'eventType' => 'UP', - 'eventId' => 'notificationsup', - 'info' => _MODIFY_NOTIFICATIONS . ' : ' . $data['notification_sid'] + 'eventId' => 'notificationsup', + 'info' => _MODIFY_NOTIFICATIONS.' : '.$data['notification_sid'], ]); - return $response->withJson(['notification'=> $notification]); + return $response->withJson(['notification' => $notification]); } public function delete(Request $request, Response $response, $aArgs) @@ -209,34 +201,36 @@ class NotificationController ->withJson(['errors' => 'Id is not a numeric']); } + $notification = NotificationModel::getById(['notification_sid' => $aArgs['id']]); + NotificationModel::delete(['notification_sid' => $aArgs['id']]); HistoryController::add([ 'tableName' => 'notifications', - 'recordId' => $aArgs['id'], + 'recordId' => $aArgs['id'], 'eventType' => 'DEL', - 'eventId' => 'notificationsdel', - 'info' => _DELETE_NOTIFICATIONS . ' : ' . $aArgs['id'] + 'eventId' => 'notificationsdel', + 'info' => _DELETE_NOTIFICATIONS.' : '.$aArgs['id'], ]); - if (PHP_OS == "Linux") { + if (PHP_OS == 'Linux') { // delete scheduled notification - $filename = "notification"; + $filename = 'notification'; $customId = CoreConfigModel::getCustomId(); - if ($customId<>"") { - $filename.="_".str_replace(" ", "", $customId); + if ($customId != '') { + $filename .= '_'.str_replace(' ', '', $customId); } - $filename.="_".$aArgs['id'].".sh"; + $filename .= '_'.$notification['notification_id'].'.sh'; $cronTab = NotificationScheduleModel::getCrontab(); $flagCron = false; - $corePath = str_replace("custom/".$customId."/src/app/notification/controllers", "", __DIR__); - $corePath = str_replace("src/app/notification/controllers", "", $corePath); - if ($customId <> '') { - $pathToFolow = $corePath . 'custom/'.$customId. '/'; + $corePath = str_replace('custom/'.$customId.'/src/app/notification/controllers', '', __DIR__); + $corePath = str_replace('src/app/notification/controllers', '', $corePath); + if ($customId != '') { + $pathToFolow = $corePath.'custom/'.$customId.'/'; } else { $pathToFolow = $corePath; } @@ -252,12 +246,12 @@ class NotificationController if ($flagCron) { NotificationScheduleModel::saveCrontab($cronTab); } - - unlink($pathToFolow . 'modules/notifications/batch/scripts/' . $filename); + + unlink($pathToFolow.'modules/notifications/batch/scripts/'.$filename); } return $response->withJson([ - 'notifications' => NotificationModel::get() + 'notifications' => NotificationModel::get(), ]); } @@ -271,29 +265,29 @@ class NotificationController } else { $obj = NotificationModel::getById(['notification_sid' => $aArgs['notification_sid']]); } - + if (empty($obj)) { $errors[] = 'notification does not exists'; } } if (!Validator::notEmpty()->validate($aArgs['notification_id'])) { - $errors[]= 'notification_id is empty'; + $errors[] = 'notification_id is empty'; } if (!Validator::length(1, 254)->notEmpty()->validate($aArgs['description'])) { - $errors[]= 'wrong format for description'; + $errors[] = 'wrong format for description'; } if (!Validator::length(0, 254)->validate($dataArgsa['event_id'])) { - $errors[]= 'event_id is too long'; + $errors[] = 'event_id is too long'; } if (!Validator::length(0, 30)->validate($aArgs['notification_mode'])) { - $errors[]= 'notification_mode is too long'; + $errors[] = 'notification_mode is too long'; } if (!Validator::intType()->notEmpty()->validate($aArgs['template_id'])) { - $errors[]= 'wrong format for template_id'; + $errors[] = 'wrong format for template_id'; } if (!Validator::notEmpty()->validate($aArgs['is_enabled']) || ($aArgs['is_enabled'] != 'Y' && $aArgs['is_enabled'] != 'N')) { - $errors[]= 'Invalid is_enabled value'; + $errors[] = 'Invalid is_enabled value'; } return $errors; @@ -310,16 +304,16 @@ class NotificationController $notification['attachfor_properties'] = []; $data = []; - $data['event'] = NotificationModel::getEvent(); - $data['template'] = NotificationModel::getTemplate(); + $data['event'] = NotificationModel::getEvent(); + $data['template'] = NotificationModel::getTemplate(); $data['diffusionType'] = NotificationModel::getDiffusionType(); - $data['groups'] = NotificationModel::getDiffusionTypeGroups(); - $data['users'] = NotificationModel::getDiffusionTypesUsers(); - $data['entities'] = NotificationModel::getDiffusionTypeEntities(); - $data['status'] = NotificationModel::getDiffusionTypeStatus(); + $data['groups'] = NotificationModel::getDiffusionTypeGroups(); + $data['users'] = NotificationModel::getDiffusionTypesUsers(); + $data['entities'] = NotificationModel::getDiffusionTypeEntities(); + $data['status'] = NotificationModel::getDiffusionTypeStatus(); $notification['data'] = $data; - return $response->withJson(['notification'=>$notification]); + return $response->withJson(['notification' => $notification]); } } diff --git a/src/app/notification/controllers/NotificationScheduleController.php b/src/app/notification/controllers/NotificationScheduleController.php index ef0da3f79e7..0b94394f989 100644 --- a/src/app/notification/controllers/NotificationScheduleController.php +++ b/src/app/notification/controllers/NotificationScheduleController.php @@ -1,17 +1,17 @@ <?php /** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ + * Copyright Maarch since 2008 under licence GPLv3. + * See LICENCE.txt file at the root folder for more details. + * This file is part of Maarch software. + */ /** -* @brief Notifications Schedule Controller -* @author dev@maarch.org -* @ingroup notifications -*/ + * @brief Notifications Schedule Controller + * + * @author dev@maarch.org + * @ingroup notifications + */ namespace Notification\controllers; @@ -32,11 +32,11 @@ class NotificationScheduleController } return $response->withJson([ - 'crontab' => NotificationScheduleModel::getCrontab(), - 'authorizedNotification' => NotificationScheduleController::getAuthorizedNotifications(), + 'crontab' => NotificationScheduleModel::getCrontab(), + 'authorizedNotification' => self::getAuthorizedNotifications(), ]); } - + // Save Crontab public function create(Request $request, Response $response) { @@ -45,17 +45,17 @@ class NotificationScheduleController } $data = $request->getParams(); - if (!NotificationScheduleController::checkCrontab($data)) { + if (!self::checkCrontab($data)) { return $response->withStatus(500)->withJson(['errors' => 'Problem with crontab']); } foreach ($data as $id => $cronValue) { foreach ($cronValue as $key => $value) { - if (!Validator::notEmpty()->validate($value)) { - $errors[] = $key." is empty"; + if (($key == 'cmd' || $key == 'state') && !Validator::notEmpty()->validate($value)) { + $errors[] = $key.' is empty'; } - if ($key != "cmd" && $key != "state" && !Validator::intVal()->validate($value) && $value != "*") { - $errors[] = "wrong format for ".$key; + if ($key != 'cmd' && $key != 'state' && $key != 'description' && !Validator::intVal()->validate($value) && $value != '*') { + $errors[] = 'wrong format for '.$key; } } } @@ -63,28 +63,28 @@ class NotificationScheduleController return $response->withStatus(500)->withJson(['errors' => $errors]); } - NotificationScheduleModel::saveCrontab(["crontab" => $data]); + NotificationScheduleModel::saveCrontab(['crontab' => $data]); return $response->withJson(true); } protected static function getAuthorizedNotifications() { - $aNotification = NotificationModel::getEnableNotifications(['select' => ['notification_sid', 'description']]); + $aNotification = NotificationModel::getEnableNotifications(['select' => ['notification_id', 'notification_sid', 'description']]); $notificationsArray = array(); - $customId = CoreConfigModel::getCustomId(); - $corePath = str_replace("custom/".$customId."/src/app/notification/controllers", "", __DIR__); - $corePath = str_replace("src/app/notification/controllers", "", $corePath); + $customId = CoreConfigModel::getCustomId(); + $corePath = str_replace('custom/'.$customId.'/src/app/notification/controllers', '', __DIR__); + $corePath = str_replace('src/app/notification/controllers', '', $corePath); foreach ($aNotification as $result) { - $filename = "notification"; - if (isset($customId) && $customId<>"") { - $filename.="_".str_replace(" ", "", $customId); + $filename = 'notification'; + if (isset($customId) && $customId != '') { + $filename .= '_'.str_replace(' ', '', $customId); } - $filename.="_".$result['notification_sid'].".sh"; + $filename .= '_'.$result['notification_id'].'.sh'; - if ($customId <> '') { - $pathToFolow = $corePath . 'custom/'.$customId . '/'; + if ($customId != '') { + $pathToFolow = $corePath.'custom/'.$customId.'/'; } else { $pathToFolow = $corePath; } @@ -92,29 +92,29 @@ class NotificationScheduleController $path = $pathToFolow.'modules/notifications/batch/scripts/'.$filename; if (file_exists($path)) { - $notificationsArray[$path] = $result['description']; + $notificationsArray[] = array('description' => $result['description'], 'path' => $path); } } - + return $notificationsArray; } protected static function checkCrontab($crontabToSave) { - $customId = CoreConfigModel::getCustomId(); + $customId = CoreConfigModel::getCustomId(); $crontabBeforeSave = NotificationScheduleModel::getCrontab(); - $corePath = str_replace("custom/".$customId."/src/app/notification/controllers", "", __DIR__); - $corePath = str_replace("src/app/notification/controllers", "", $corePath); + $corePath = str_replace('custom/'.$customId.'/src/app/notification/controllers', '', __DIR__); + $corePath = str_replace('src/app/notification/controllers', '', $corePath); foreach ($crontabToSave as $id => $cronValue) { - if ($cronValue['state'] != "hidden" && $crontabBeforeSave[$id]['state'] == "hidden") { + if ($cronValue['state'] != 'hidden' && $crontabBeforeSave[$id]['state'] == 'hidden') { $returnValue = false; break; - } elseif ($cronValue['state'] == "hidden" && $crontabBeforeSave[$id]['state'] != "hidden") { + } elseif ($cronValue['state'] == 'hidden' && $crontabBeforeSave[$id]['state'] != 'hidden') { $returnValue = false; break; - } elseif ($cronValue['state'] == "new" || $cronValue['state'] == "normal") { - if ($customId <> '') { - $pathToFolow = $corePath . 'custom/'.$customId . '/'; + } elseif ($cronValue['state'] == 'new' || $cronValue['state'] == 'normal') { + if ($customId != '') { + $pathToFolow = $corePath.'custom/'.$customId.'/'; } else { $pathToFolow = $corePath; } @@ -154,7 +154,7 @@ class NotificationScheduleController } $notification_sid = $data['notification_sid']; - $notification_id = $data['notification_id']; + $notification_id = $data['notification_id']; NotificationScheduleModel::createScriptNotification(['notification_sid' => $notification_sid, 'notification_id' => $notification_id]); diff --git a/src/app/notification/models/NotificationModelAbstract.php b/src/app/notification/models/NotificationModelAbstract.php index cdf2e7f3079..28b650c84ae 100644 --- a/src/app/notification/models/NotificationModelAbstract.php +++ b/src/app/notification/models/NotificationModelAbstract.php @@ -1,17 +1,17 @@ <?php /** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ + * Copyright Maarch since 2008 under licence GPLv3. + * See LICENCE.txt file at the root folder for more details. + * This file is part of Maarch software. + */ /** -* @brief Notifications Model -* @author dev@maarch.org -* @ingroup Module -*/ + * @brief Notifications Model + * + * @author dev@maarch.org + * @ingroup Module + */ namespace Notification\models; @@ -22,15 +22,15 @@ use SrcCore\models\DatabaseModel; use Status\models\StatusModel; use SrcCore\models\CoreConfigModel; -class NotificationModelAbstract +class NotificationModelAbstract { public static function get(array $aArgs = []) { ValidatorModel::arrayType($aArgs, ['select']); $aNotifications = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['notifications'] + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['notifications'], ]); return $aNotifications; @@ -41,10 +41,10 @@ class NotificationModelAbstract ValidatorModel::notEmpty($aArgs, ['notification_sid']); $aNotification = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['notifications'], - 'where' => ['notification_sid = ?'], - 'data' => [$aArgs['notification_sid']] + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['notifications'], + 'where' => ['notification_sid = ?'], + 'data' => [$aArgs['notification_sid']], ]); if (empty($aNotification[0])) { @@ -59,10 +59,10 @@ class NotificationModelAbstract ValidatorModel::notEmpty($aArgs, ['notificationId']); $aNotification = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['notifications'], - 'where' => ['notification_id = ?'], - 'data' => [$aArgs['notificationId']] + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['notifications'], + 'where' => ['notification_id = ?'], + 'data' => [$aArgs['notificationId']], ]); if (empty($aNotification[0])) { @@ -78,9 +78,9 @@ class NotificationModelAbstract ValidatorModel::intVal($aArgs, ['notification_sid']); DatabaseModel::delete([ - 'table' => 'notifications', - 'where' => ['notification_sid = ?'], - 'data' => [$aArgs['notification_sid']], + 'table' => 'notifications', + 'where' => ['notification_sid = ?'], + 'data' => [$aArgs['notification_sid']], ]); return true; @@ -88,25 +88,24 @@ class NotificationModelAbstract public static function create(array $aArgs = []) { - ValidatorModel::notEmpty($aArgs, ['notification_id', 'description', 'is_enabled', 'event_id', 'notification_mode', 'template_id', 'diffusion_type', 'diffusion_properties']); + ValidatorModel::notEmpty($aArgs, ['notification_id', 'description', 'is_enabled', 'event_id', 'notification_mode', 'template_id', 'diffusion_type']); ValidatorModel::intVal($aArgs, ['template_id']); - ValidatorModel::stringType($aArgs, ['notification_id','description','is_enabled','event_id','notification_mode',]); + ValidatorModel::stringType($aArgs, ['notification_id', 'description', 'is_enabled', 'event_id', 'notification_mode']); DatabaseModel::insert([ - 'table' => 'notifications', + 'table' => 'notifications', 'columnsValues' => [ - 'notification_id' => $aArgs['notification_id'], - 'description' => $aArgs['description'], - 'is_enabled' => $aArgs['is_enabled'], - 'event_id' => $aArgs['event_id'], - 'notification_mode' => $aArgs['notification_mode'], - 'template_id' => $aArgs['template_id'], - 'rss_url_template' => $aArgs['rss_url_template'], - 'diffusion_type' => $aArgs['diffusion_type'], - 'diffusion_properties' => $aArgs['diffusion_properties'], - 'attachfor_type' => $aArgs['attachfor_type'], - 'attachfor_properties' => $aArgs['attachfor_properties'] - ] + 'notification_id' => $aArgs['notification_id'], + 'description' => $aArgs['description'], + 'is_enabled' => $aArgs['is_enabled'], + 'event_id' => $aArgs['event_id'], + 'notification_mode' => $aArgs['notification_mode'], + 'template_id' => $aArgs['template_id'], + 'diffusion_type' => $aArgs['diffusion_type'], + 'diffusion_properties' => $aArgs['diffusion_properties'], + 'attachfor_type' => $aArgs['attachfor_type'], + 'attachfor_properties' => $aArgs['attachfor_properties'], + ], ]); return true; @@ -123,9 +122,9 @@ class NotificationModelAbstract $aReturn = DatabaseModel::update([ 'table' => 'notifications', - 'set' => $aArgs, + 'set' => $aArgs, 'where' => ['notification_sid = ?'], - 'data' => [$notification_sid] + 'data' => [$notification_sid], ]); return $aReturn; @@ -134,25 +133,24 @@ class NotificationModelAbstract public static function getEvent() { $tabEvent_Type = DatabaseModel::select([ - 'select' => ['id, label_action'], - 'table' => ['actions'] + 'select' => ['id, label_action'], + 'table' => ['actions'], ]); //get event system $customId = CoreConfigModel::getCustomId(); - if (file_exists('custom/' .$customId. 'modules/notifications/xml/event_type.xml')) { - $path = 'custom/' .$customId. 'modules/notifications/xml/event_type.xml'; + if (file_exists('custom/'.$customId.'modules/notifications/xml/event_type.xml')) { + $path = 'custom/'.$customId.'modules/notifications/xml/event_type.xml'; } else { $path = 'modules/notifications/xml/event_type.xml'; } $xmlfile = simplexml_load_file($path); if ($xmlfile) { foreach ($xmlfile->event_type as $eventType) { - $tabEvent_Type[] = array( - 'id' => (string) $eventType->id, - 'label_action' => (string) $eventType->label, + 'id' => (string) $eventType->id, + 'label_action' => (string) $eventType->label, ); } } @@ -163,12 +161,12 @@ class NotificationModelAbstract public static function getTemplate() { $tabTemplate = DatabaseModel::select([ - 'select' => ['template_id, template_label'], - 'table' => ['templates'], - 'where' => ['template_target = ?'], - 'data' => ['notifications'] + 'select' => ['template_id, template_label'], + 'table' => ['templates'], + 'where' => ['template_target = ?'], + 'data' => ['notifications'], ]); - + return $tabTemplate; } @@ -192,7 +190,7 @@ class NotificationModelAbstract // 'table' => [(string)$diffusionType->from], // 'where' => [(string)$diffusionType->where], // 'data' => [(string)$diffusionType->data] - // ]); + // ]); // }else{ // $result = DatabaseModel::select([ // 'select' => [(string)$diffusionType->select], @@ -209,9 +207,6 @@ class NotificationModelAbstract // 'request' => $result, // ); - - - // } // } // $result = DatabaseModel::select([ @@ -221,8 +216,8 @@ class NotificationModelAbstract // 'data' => ['Y'] // ]); $tabDiffusion_Type[] = array( - 'id' => 'group', - 'label' => constant((string)'_GROUP'), + 'id' => 'group', + 'label' => 'Groupe', 'add_attachment' => 'true', //'request' => $result, ); @@ -233,8 +228,8 @@ class NotificationModelAbstract // 'data' => ['Y'] // ]); $tabDiffusion_Type[] = array( - 'id' => 'entity', - 'label' => constant((string)'_ENTITY'), + 'id' => 'entity', + 'label' => 'Entité', 'add_attachment' => 'true', //'request' => $result ); @@ -243,26 +238,26 @@ class NotificationModelAbstract // 'table' => ['status'] // ]); $tabDiffusion_Type[] = array( - 'id' => 'dest_entity', - 'label' => constant((string)'_DEST_ENTITY'), + 'id' => 'dest_entity', + 'label' => 'Service de l\'utilisateur destinataire', 'add_attachment' => 'false', //'request' => $result ); $tabDiffusion_Type[] = array( - 'id' => 'dest_user', - 'label' => constant((string)'_DEST_USER'), + 'id' => 'dest_user', + 'label' => 'Liste de diffusion du document', 'add_attachment' => 'false', //'request' => $result ); $tabDiffusion_Type[] = array( - 'id' => 'dest_user_visa', - 'label' => constant((string)'_DEST_USER_VISA'), + 'id' => 'dest_user_visa', + 'label' => 'Viseur actuel du document', 'add_attachment' => 'true', //'request' => $result ); $tabDiffusion_Type[] = array( - 'id' => 'dest_user_sign', - 'label' => constant((string)'_DEST_USER_SIGN'), + 'id' => 'dest_user_sign', + 'label' => 'Signataire actuel du document', 'add_attachment' => 'true', //'request' => $result ); @@ -271,73 +266,71 @@ class NotificationModelAbstract // 'table' => ['users'] // ]); $tabDiffusion_Type[] = array( - 'id' => 'user', - 'label' => constant((string)'_USER'), + 'id' => 'user', + 'label' => 'Utilisateur désigné', 'add_attachment' => 'true', //'request' => $result ); - $result = []; - $tabDiffusion_Type[] = array( - 'id' => 'note_dest_user', - 'label' => constant((string)'_NOTE_DEST_USER'), - 'add_attachment' => 'false', - //'request' => $result - ); + $tabDiffusion_Type[] = array( - 'id' => 'note_copy_list', - 'label' => constant((string)'_NOTE_COPY_LIST'), + 'id' => 'copy_list', + 'label' => 'Liste de diffusion du document', 'add_attachment' => 'false', //'request' => $result ); + + $result = []; + $tabDiffusion_Type[] = array( - 'id' => 'contact', - 'label' => constant((string)'_CONTACT'), + 'id' => 'contact', + 'label' => 'Contact du document', 'add_attachment' => 'true', //'request' => $result ); - return $tabDiffusion_Type; - } public static function getDiffusionTypeGroups() { $groups = GroupModel::get(); + return $groups; } public static function getDiffusionTypesUsers() { $users = DatabaseModel::select([ - 'select' => ["user_id as id, concat(firstname,' ',lastname) as label"], - 'table' => ['users'] + 'select' => ["user_id as id, concat(firstname,' ',lastname) as label"], + 'table' => ['users'], ]); + return $users; } public static function getDiffusionTypeEntities() { $entities = EntityModel::get(); + return $entities; } public static function getDiffusionTypeStatus() { $status = StatusModel::get(); + return $status; } public static function getEnableNotifications(array $aArgs = []) { $aReturn = DatabaseModel::select([ - 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], - 'table' => ['notifications'], - 'where' => ['is_enabled = ?'], - 'data' => ['Y'] + 'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'], + 'table' => ['notifications'], + 'where' => ['is_enabled = ?'], + 'data' => ['Y'], ]); return $aReturn; } - } diff --git a/src/app/notification/models/NotificationScheduleModelAbstract.php b/src/app/notification/models/NotificationScheduleModelAbstract.php index 3c53ce9dd0a..f875e730a08 100644 --- a/src/app/notification/models/NotificationScheduleModelAbstract.php +++ b/src/app/notification/models/NotificationScheduleModelAbstract.php @@ -1,17 +1,17 @@ <?php /** -* Copyright Maarch since 2008 under licence GPLv3. -* See LICENCE.txt file at the root folder for more details. -* This file is part of Maarch software. -* -*/ + * Copyright Maarch since 2008 under licence GPLv3. + * See LICENCE.txt file at the root folder for more details. + * This file is part of Maarch software. + */ /** -* @brief Notifications Model -* @author dev@maarch.org -* @ingroup Module -*/ + * @brief Notifications Model + * + * @author dev@maarch.org + * @ingroup Module + */ namespace Notification\models; @@ -50,10 +50,10 @@ class NotificationScheduleModelAbstract HistoryController::add([ 'tableName' => 'notifications', - 'recordId' => $GLOBALS['userId'], + 'recordId' => $GLOBALS['userId'], 'eventType' => 'UP', - 'eventId' => 'notificationadd', - 'info' => _NOTIFICATION_SCHEDULE_UPDATED + 'eventId' => 'notificationadd', + 'info' => _NOTIFICATION_SCHEDULE_UPDATED, ]); return true; @@ -61,17 +61,17 @@ class NotificationScheduleModelAbstract public static function getCrontab(array $aArgs = []) { - if (!isset($aArgs["setHiddenValue"])) { - $aArgs["setHiddenValue"] = true; + if (!isset($aArgs['setHiddenValue'])) { + $aArgs['setHiddenValue'] = true; } - $crontab = shell_exec('crontab -l'); + $crontab = shell_exec('crontab -l'); // TODO check crontab is installed - $lines = explode("\n", $crontab); - $data = array(); + $lines = explode("\n", $crontab); + $data = array(); $customId = CoreConfigModel::getCustomId(); - $corePath = str_replace("custom/".$customId."/src/app/notification/models", "", __DIR__); - $corePath = str_replace("src/app/notification/models", "", $corePath); + $corePath = str_replace('custom/'.$customId.'/src/app/notification/models', '', __DIR__); + $corePath = str_replace('src/app/notification/models', '', $corePath); foreach ($lines as $cronLine) { $cronLine = trim($cronLine); @@ -89,28 +89,32 @@ class NotificationScheduleModelAbstract list($m, $h, $dom, $mon, $dow, $cmd) = explode(' ', $cronLine, 6); } - if ($customId <> '') { - $pathToFolow = $corePath . 'custom/'.$customId . '/'; + if ($customId != '') { + $pathToFolow = $corePath.'custom/'.$customId.'/'; } else { $pathToFolow = $corePath; } - $state = "normal"; - if (strpos($cmd, $pathToFolow.'modules/notifications/batch/scripts/') !== 0 && $aArgs["setHiddenValue"]) { - $cmd = "hidden"; + $state = 'normal'; + if (strpos($cmd, $pathToFolow.'modules/notifications/batch/scripts/') !== 0 && $aArgs['setHiddenValue']) { + $cmd = 'hidden'; $state = 'hidden'; } + $filename = explode('/', $cmd); + $data[] = array( - 'm' => $m, - 'h' => $h, - 'dom' => $dom, - 'mon' => $mon, - 'dow' => $dow, - 'cmd' => $cmd, - 'state' => $state + 'm' => $m, + 'h' => $h, + 'dom' => $dom, + 'mon' => $mon, + 'dow' => $dow, + 'cmd' => $cmd, + 'description' => end($filename), + 'state' => $state, ); } + return $data; } @@ -120,31 +124,31 @@ class NotificationScheduleModelAbstract ValidatorModel::intVal($aArgs, ['notification_sid']); $notification_sid = $aArgs['notification_sid']; - $notification_id = $aArgs['notification_id']; + $notification_id = $aArgs['notification_id']; //Creer le script sh pour les notifications - $filename = "notification"; + $filename = 'notification'; $customId = CoreConfigModel::getCustomId(); - if (isset($customId) && $customId<>"") { - $filename.="_".str_replace(" ", "", $customId); + if (isset($customId) && $customId != '') { + $filename .= '_'.str_replace(' ', '', $customId); } - $filename.="_".$notification_sid.".sh"; + $filename .= '_'.$notification_id.'.sh'; - $corePath = str_replace("custom/".$customId."/src/app/notification/models", "", __DIR__); - $corePath = str_replace("src/app/notification/models", "", $corePath); + $corePath = str_replace('custom/'.$customId.'/src/app/notification/models', '', __DIR__); + $corePath = str_replace('src/app/notification/models', '', $corePath); - if (file_exists($corePath. 'custom/'.$customId .'/modules/notifications/batch/config/config.xml')) { - $ConfigNotif = $corePath. 'custom/'. $customId .'/modules/notifications/batch/config/config.xml'; - } elseif (file_exists($corePath. 'custom/'. $customId .'/modules/notifications/batch/config/config_'.$customId.'.xml')) { - $ConfigNotif = $corePath. 'custom/'. $customId .'/modules/notifications/batch/config/config_'.$customId.'.xml'; - } elseif (file_exists($corePath. 'modules/notifications/batch/config/config_'.$customId.'.xml')) { - $ConfigNotif = $corePath. 'modules/notifications/batch/config/config_'.$customId.'.xml'; + if (file_exists($corePath.'custom/'.$customId.'/modules/notifications/batch/config/config.xml')) { + $ConfigNotif = $corePath.'custom/'.$customId.'/modules/notifications/batch/config/config.xml'; + } elseif (file_exists($corePath.'custom/'.$customId.'/modules/notifications/batch/config/config_'.$customId.'.xml')) { + $ConfigNotif = $corePath.'custom/'.$customId.'/modules/notifications/batch/config/config_'.$customId.'.xml'; + } elseif (file_exists($corePath.'modules/notifications/batch/config/config_'.$customId.'.xml')) { + $ConfigNotif = $corePath.'modules/notifications/batch/config/config_'.$customId.'.xml'; } else { - $ConfigNotif = $corePath. 'modules/notifications/batch/config/config.xml'; + $ConfigNotif = $corePath.'modules/notifications/batch/config/config.xml'; } - - if ($customId <> '') { - $pathToFolow = $corePath . 'custom/'.$customId . '/'; + + if ($customId != '') { + $pathToFolow = $corePath.'custom/'.$customId.'/'; if (!file_exists($pathToFolow.'modules/notifications/batch/scripts/')) { mkdir($pathToFolow.'modules/notifications/batch/scripts/', 0777, true); } @@ -175,14 +179,14 @@ class NotificationScheduleModelAbstract fwrite($file_open, 'php \'process_email_stack.php\' -c '.$ConfigNotif); fwrite($file_open, "\n"); fclose($file_open); - shell_exec("chmod +x " . escapeshellarg($pathToFolow . "modules/notifications/batch/scripts/" . $filename)); + shell_exec('chmod +x '.escapeshellarg($pathToFolow.'modules/notifications/batch/scripts/'.$filename)); HistoryController::add([ 'tableName' => 'notifications', - 'recordId' => $notification_id, + 'recordId' => $notification_id, 'eventType' => 'ADD', - 'eventId' => 'notificationadd', - 'info' => _NOTIFICATION_SCRIPT_ADDED + 'eventId' => 'notificationadd', + 'info' => _NOTIFICATION_SCRIPT_ADDED, ]); return true; -- GitLab