-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_chat.php
More file actions
287 lines (236 loc) · 9.06 KB
/
process_chat.php
File metadata and controls
287 lines (236 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<?php
header('Content-Type: application/json');
// Increase memory limit and execution time for large files
ini_set('memory_limit', '256M');
ini_set('max_execution_time', 120);
// Get POST parameters
$contactFile = $_POST['contactFile'] ?? null;
$chartType = $_POST['chartType'] ?? null;
$groupBy = $_POST['groupBy'] ?? null;
// Input validation
if (!$contactFile || !$chartType || !$groupBy) {
echo json_encode(['error' => 'Missing required parameters']);
exit;
}
// Security: Construct file path and validate
$chatsDir = __DIR__ . '/chats/';
$filePath = $chatsDir . $contactFile;
// Use realpath to resolve any path traversal attempts
$realPath = realpath($filePath);
$realChatsDir = realpath($chatsDir);
if (!$realPath || !$realChatsDir || strpos($realPath, $realChatsDir) !== 0) {
echo json_encode(['error' => 'Invalid file path']);
exit;
}
// Check if file exists
if (!file_exists($realPath)) {
echo json_encode(['error' => 'Chat file not found']);
exit;
}
// Initialize data structure
$dailyMessageCounts = [];
// WhatsApp message pattern: "11/11/22, 1:33 AM - Sender Name: message"
// Note: There's a narrow no-break space (U+202F) between time and AM/PM
$messagePattern = '/^(\d{1,2}\/\d{1,2}\/\d{2,4}), \d{1,2}:\d{2}[\s\x{202F}]*[AP]M - ([^:]+): /u';
// Process file line by line for memory efficiency
$handle = fopen($realPath, 'r');
if (!$handle) {
echo json_encode(['error' => 'Unable to open chat file']);
exit;
}
while (($line = fgets($handle)) !== false) {
// Skip empty lines
$line = trim($line);
if (empty($line)) {
continue;
}
// Check if line matches message pattern
if (preg_match($messagePattern, $line, $matches)) {
$dateString = $matches[1];
// Convert date to standard format
try {
// Handle both 2-digit and 4-digit years
$date = DateTime::createFromFormat('n/j/y', $dateString);
if (!$date) {
$date = DateTime::createFromFormat('n/j/Y', $dateString);
}
if ($date) {
$normalizedDate = $date->format('Y-m-d');
// Increment counter
if (isset($dailyMessageCounts[$normalizedDate])) {
$dailyMessageCounts[$normalizedDate]++;
} else {
$dailyMessageCounts[$normalizedDate] = 1;
}
}
} catch (Exception $e) {
// Skip invalid dates
continue;
}
}
}
fclose($handle);
// Sort dates chronologically
ksort($dailyMessageCounts);
// Group data by year
$yearlyData = [];
foreach ($dailyMessageCounts as $date => $count) {
$year = date('Y', strtotime($date));
if (!isset($yearlyData[$year])) {
$yearlyData[$year] = [];
}
$yearlyData[$year][$date] = $count;
}
// Prepare response data grouped by year
$response = [
'years' => [],
'totalMessages' => array_sum($dailyMessageCounts),
'dateRange' => []
];
if (!empty($dailyMessageCounts)) {
$allDates = array_keys($dailyMessageCounts);
$response['dateRange'] = [
'start' => $allDates[0],
'end' => $allDates[count($allDates) - 1]
];
}
foreach ($yearlyData as $year => $yearMessages) {
$yearData = [
'year' => $year,
'totalMessages' => array_sum($yearMessages)
];
if ($groupBy === 'day') {
// Create full year data with zeros for missing days
$yearStart = $year . '-01-01';
$yearEnd = $year . '-12-31';
$fullYearData = [];
$fullYearLabels = [];
$currentDate = new DateTime($yearStart);
$endDate = new DateTime($yearEnd);
while ($currentDate <= $endDate) {
$dateStr = $currentDate->format('Y-m-d');
$fullYearLabels[] = $dateStr;
$fullYearData[] = $yearMessages[$dateStr] ?? 0;
$currentDate->add(new DateInterval('P1D'));
}
$yearData['labels'] = $fullYearLabels;
$yearData['data'] = $fullYearData;
} elseif ($groupBy === 'week') {
// Group by weeks within the year (52 data points with month context)
$weeklyData = [];
$weekDetails = [];
foreach ($yearMessages as $date => $count) {
$timestamp = strtotime($date);
$jan1 = strtotime($year . '-01-01');
$daysDiff = floor(($timestamp - $jan1) / (60 * 60 * 24));
$weekNumber = floor($daysDiff / 7) + 1;
$weekKey = 'W' . sprintf('%02d', $weekNumber);
if (isset($weeklyData[$weekKey])) {
$weeklyData[$weekKey] += $count;
$weekDetails[$weekKey]['endDate'] = $date;
} else {
$weeklyData[$weekKey] = $count;
$weekDetails[$weekKey] = [
'startDate' => $date,
'endDate' => $date
];
}
}
// Create full year of weeks (52-53 weeks) with month-aware labels
$fullWeeklyData = [];
$fullWeeklyLabels = [];
$fullWeekDetails = [];
for ($week = 1; $week <= 53; $week++) {
$weekKey = 'W' . sprintf('%02d', $week);
// Calculate what month this week primarily falls in
$weekStartDay = ($week - 1) * 7 + 1;
$weekDate = mktime(0, 0, 0, 1, $weekStartDay, $year);
$monthName = date('M', $weekDate);
// Create month-aware label (e.g., "Jan W1", "Feb W2")
$weekInYear = $week;
$label = $monthName . ' W' . sprintf('%02d', $weekInYear);
$fullWeeklyLabels[] = $label;
$fullWeeklyData[] = $weeklyData[$weekKey] ?? 0;
if (isset($weekDetails[$weekKey])) {
$fullWeekDetails[] = [
'weekNumber' => $week,
'monthName' => $monthName,
'startDate' => $weekDetails[$weekKey]['startDate'],
'endDate' => $weekDetails[$weekKey]['endDate']
];
} else {
$fullWeekDetails[] = [
'weekNumber' => $week,
'monthName' => $monthName,
'startDate' => null,
'endDate' => null
];
}
}
$yearData['labels'] = $fullWeeklyLabels;
$yearData['data'] = $fullWeeklyData;
$yearData['weekDetails'] = $fullWeekDetails;
} elseif ($groupBy === 'month') {
// Group by months within the year (12 data points)
$monthlyData = [];
$monthDetails = [];
foreach ($yearMessages as $date => $count) {
$timestamp = strtotime($date);
$monthKey = date('Y-m', $timestamp);
$monthName = date('M', $timestamp);
if (isset($monthlyData[$monthKey])) {
$monthlyData[$monthKey] += $count;
$monthDetails[$monthKey]['endDate'] = $date;
} else {
$monthlyData[$monthKey] = $count;
$monthDetails[$monthKey] = [
'name' => $monthName,
'startDate' => $date,
'endDate' => $date
];
}
}
// Create full year of months (Jan-Dec)
$fullMonthlyData = [];
$fullMonthlyLabels = [];
$fullMonthDetails = [];
for ($month = 1; $month <= 12; $month++) {
$monthKey = $year . '-' . sprintf('%02d', $month);
$monthName = date('M', mktime(0, 0, 0, $month, 1, $year));
$fullMonthlyLabels[] = $monthName;
$fullMonthlyData[] = $monthlyData[$monthKey] ?? 0;
if (isset($monthDetails[$monthKey])) {
$fullMonthDetails[] = [
'monthNumber' => $month,
'monthName' => $monthName,
'startDate' => $monthDetails[$monthKey]['startDate'],
'endDate' => $monthDetails[$monthKey]['endDate']
];
} else {
$fullMonthDetails[] = [
'monthNumber' => $month,
'monthName' => $monthName,
'startDate' => null,
'endDate' => null
];
}
}
$yearData['labels'] = $fullMonthlyLabels;
$yearData['data'] = $fullMonthlyData;
$yearData['monthDetails'] = $fullMonthDetails;
}
$response['years'][] = $yearData;
}
// Sort years chronologically
usort($response['years'], function($a, $b) {
return (int)$a['year'] - (int)$b['year'];
});
// Calculate Y-axis max from all processed data
$allProcessedValues = [];
foreach ($response['years'] as $year) {
$allProcessedValues = array_merge($allProcessedValues, $year['data']);
}
$maxValue = empty($allProcessedValues) ? 10 : max($allProcessedValues);
$response['yAxisMax'] = ceil($maxValue * 1.1); // Add 10% padding
echo json_encode($response);
?>