Browse Source

Multiple saloons

AR 7 months ago
parent
commit
7256577c44
9 changed files with 465 additions and 205 deletions
  1. 248 0
      functions.php
  2. 1 0
      history/index.php
  3. 147 48
      index.php
  4. 7 69
      post.php
  5. 26 46
      server.php
  6. 13 0
      setup.ini
  7. 0 1
      tmp/users/flo
  8. 17 0
      update_session.php
  9. 6 41
      users.php

+ 248 - 0
functions.php

@@ -0,0 +1,248 @@
1
+<?php
2
+
3
+function getSetup($key = null, $default_value = null) {
4
+    $arr = parse_ini_file('setup.ini');
5
+    return isset($key) ? (isset($arr[$key])? trim($arr[$key]) : $default_value) : $arr;
6
+}
7
+
8
+
9
+
10
+function get_msg_file_path($saloon)
11
+{
12
+	return dirname( __FILE__ ) .'/history/' . sanitize_file_name('msg_' . $saloon . '.txt');
13
+
14
+}
15
+
16
+function get_session_file_path($saloon)
17
+{
18
+	//return dirname( __FILE__ ) .'/history/' . sanitize_file_name('sessions_' . $saloon . '.txt');
19
+
20
+	// all saloons
21
+	return dirname( __FILE__ ) .'/history/' . sanitize_file_name('sessions.txt');
22
+}
23
+
24
+function get_file_to_lock($file_path)
25
+{
26
+	$hFile = @fopen($file_path . '.lock', 'rb');
27
+	if(!$hFile)
28
+	{
29
+		file_put_contents($file_path . '.lock', '');
30
+		$hFile = @fopen($file_path . '.lock', 'rb');
31
+	}
32
+	return $hFile;
33
+
34
+}
35
+
36
+// read file with share lock
37
+function file_lock_and_get_json($file_path)
38
+{
39
+	$hFile = get_file_to_lock($file_path);
40
+	@flock($hFile, LOCK_SH);
41
+	$contents = @file_get_contents($file_path);
42
+	@flock($hFile, LOCK_UN);
43
+	fclose($hFile);
44
+
45
+	$json = json_decode($contents, true);
46
+
47
+	return $json;
48
+}
49
+
50
+function json_encode_for_save($data)
51
+{
52
+	$json_pretty_option = getSetup('pretty_json', false);
53
+	
54
+	$json_options = $json_pretty_option ? JSON_PRETTY_PRINT : 0;
55
+	
56
+	return json_encode($data, $json_options);
57
+	
58
+}
59
+
60
+// append message with exclusive lock
61
+function file_lock_and_append_msg($file_path, $msg)
62
+{
63
+	$hFile = get_file_to_lock($file_path);
64
+	@flock($hFile, LOCK_EX);
65
+
66
+	// read entire file
67
+	$string = @file_get_contents($file_path);
68
+	$json_msgs = json_decode($string, true);
69
+
70
+	// append message
71
+	$json_msgs['msgs'][] = $msg;
72
+
73
+	file_put_contents($file_path, json_encode_for_save($json_msgs));
74
+
75
+	@flock($hFile, LOCK_UN);
76
+	fclose($hFile);
77
+
78
+	return true;
79
+}
80
+
81
+function file_lock_and_update_session($file_path, $session)
82
+{
83
+	$hFile = get_file_to_lock($file_path);
84
+	@flock($hFile, LOCK_EX);
85
+
86
+	// read entire file
87
+	$string = @file_get_contents($file_path);
88
+	$json_sessions = json_decode($string, true);
89
+
90
+
91
+	// update our session
92
+	$json_sessions[$session['session_id']] = $session;
93
+
94
+	$json_sessions = update_sessions_status($json_sessions);
95
+
96
+
97
+	file_put_contents($file_path, json_encode_for_save($json_sessions));
98
+
99
+	@flock($hFile, LOCK_UN);
100
+	fclose($hFile);
101
+
102
+	return true;
103
+
104
+}
105
+
106
+// mark idle sessions and delete old ones
107
+function update_sessions_status($json_sessions)
108
+{
109
+	if(!$json_sessions) return array();
110
+
111
+	$delete_ids = array();
112
+	foreach ($json_sessions as $session_id => $session)
113
+	{
114
+		$delta_second = time() - $session['last_update'];
115
+
116
+		$session['idle'] = ($delta_second > getSetup('warning_idle_session_seconds', 20))?'true':'false';
117
+
118
+		if($delta_second > getSetup('max_idle_session_seconds', 5*60))
119
+		{
120
+			$delete_ids [] = $session_id;
121
+		}
122
+	}
123
+
124
+	foreach($delete_ids as $delete_id)
125
+	{
126
+		unset($json_sessions[$delete_id]);
127
+	}
128
+
129
+	return $json_sessions;
130
+}
131
+
132
+function stripslashes_deep($value)
133
+{
134
+    $value = is_array($value) ?
135
+                array_map('stripslashes_deep', $value) :
136
+                stripslashes($value);
137
+
138
+    return $value;
139
+}
140
+
141
+//  $_POST value, dealing with magic quotes
142
+function get_post_var($name)
143
+{
144
+	$value = $_POST[$name];
145
+	if (get_magic_quotes_gpc())
146
+	{
147
+		$value = stripslashes_deep($value);
148
+	}
149
+	return $value;
150
+
151
+}
152
+
153
+
154
+
155
+
156
+/**
157
+ * Sanitizes a filename, replacing whitespace with dashes.
158
+ *
159
+ * Removes special characters that are illegal in filenames on certain
160
+ * operating systems and special characters requiring special escaping
161
+ * to manipulate at the command line. Replaces spaces and consecutive
162
+ * dashes with a single dash. Trims period, dash and underscore from beginning
163
+ * and end of filename. It is not guaranteed that this function will return a
164
+ * filename that is allowed to be uploaded.
165
+ *
166
+ * @since 2.1.0
167
+ *
168
+ * @param string $filename The filename to be sanitized
169
+ * @return string The sanitized filename
170
+ */
171
+function sanitize_file_name( $filename )
172
+ {
173
+        $filename_raw = $filename;
174
+        $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));
175
+        /**
176
+         * Filters the list of characters to remove from a filename.
177
+         *
178
+         * @since 2.8.0
179
+         *
180
+         * @param array  $special_chars Characters to remove.
181
+         * @param string $filename_raw  Filename as it was passed into sanitize_file_name().
182
+         */
183
+        //$special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
184
+        $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
185
+        $filename = str_replace( $special_chars, '', $filename );
186
+        $filename = str_replace( array( '%20', '+' ), '-', $filename );
187
+        $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
188
+        $filename = trim( $filename, '.-_' );
189
+
190
+//        if ( false === strpos( $filename, '.' ) ) {
191
+//                $mime_types = wp_get_mime_types();
192
+//                $filetype = wp_check_filetype( 'test.' . $filename, $mime_types );
193
+//                if ( $filetype['ext'] === $filename ) {
194
+//                        $filename = 'unnamed-file.' . $filetype['ext'];
195
+//                }
196
+
197
+//        }
198
+
199
+		return $filename;
200
+
201
+        // Split the filename into a base and extension[s]
202
+        $parts = explode('.', $filename);
203
+
204
+        // Return if only one extension
205
+        if ( count( $parts ) <= 2 ) {
206
+                /**
207
+                 * Filters a sanitized filename string.
208
+                 *
209
+                 * @since 2.8.0
210
+                 *
211
+                 * @param string $filename     Sanitized filename.
212
+                 * @param string $filename_raw The filename prior to sanitization.
213
+                 */
214
+//                return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
215
+        }
216
+
217
+        // Process multiple extensions
218
+        $filename = array_shift($parts);
219
+        $extension = array_pop($parts);
220
+        $mimes = get_allowed_mime_types();
221
+
222
+        /*
223
+         * Loop over any intermediate extensions. Postfix them with a trailing underscore
224
+         * if they are a 2 - 5 character long alpha string not in the extension whitelist.
225
+         */
226
+        foreach ( (array) $parts as $part) {
227
+                $filename .= '.' . $part;
228
+
229
+                if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
230
+                        $allowed = false;
231
+                        foreach ( $mimes as $ext_preg => $mime_match ) {
232
+                                $ext_preg = '!^(' . $ext_preg . ')$!i';
233
+                                if ( preg_match( $ext_preg, $part ) ) {
234
+                                        $allowed = true;
235
+                                        break;
236
+                                }
237
+                        }
238
+                        if ( !$allowed )
239
+                                $filename .= '_';
240
+                }
241
+        }
242
+        $filename .= '.' . $extension;
243
+        /** This filter is documented in wp-includes/formatting.php */
244
+        return apply_filters('sanitize_file_name', $filename, $filename_raw);
245
+}
246
+
247
+
248
+?>

