MasterClass/application/controllers/reports/Subscribers.php
2025-07-29 15:53:43 +03:00

615 lines
22 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
use app\core\utils\Response;
use app\core\auth\Page;
//require phpoffice library(Spreadsheet and Writer)
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
//require excel styles
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
//require excel protection for lock/unlock
use PhpOffice\PhpSpreadsheet\Style\Protection;
//require excel contitions
use PhpOffice\PhpSpreadsheet\Style\Conditional;
//require excel datavalidations
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
class Subscribers extends MY_Controller {
/**
* php excel object instance variables
*
* @var string
*/
private $spreadsheet;
/**
* no show excel file tabs
*
* @var string
*/
private $reports;
/**
* instance variable for PhpOffice writer class
*
* @var string
*/
private $writer;
/**
* instance variable for activesheet
*
* @var string
*/
private $sheets;
/**
* variable for default background color
*
* @var string
*/
private $default_background_color;
/**
* Tab title
*
* @var string
*/
private $sheetTitle;
/**
* Holds default maximum row
*
* @var int
*/
private $defaultMaximumRow;
/**
* Holds default column headers
*
* @var array
*/
private $columnHeaders;
/**
* Cells Index Name
*
* @var array
*/
private $basicCells;
/**
* EXCEL PASSWORD PROTECTION THIS IS CONFIDENTIAL
*/
private const PASSWORD = '1@#]00YHkBlackHatzZ';
public function __construct() {
//parent::__construct();
$this->my_parent_controller();
$this->load->model("user_model");
$this->clear_cache();
$this->lang->load('backoffice/reports', 'fr');
// Create new PHPExcel object
$this->spreadsheet = new Spreadsheet();
//get active sheet
$this->sheets = $this->spreadsheet->getActiveSheet();
//create writer object
$this->writer = new Xlsx($this->spreadsheet);
// Set sheet name
$this->sheetTitle = $this->lang->line("reports")["client"]["client_file_name"];
//set default background color
$this->default_background_color = '428bcb';
$this->columnHeaders = array(
"civility",
"last_name",
"first_name",
"address",
"code_postal",
"city",
"telephone_number",
"email_address"
);
$this->basicCells = 'ABCDEFGH';
}
/**
* Set execution and memory limit
*
* @return void
* access public
*/
public function setMemoryLimit()
{
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', (60*3));
}
/**
* Set document properties
*
* @return void
* access public
*/
public function setDocumentProperties()
{
return $this->spreadsheet->getProperties()->setCreator("Company For Madagascar Event Management System")
->setLastModifiedBy("Company For Madagascar Event Management System")
->setTitle("Office 2007 XLSX Document")
->setSubject("Office 2007 XLSX Document")
->setDescription("No show export import file")
->setKeywords("office 2007 openxml php")
->setCategory("Export file");
}
/**
* Set headers(pragma, cache control , cookies etc..)
*
* @param string $filename
* @return void
*/
public function setHeaders($filename)
{
// Redirect output to a clients web browser (Excel2007)
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
header('Cache-Control: max-age=0');
// header('Content-Encoding: deflate, gzip');
header('Cache-Control: private');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$this->writer->save('php://output');
exit();
}
/**
* Auto size columns for each worksheet
*
* @return void
* access public
*/
public function setExcelAutoSize()
{
foreach ($this->spreadsheet->getWorksheetIterator() as $worksheet) {
$this->spreadsheet->setActiveSheetIndex($this->spreadsheet->getIndex($worksheet));
$sheet = $this->sheets;
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
$sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}
}
}
/**
* Set excel main headers (first rows 1 - 2 with freeze pane)
*
* @param integer $eventID
* @param integer $eventScheduleID
* @param string $event_title
* @return void
* access private member
*/
private function setExcelHeaders()
{
$this->sheets->getRowDimension(1)->setRowHeight(-1);
foreach(range('A','H') as $columnID) {
$this->sheets->getColumnDimension($columnID)->setAutoSize(true);
}
// Merge and Set Header Cell values
$this->sheets->freezePane('D3')->setTitle($this->sheetTitle);
if(count($this->columnHeaders) > 0) {
$colCount = 0;
foreach($this->columnHeaders as $fcol => $name) {
$columnName = $this->basicCells{$colCount};
$this->sheets->setCellValue("{$columnName}1", mb_strtoupper($this->lang->line($name)));
$colCount++;
// if($name == "subscription_date_op" ) {
// $this->sheets->setCellValue('L2', mb_strtoupper('Date').' d\'inscription'); // L2
// $this->sheets->setCellValue('M2', mb_strtoupper('Heure').' d\'inscription'); // M2
// $colCount = 13;
// } else {
// if($colCount < 26) { // A1:A2 - Z1:Z2
// $columnName = $this->basicCells{$colCount};
// $this->sheets->setCellValue("{$columnName}1", mb_strtoupper($this->lang->line($name)))->mergeCells("{$columnName}1:{$columnName}2");
// $colCount++;
// }else { // AA1 AB1 AC1
// $columnName = substr($this->basicCells, $colCount, 2);
// $this->sheets->setCellValue("{$columnName}1", mb_strtoupper($this->lang->line($name)))->mergeCells("{$columnName}1:{$columnName}2");
// $colCount = $colCount + 2;
// }
// }
}
}
$generalStyleArray = [
'font' => [
'bold' => false,
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'rotation' => 90,
'startColor' => [
'argb' => '428bca',
],
'endColor' => [
'argb' => '428bca',
],
],
];
$boderStyle = ['borderStyle' => Border::BORDER_THIN];
$boderStyleArray = [
'borders' => [
'top' => $boderStyle,
'right' => $boderStyle,
'left' => $boderStyle,
'bottom' => $boderStyle
]
];
// set style
$this->sheets->getStyle('A2:H2')->applyFromArray($generalStyleArray);
$this->sheets->getStyle('A1:H1')->applyFromArray($generalStyleArray);
// $this->sheets->getStyle('L2:M2')->applyFromArray($boderStyleArray);
}
public function reportData($queryData) {
$subscribers = $this->user_model->get_subscriber_information_list_export($this->data["logged_in"]["user_id"], $queryData, 4);
$intValueColumns = ['number_of_user_and_guest', 'avg_number_of_registration', 'number_of_registration', 'total_number_of_reservations_places_cancelled', 'number_of_places_reserved_on_wl'];
$active_sheet = $this->spreadsheet->setActiveSheetIndex(0);
// print_r($subscribers);
// exit;
if(count($subscribers) > 0)
{
// Row starts at 3
$cell_row_index = 3;
foreach($subscribers as $epd) {
$colCount = 0;
foreach($this->columnHeaders as $fcol => $name) {
// if ($name === "subscription_date_op") {
// $val = ($epd->{$name} != "") ? explode(" ", $epd->{$name}) : array();
// $date = (isset($val[0]))?$val[0]:"";
// $hour = (isset($val[1]))?$val[1]:"";
// $active_sheet->setCellValue("L{$cell_row_index}", $date); // L{$cell_row_index}
// $active_sheet->setCellValue("M{$cell_row_index}", $hour); // M{$cell_row_index}
// $colCount = 13;
// } else {
$value = "";
if (trim($name) != "" && isset($epd->{$name}) && !empty($epd->{$name})) {
$value = $epd->{$name};
}
// if($colCount < 26) { // A1:A2 - Z1:Z2
$columnName = $this->basicCells{$colCount};
$active_sheet->setCellValue("{$columnName}{$cell_row_index}", $value);
$colCount++;
// } else { // AA1 AB1 AC1
// $columnName = substr($this->basicCells, $colCount, 2);
// $active_sheet->setCellValue("{$columnName}{$cell_row_index}", $value);
// $colCount = $colCount + 2;
// }
// }
} // Enf of inner loop
$cell_row_index++;
} // End of outer loop
}
}
/**
* Export no show file with title+date
*
* @param integer $eventID
* @param integer $eventScheduleID
* @return void
* access private member
*/
public function export_subscribers_list($queryString)
{
// Parse URL data
parse_str($queryString, $queryData);
//call memory limit
$this->setMemoryLimit();
//call document properties
$this->setDocumentProperties();
//set php excel first 5 row(s) with freeze header
$this->setExcelHeaders();
//get data for populate
$this->reportData($queryData);
//Call auto size function columns for active worksheet
$this->setExcelAutoSize();
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$this->spreadsheet->setActiveSheetIndex(0);
// protect the workbok
$this->spreadsheet->getSecurity()->setLockWindows(true);
$this->spreadsheet->getSecurity()->setLockStructure(true);
$this->spreadsheet->getSecurity()->setWorkbookPassword('secret');
$this->setHeaders("La liste client (".date('d-m-Y H\hi').")");
}
public function get_subscribers_list()
{
Response::handleSessionTimeout("bo");
$this->load->model('event_registration_limit_model');
$this->load->model('user_registration_model');
$this->load->model('user_subscriber_model');
//$list = $this->user_subscriber_model->getSubscribers();
$list = $this->user_model->get_datatables($this->data["logged_in"]["user_id"], $this->input->post(), 3);
$login_by = $this->data["logged_in"]["user_id"];
$user_role = $this->data["logged_in"]["role_id"];
$style = ($user_role == '2') ? 'display:none;': '';
$roles = $this->user_registration_model->get_subscriber_roles();
$data = $row = array();
foreach ($list as $subscribers) {
$row["subscriber"] = "{$subscribers->first_name} {$subscribers->last_name}";
$row["email_address"] = $subscribers->email_address;
// $row["membership"] = $this->user_registration_model->get_membership_name($subscribers->subscription_id, $roles);
// $row["expiration_date"] = $subscribers->expiration_date;
// $row["birth_date"] = $subscribers->birth_date;
$row["telephone_number"] = (trim($subscribers->telephone_number) != "+[33] X XX XX XX XX" ? trim(remove_brackets(array( '[', ']' ), (strpos($subscribers->telephone_number, '+') !== false ? $subscribers->telephone_number : ( trim($subscribers->telephone_number) !="" ? "+".$subscribers->telephone_number : "" ) ) )) : "");
// $row["mobile_number"] =(trim($subscribers->mobile_number) != "+[33] X XX XX XX XX" ? trim(remove_brackets(array( '[', ']' ),(strpos($subscribers->mobile_number, '+') !== false ? $subscribers->mobile_number : ( trim($subscribers->mobile_number) !="" ? "+".$subscribers->mobile_number : "") ))) : "");
$row["address"] = $subscribers->address;
// $row["noshow_complete"] = $subscribers->noshow_complete;
// $row["noshow_partial"] = $subscribers->noshow_partial;
// $row["noshow_moderation"] = $subscribers->noshow_moderation;
// $row["status"] = $subscribers->status;
$row["actions"] = '';
// if (Page::authorize(PAGE_CODE['subscribers'], PRIVS[PAGE_CODE['subscribers']]['edit'], false)) {
// $row["actions"] .= "<button href='#' onclick='subscribers_list.edit_subscription_modal({$subscribers->sub_id})' class='action-btn' name='membership-{$subscribers->subscriber_id}' data-id='{$subscribers->sub_id}' ><i class='fa fa-euro' aria-hidden='true'></i></button>";
// }
if (Page::authorize(PAGE_CODE['subscribers'], PRIVS[PAGE_CODE['subscribers']]['edit'], false)) {
$row["actions"] .= "<button href='#' onclick='subscribers_list.edit_info_modal(this)' class='action-btn' name='{$subscribers->subscriber_id}' data-id='{$subscribers->sub_id}' ><i class='fa fa-pencil' aria-hidden='true'></i></button>";
}
if (Page::authorize(PAGE_CODE['subscribers'], PRIVS[PAGE_CODE['subscribers']]['delete'], false)) {
$row["actions"] .= "<button style='{$style}' href = '#' onclick = 'subscribers_list.delete(this)' class='action-btn' name = '{$row["subscriber"]}' data-id = '{$subscribers->sub_id}' ><i class='fa fa-trash' aria-hidden = 'true' ></i ></button>";
}
// if (Page::authorize(PAGE_CODE['subscribers'], PRIVS[PAGE_CODE['subscribers']]['login_as'], false)) {
// $row["actions"] .= "<button href='#' onclick='subscribers_list.token_modal(this)' id='$subscribers->sub_id' class='action-btn' name='{$row["subscriber"]}' data-id='auth_token/{$subscribers->sub_id}/{$login_by}'><i class='fa fa-sign-in' aria-hidden='true'></i></button>";
// }
// if (Page::authorize(PAGE_CODE['subscribers'], PRIVS[PAGE_CODE['subscribers']]['mod_toggle'], false)) {
// $row["actions"] .= "<button href='#' onclick='subscribers_list.disableEnableModeration(this)' data-name='{$row["subscriber"]}' class='action-btn disableEnableModeration' name='{$subscribers->subscriber_id}' data-id='{$subscribers->sub_id}' ><i class='fa fa-unlock-alt' aria-hidden='true'></i></button>";
// }
array_push($data, $row);
}
$output = array(
"draw" => $this->input->post('draw'),
"recordsTotal" => $this->user_model->count_all($this->data["logged_in"]["user_id"], $this->input->post(), 3),
"recordsFiltered" => $this->user_model->count_filtered($this->data["logged_in"]["user_id"], $this->input->post(), 3),
"data" => $data,
);
//output to json format
output_to_json($this, $output);
}
public function delete_subscriber()
{
Response::handleSessionTimeout("bo");
$deleted = $this->user_model->delete_subscribers( $this->input->post('user_id') , ["status" => 0]);
output_to_json($this,
array(
'is_success' => $deleted
)
);
}
public function get_subscriber()
{
Response::handleSessionTimeout("bo");
output_to_json($this, $this->user_model->get_subscribers( $this->input->post('s_id') ));
}
public function put_subscriber()
{
Response::handleSessionTimeout("bo");
// if(_empty_prefix($this->input->post("phone"))){
// output_to_json($this, array(
// "error" => true,
// "field" => "phone",
// "message" => "Entrez au moins 9 chiffres."
// ));
// }else if(_empty_prefix($this->input->post("mobile"))){
// output_to_json($this, array(
// "error" => true,
// "field" => "mobile",
// "message" => "Entrez au moins 9 chiffres."
// ));
//}else{
$this->user_model->put_subscribers($this->input->post('user_id'), $this->input->post());
output_to_json($this, array(
"success" => true
));
//}
}
public function enable_disable_user_moderation() {
Response::handleSessionTimeout("bo");
$this->load->model('user_subscriber_model');
output_to_json($this, array(
"success" => $this->user_subscriber_model->enable_disable_user_moderation( $this->input->post() )
));
}
public function get_user_moderation($subscriber_id) {
Response::handleSessionTimeout("bo");
$this->load->model('user_subscriber_model');
output_to_json($this, $this->user_subscriber_model->get_user_moderation( $subscriber_id ));
}
private function setSubscriberExcelHeaders()
{
$this->sheets->getRowDimension(1)->setRowHeight(-1);
foreach(range('A','B') as $columnID) {
$this->sheets->getColumnDimension($columnID)->setAutoSize(true);
}
// Merge and Set Header Cell values
$requiredCells = 'ABC';
$colCount = 0;
$columns =['#', 'EMAIL', 'DATE'];
foreach($columns as $fcol => $name) {
$columnName = substr($requiredCells, $colCount, 1);
$this->sheets->setCellValue("{$columnName}1", $name);
$colCount++;
}
$generalStyleArray = [
'font' => [
'bold' => false,
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'rotation' => 90,
'startColor' => [
'argb' => '428bca',
],
'endColor' => [
'argb' => '428bca',
],
],
];
$boderStyle = ['borderStyle' => Border::BORDER_THIN];
$boderStyleArray = [
'borders' => [
'top' => $boderStyle,
'right' => $boderStyle,
'left' => $boderStyle,
'bottom' => $boderStyle
]
];
// set style
$this->sheets->getStyle('A2:C2')->applyFromArray($generalStyleArray);
$this->sheets->getStyle('A1:C1')->applyFromArray($generalStyleArray);
// $this->sheets->getStyle('L2:M2')->applyFromArray($boderStyleArray);
}
public function export_subscribers_info() {
Response::handleSessionTimeout("bo");
$event_id = $this->input->get('event_id');
if(!isset($event_id)) {
//
}
//call memory limit
$this->setMemoryLimit();
//call document properties
$this->setDocumentProperties();
//set php excel first 5 row(s) with freeze header
$this->setSubscriberExcelHeaders();
//get data for populate
$this->get_event_subscribers($event_id);
//Call auto size function columns for active worksheet
$this->setExcelAutoSize();
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$this->spreadsheet->setActiveSheetIndex(0);
// protect the workbok
$this->spreadsheet->getSecurity()->setLockWindows(true);
$this->spreadsheet->getSecurity()->setLockStructure(true);
$this->spreadsheet->getSecurity()->setWorkbookPassword('secret');
$this->setHeaders("La liste client (".date('d-m-Y H\hi').")");
}
private function get_event_subscribers($event_id) {
$this->load->model('event_workshop_informer_model');
$subscribers = $this->event_workshop_informer_model->get_subscribers_by_event($event_id);
$active_sheet = $this->spreadsheet->setActiveSheetIndex(0);
$requiredCells = 'ABC';
if(count($subscribers) > 0)
{
// Row starts at 3
$cell_row_index = 3;
$columns = ['#', 'EMAIL', 'DATE'];
foreach($subscribers as $epd) {
$colCount = 0;
foreach($columns as $fcol => $name) {
$active_sheet->setCellValue("A{$cell_row_index}", $cell_row_index-2);
$active_sheet->setCellValue("B{$cell_row_index}", $epd->email_address); // L{$cell_row_index}
$active_sheet->setCellValue("C{$cell_row_index}", $epd->date_created);
} // Enf of inner loop
$cell_row_index++;
} // End of outer loop
}
}
}