+ 1 - 0
history/index.php

@@ -0,0 +1 @@
1
+<?php //Silence ?>

+ 147 - 48
index.php

@@ -7,6 +7,10 @@ function loginForm() {
7 7
 		<p>Please enter your name to continue:</p>
8 8
 		<label for="name">Name:</label>
9 9
 		<input type="text" name="name" id="name" autofocus />
10
+		<p>
11
+		   <label for="saloon">Saloon:</label>
12
+		   <input type="text" name="saloon" id="saloon" />
13
+		</p>
10 14
 		<input type="submit" name="enter" id="enter" value="Enter" />
11 15
 	</form>
12 16
 	</div>
@@ -18,15 +22,6 @@ function getSetup($key = null) {
18 22
 	return isset($key) ? $arr[$key] : $arr;
19 23
 }
20 24
 
21
-function deleteOldHistory() {
22
-	$expireHistory = getSetup('expire_history');
23
-	$expireDate = date('Y-m-d', strtotime("-$expireHistory day"));
24
-	foreach (glob('./history/*') as $f) {
25
-		if (basename($f) < $expireDate) {
26
-			unlink($f);
27
-		}
28
-	}
29
-}
30 25
 
31 26
 
32 27
 
@@ -42,6 +37,7 @@ if (isset($_GET['logout'])) {
42 37
 if (isset($_POST['enter'])) {
43 38
 	if ($_POST['name'] != "") {
44 39
 		$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
40
+		$_SESSION['saloon'] = stripslashes(htmlspecialchars($_POST['saloon']));
45 41
 	} else {
46 42
 		echo '<span class="error">Please type in a name</span>';
47 43
 	}
@@ -57,9 +53,8 @@ if (isset($_POST['enter'])) {
57 53
     </head>
58 54
 
59 55
 <?php
60
-if (!isset($_SESSION['name'])) {
56
+if (!isset($_SESSION['name']) || !isset($_SESSION['saloon'])) {
61 57
 	loginForm();
62
-	deleteOldHistory();
63 58
 } else {
64 59
 ?>
65 60
 	<div id="wrapper">
@@ -72,7 +67,13 @@ if (!isset($_SESSION['name'])) {
72 67
 	    </div>	
73 68
 	    <div id="datbox">
74 69
 	    	<div id="chatbox"></div>
75
-		<div id="usrlist"><b>Fameux connectés :</b><br><br><div id="usrs"></div></div>
70
+		<div id="usrlist">
71
+			<b>Fameux connectés dans ce salon (<span id='current_saloon' ></span>):</b>
72
+			<div id="usrs"></div>
73
+			<br><br>
74
+			<b>Autres Fameux</b>
75
+			<div id="usrs_others"></div>
76
+		</div>
76 77
 	    </div>
77 78
 
78 79
 	    <form name="message" action=".">
@@ -117,13 +118,75 @@ if (!isset($_SESSION['name'])) {
117 118
 		return 'hsl('+thisdivcolor+',80%, 50%)';
118 119
 	}
119 120
 	
121
+	//https://www.w3resource.com/javascript-exercises/javascript-date-exercise-46.php
122
+	function get_diff_days(dt2, dt1)
123
+	{
124
+		var diff =(dt2.getTime() - dt1.getTime()) / 1000;
125
+		diff /= (60 * 60 * 24);
126
+		return Math.abs(Math.round(diff));
127
+	}
128
+
129
+	function pad00(n){
130
+		return n > 9 ? "" + n: "0" + n;
131
+	}
132
+
133
+	function unix_time_to_locale_string(t)
134
+	{
135
+		var now = new Date();
136
+		var evt_date = new Date(t * 1000);
137
+
138
+		var date_string = '';
139
+
140
+		var diff_days = get_diff_days(now, evt_date);
141
+
142
+		if(diff_days == 0)
143
+		{
144
+
145
+		}
146
+		else if (diff_days == 1)
147
+		{
148
+			date_string = 'Hier ';
149
+		}
150
+		else if (diff_days == 2)
151
+		{
152
+			date_string = 'Avant-hier ';
153
+		}
154
+		else
155
+		{
156
+			date_string = evt_date.toLocaleDateString() + ' ';
157
+		}
158
+
159
+		date_string += pad00(evt_date.getHours()) + ':' + pad00(evt_date.getMinutes());
160
+
161
+		return date_string;
162
+	}
120 163
 	
164
+	/*
165
+	 * echapper un texte html
166
+	 *
167
+	 * un debat houleux
168
+	 * @see http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery
169
+	 *
170
+	 */
171
+	function escapeHtml(html_text)
172
+	{
173
+		return $('<div/>').text(html_text).html();
174
+	}
121 175
 	
122 176
 	// jQuery Document
123 177
 	$(document).ready(function() {
124
-		var id = 'undefined';
125
-		var oldId = null;
126
-		var isRunLoadLog = false;
178
+		
179
+		
180
+		var saloon_id = '<?php echo str_replace("'","''", $_SESSION['saloon']); ?>';
181
+		if(!saloon_id) saloon_id = 'default';
182
+		
183
+		$('#current_saloon').text(saloon_id);
184
+		
185
+		var login = '<?php echo str_replace("'","''", $_SESSION['name']); ?>';
186
+		
187
+		var session_id = '<?php echo session_id(); ?>';
188
+		
189
+		var last_message = 0;
127 190
 		var audio = new Audio('./front-desk-bell.mp3');
128 191
 		audio.volume = 0.05;
129 192
 		//If user submits the form
@@ -134,13 +197,11 @@ if (!isset($_SESSION['name'])) {
134 197
 			$.ajax({
135 198
 			type: 'POST',
136 199
 				url: 'post.php',
137
-				data: {text: clientmsg},
200
+				data: {msg:{msg:clientmsg, login: login, session_id: session_id}, saloon: saloon_id },
138 201
 				//cache: false,
139 202
 				async: true,
140 203
 				success: function(data) {
141
-					if (!isRunLoadLog) {
142
-						loadLog();
143
-					}
204
+					loadLog();
144 205
 				},
145 206
 				error: function(request, status, error) {
146 207
 					$("#usermsg").val(clientmsg);
@@ -153,66 +214,104 @@ if (!isset($_SESSION['name'])) {
153 214
 			$.ajax({
154 215
 			type: 'POST',
155 216
 				url: 'users.php',
156
-				data: {},
217
+				data: {saloon: saloon_id},
157 218
 				dataType: 'json',
158 219
 				//cache: false,
159 220
 				async: true,
160 221
 				success: function(data) {
161 222
 					var html = '';
162
-					for (var usr in data.data) {
163
-						html = html+"<div class='msgln' style='color:" + color_from_login(data.data[usr]) + "'><em>"+data.data[usr]+"</em></div>";
164
-						$("#usrs").html(html);
223
+					var html_others = '';
224
+					$("#usrs").html('');
225
+					$("#usrs_others").html('');
226
+					for (var usr in data) {
227
+						if(data[usr].saloon == saloon_id)
228
+						{
229
+							$("#usrs").append("<div class='msgln' style='color:" + color_from_login(data[usr].login) + "'><em>"+data[usr].login+"</em></div>");
230
+						}
231
+						else
232
+						{
233
+							var link = $("<a><div class='msgln' style='color:" + color_from_login(data[usr].login) + "'><em>"+data[usr].login + " (" + data[usr].saloon + ")</em></div></a>");
234
+							var saloon = data[usr].saloon;
235
+							link.click(function(){change_saloon(saloon);});
236
+							$("#usrs_others").append(link);
237
+						}
165 238
 					}
166 239
 				},
167 240
 			});
168 241
 		}
242
+		
243
+		function update_session() {
244
+			$.ajax({
245
+			type: 'POST',
246
+				url: 'update_session.php',
247
+				data: {saloon: saloon_id, session:{login: login, session_id: session_id, saloon: saloon_id}},
248
+				dataType: 'json',
249
+				//cache: false,
250
+				async: true,
251
+				success: function(data) {
252
+				},
253
+			});
254
+		}
169 255
 
170 256
 		//Load the file containing the chat log
171 257
 		function loadLog() {
172
-			isRunLoadLog = true;
173 258
 			var oldscrollHeight = $("#chatbox")[0].scrollHeight;
174 259
 			$.ajax({
175 260
 			type: 'POST',
176 261
 				url: 'server.php',
177
-				data: {id: id},
262
+				data: {from: last_message, saloon: saloon_id},
178 263
 				dataType: 'json',
179 264
 				//cache: false,
180 265
 				async: true,
181 266
 				success: function(data) {
182
-					id = data.id;
267
+					last_message = data.last_message;
183 268
 					$(window).focus(function() {
184 269
 						document.title = "Chat FAME";
185 270
 					});
186
-					if (oldId !== id) {
187
-						oldId = id;
188
-						var html = '';
189
-						var date;
190
-						for (var k in data.data.reverse()) {
191
-							date = new Date(parseInt(data.data[k][0])*1000);
192
-							date = date.toLocaleTimeString('en-GB');
193
-							date = date.replace(/([\d]+\D+[\d]{2})\D+[\d]{2}(.*)/, '$1$2');
194
-							html = html
195
-								+"<div class='msgln'>("+date+") <span style='color:" + color_from_login(data.data[k][1]) + "'><b>"
196
-								+data.data[k][1]+"</b></span>: "+linkify(data.data[k][2])+"<br></div>";
197
-						}
198
-						$("#chatbox").append(html); //Insert chat messages into the #chatbox div
199
-						var newscrollHeight = $("#chatbox")[0].scrollHeight;
200
-						if (newscrollHeight > oldscrollHeight) {
201
-							$("#chatbox").scrollTop($("#chatbox")[0].scrollHeight);
202
-						}    
203
-						document.title = "(1) Chat FAME";
204
-						if (!$("#mute").prop('checked')) {
205
-							if (!document.hasFocus()) audio.play();
206
-						}
271
+
272
+					var html = '';
273
+					var date;
274
+					var msg;
275
+					var login;
276
+					for (var k in data.msgs) {
277
+						msg = linkify(escapeHtml(data.msgs[k].msg));
278
+						date = unix_time_to_locale_string(data.msgs[k].time);
279
+						login = data.msgs[k].login
280
+						html = html
281
+							+"<div class='msgln'>("+date+") <span style='color:" + color_from_login(login) + "'><b>"
282
+							+login+"</b></span>: "+msg+"<br></div>";
283
+					}
284
+					$("#chatbox").append(html); //Insert chat messages into the #chatbox div
285
+					var newscrollHeight = $("#chatbox")[0].scrollHeight;
286
+					if (newscrollHeight > oldscrollHeight) {
287
+						$("#chatbox").scrollTop($("#chatbox")[0].scrollHeight);
288
+					}    
289
+					document.title = "(1) Chat FAME";
290
+					if (!$("#mute").prop('checked')) {
291
+						if (!document.hasFocus()) audio.play();
207 292
 					}
208
-					isRunLoadLog = false;
209 293
 				},
210 294
 			});
211 295
 		}
296
+		
297
+		function change_saloon(new_saloon)
298
+		{
299
+			saloon_id = new_saloon;
300
+			$('#current_saloon').text(saloon_id);
301
+			last_message = 0;
302
+			$("#chatbox").html('');
303
+			update_session();
304
+			loadLog();
305
+			beacon();
306
+		}
307
+		
308
+		update_session();
212 309
 		loadLog();
213 310
 		beacon();
214 311
 		setInterval(loadLog, <?php echo getSetup('interval') ?>);	//Reload file every 2.5 seconds
215 312
 		setInterval(beacon, <?php echo getSetup('interval') ?>);	//Reload file every 2.5 seconds
313
+		
314
+		setInterval(update_session, 1000*<?php echo getSetup('update_session_interval_seconds') ?>);
216 315
 
217 316
 		//If user wants to end session
218 317
 		$("#exit").click(function() {

+ 7 - 69
post.php

@@ -1,81 +1,19 @@
1 1
 <?php
2 2
 
3
-function getSetup($key = null) {
4
-    $arr = parse_ini_file('setup.ini');
5
-    return isset($key) ? $arr[$key] : $arr;
6
-}
7 3
 
4
+include 'functions.php';
8 5
 
9 6
 
10
-//$_POST['text'] = 'abc';
11 7
 session_start();
12
-if (!isset($_SESSION['name'])) return;
13
-$text = isset($_POST['text']) ? $_POST['text'] : '';
14
-if ($text === '') return;
15 8
 
16
-$isApc = extension_loaded('apc');
9
+$saloon = get_post_var("saloon");
17 10
 
18
-$setup = getSetup();
19
-$time = time();
20
-$date = date('Y-m-d', $time);
21
-$uniqid = uniqid();
22
-$id = $time.'-'.$uniqid;
23 11
 
24
-$tmpDir = './tmp/';
25
-$historyDir = './history/';
12
+$msg = get_post_var("msg");
26 13
 
27
-$tmpFile = $tmpDir.'cache';
28
-$historyFile = $historyDir.$date;
14
+//  Store UNIX timestamp
15
+$msg['time'] = time();
29 16
 
30
-$fh = @fopen($historyFile, 'a');
31
-if ($fh === false) {
32
-    mkdir($historyDir);
33
-    if (!is_dir($tmpDir)) mkdir($tmpDir);
34
-    $fh = @fopen($historyFile, 'a');
35
-}
17
+file_lock_and_append_msg(get_msg_file_path($saloon), $msg);
36 18
 
37
-/* start semafore */
38
-flock($fh, LOCK_EX);
39
-
40
-// data
41
-$data = array($id, $_SESSION['name'], stripslashes(htmlspecialchars($text)));
42
-
43
-// write history
44
-fwrite($fh, implode('&', $data)."\n");
45
-
46
-// cache
47
-if ($isApc) {
48
-    $cache = apc_fetch('chat');
49
-    if ($cache === false) {
50
-        $cache = array();
51
-    }
52
-} else {
53
-    $cache = @file_get_contents($tmpFile);
54
-    if ($cache === false) {
55
-        $cache = array();
56
-    } else {
57
-        $cache = unserialize($cache);
58
-    }    
59
-}
60
-
61
-array_unshift($cache, $data);
62
-
63
-// delete expired cache
64
-$expireTime = floor($time - $setup['interval']/1000 - $setup['expire_cache']);
65
-foreach (array_reverse($cache,true) as $k => $e) {
66
-    if ($e[0] < $expireTime) {
67
-        unset($cache[$k]);
68
-    } else {
69
-        break;
70
-    }
71
-}
72
-
73
-if ($isApc) {
74
-    apc_store('chat', $cache);
75
-} else {
76
-    file_put_contents($tmpFile, serialize($cache));
77
-}
78
-
79
-/* end semafore */
80
-flock($fh, LOCK_UN);
81
-fclose($fh);
19
+?>

+ 26 - 46
server.php

@@ -1,51 +1,31 @@
1 1
 <?php
2 2
 
3
+include 'functions.php';
3 4
 
4
-// set the default timezone to use. Available since PHP 5.1
5
-date_default_timezone_set('UTC');
6
-
7
-//$_POST['id'] = '1305177620-53c14f147c456';
8
-if (!isset($_POST['id'])) return;
9
-$isApc = extension_loaded('apc');
10
-$id = $_POST['id'];
11
-$cache = $isApc ? apc_fetch('chat') : @unserialize(file_get_contents('./tmp/cache'));
12
-$data = array();
13
-if ($id === 'undefined') {
14
-    $id = empty($cache) ? 0 : $cache[0][0];
15
-} elseif ($id === '0') {
16
-    if (!empty($cache)) {
17
-        $id = $cache[0][0];
18
-        $data = $cache;
19
-    }
20
-} else {
21
-    $end = end($cache);
22
-    // read data from cache
23
-    if ($id >= $end[0]) {
24
-        foreach ($cache as $k => $c) {
25
-            if ($c[0] === $id) break;
26
-        }
27
-        $data = array_slice($cache, 0, $k);
28
-    }
29
-    // read data from history (any problem witch Internet and are delays)
30
-    else {
31
-        $date = date('Y-m-d');
32
-        $history = array();
33
-        while (($history = array_merge(file('./history/'.$date, FILE_IGNORE_NEW_LINES), $history)) && $history[0] > $id) {
34
-            $date = date('Y-m-d', strtotime('-1 day', strtotime($date)));
35
-            if (!file_exists('./history/'.$date)) break;
36
-        }
37
-        // prepare history
38
-        $history = array_reverse($history);
39
-        foreach ($history as & $ref) {
40
-            $ref = explode('&', $ref);
41
-        }
42
-        // get data
43
-        foreach ($history as $k => $h) {
44
-            if ($h[0] === $id) break;
45
-        }
46
-        $data = array_slice($history, 0, $k);
47
-    }
48
-    $id = $cache[0][0];
5
+session_start();
6
+
7
+$saloon = get_post_var("saloon");
8
+
9
+$json_msgs = file_lock_and_get_json(get_msg_file_path($saloon));
10
+
11
+$from = get_post_var("from");
12
+
13
+$count_msgs = count($json_msgs['msgs']);
14
+
15
+if($from == $count_msgs)
16
+{
17
+	// no new message
18
+	return;
49 19
 }
50 20
 
51
-echo json_encode(array('id' => $id, 'data' => $data));
21
+$msg_to_send['last_message'] = $count_msgs;
22
+
23
+for($i = $from ; $i < $count_msgs ; ++$i)
24
+{
25
+	$msg_to_send['msgs'][] = $json_msgs['msgs'][$i];
26
+}
27
+
28
+echo json_encode($msg_to_send);
29
+
30
+
31
+?>

+ 13 - 0
setup.ini

@@ -2,8 +2,21 @@
2 2
 ; how often get data from serwer
3 3
 interval = 2500 ; in milliseconds
4 4
 
5
+; how often update session
6
+update_session_interval_seconds = 15
7
+
8
+
5 9
 ; extra time for cache when is problem with Internet
6 10
 expire_cache = 60 ; in seconds
7 11
 
8 12
 ; time for history
9 13
 expire_history = 30 ; in days
14
+
15
+; time before appearing idle
16
+warning_idle_session_seconds = 20
17
+
18
+; time before removing idle session
19
+max_idle_session_seconds = 300
20
+
21
+; pretty json for debugging storage
22
+pretty_json = true

+ 0 - 1
tmp/users/flo

@@ -1 +0,0 @@
1
-connected

+ 17 - 0
update_session.php

@@ -0,0 +1,17 @@
1
+<?php
2
+include 'functions.php';
3
+
4
+session_start();
5
+
6
+$saloon = get_post_var("saloon");
7
+$_SESSION['saloon'] = $saloon;
8
+
9
+$session = get_post_var("session");
10
+
11
+//  Retourne le timestamp UNIX actuel
12
+$session['last_update'] = time();
13
+
14
+file_lock_and_update_session(get_session_file_path($saloon), $session);
15
+
16
+
17
+?>

+ 6 - 41
users.php

@@ -1,50 +1,15 @@
1 1
 <?php
2
-
3
-// set the default timezone to use. Available since PHP 5.1
4
-date_default_timezone_set('UTC');
5
-
6
-function getSetup($key = null) {
7
-    $arr = parse_ini_file('setup.ini');
8
-    return isset($key) ? $arr[$key] : $arr;
9
-}
2
+include 'functions.php';
10 3
 
11 4
 session_start();
12
-if (!isset($_SESSION['name'])) return;
13
-
14
-$isApc = extension_loaded('apc');
15
-
16
-$setup = getSetup();
17
-$time = time();
18
-$date = date('Y-m-d', $time);
19
-$uniqid = uniqid();
20
-$id = $time.'-'.$uniqid;
21
-$name = $_SESSION['name'];
22
-$escaped = preg_replace('/[^A-Za-z0-9_\-]/', '_', $name);
23
-
24
-$tmpDir = './tmp/';
25
-$historyDir = './history/';
26 5
 
27
-$tmpFile = $tmpDir.'cache';
28
-$tmpUsers = $tmpDir.'users/';
29
-$historyFile = $historyDir.$date;
6
+$saloon = get_post_var("saloon");
30 7
 
31
-$fh = fopen($tmpUsers.$escaped, 'w') or die("Can't create file");
32
-fwrite($fh, "connected");
33
-fclose($fh);
34 8
 
35
-$res = array();
9
+$json_sessions = file_lock_and_get_json(get_session_file_path($saloon));
36 10
 
37
-$users = array_diff(scandir($tmpUsers), array('.', '..'));
11
+$json_sessions = update_sessions_status($json_sessions);
38 12
 
39
-foreach ( $users as $user )
40
-{
41
-	if (time()-filemtime($tmpUsers.$user) > 10) {
42
-		// file/user older than 10 sec
43
-		unlink($tmpUsers.$user);
44
-	} else {
45
-		// file younger than 2 hours
46
-		array_push($res, $user);
47
-	}
48
-}
13
+echo json_encode($json_sessions);
49 14
 
50
-echo json_encode(array('data' => $res));
15
+?>