1 | #!/usr/bin/env node
|
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 | var multiparty = require('multiparty');
|
27 | var http = require('http');
|
28 | var https = require('https');
|
29 | var util = require('util');
|
30 | var path = require("path");
|
31 | require("date-format-lite");
|
32 | var mv = require('mv');
|
33 | var fs = require('fs');
|
34 | var exec = require('child_process').exec;
|
35 | var fsExtra = require('fs-extra');
|
36 | var request = require("request");
|
37 | var needle = require('needle');
|
38 | var readChunk = require('read-chunk');
|
39 | var async = require('async');
|
40 | var mysql = require('mysql');
|
41 | var os = require('os');
|
42 | const querystring = require('querystring');
|
43 | var crypto = require('crypto');
|
44 | var get_ip = require('ipware')().get_ip;
|
45 |
|
46 |
|
47 | var httpsFlag = false;
|
48 | var serverOptions = {};
|
49 | var listenPort = 3277;
|
50 | var msg = {};
|
51 | var lang;
|
52 | var timeUnits;
|
53 | var agoDefault;
|
54 | var verbose = false;
|
55 | var currentDbServer = [];
|
56 | currentDbServer[0] = 0;
|
57 | var usage = "Usage: node loop-server-fast.js config/path/config.json config/path/messages.json [-production]\n\nOr:\n\nnpm config set loop-server-fast:configFile /path/to/your/loop/server/config.json\nnpm config set loop-server-fast:messagesFile /path/to/your/loop/server/messages.json\n[npm config set loop-server-fast:production true]\nnpm run start\n\n";
|
58 | var defaultPHPScript = "search-chat.php?";
|
59 | var defaultPHPScriptLen = defaultPHPScript.length;
|
60 |
|
61 |
|
62 | process.on('SIGINT', function() {
|
63 |
|
64 | console.log("Requesting a shutdown.");
|
65 | closeAllConnections();
|
66 | setTimeout(function() {
|
67 |
|
68 | console.log("Clean exit.");
|
69 | process.exit(0);
|
70 | }, 300);
|
71 | });
|
72 |
|
73 |
|
74 |
|
75 | if((process.argv)&&(process.argv[2])){
|
76 | var loopServerConfig = process.argv[2];
|
77 | } else {
|
78 | if(process.env.npm_package_config_configFile) {
|
79 | var loopServerConfig = process.env.npm_package_config_configFile;
|
80 | } else {
|
81 |
|
82 | console.log(usage);
|
83 | process.exit(0);
|
84 | }
|
85 | }
|
86 |
|
87 |
|
88 |
|
89 |
|
90 | var config = JSON.parse(fs.readFileSync(loopServerConfig));
|
91 | if(!config) {
|
92 | console.log("Couldn't find config file " + loopServerConfig);
|
93 | process.exit(0);
|
94 | }
|
95 |
|
96 |
|
97 | if(((process.argv)&&(process.argv[3]))||(process.env.npm_package_config_messagesFile)){
|
98 |
|
99 | if(process.argv[3]) {
|
100 | var loopServerMessages = process.argv[3];
|
101 | } else {
|
102 |
|
103 | var loopServerMessages = process.env.npm_package_config_messagesFile;
|
104 | }
|
105 | msg = JSON.parse(fs.readFileSync(loopServerMessages));
|
106 | if(!msg) {
|
107 | console.log("Couldn't find messages file " + loopServerMessages);
|
108 | process.exit(0);
|
109 | }
|
110 | lang = msg.defaultLanguage;
|
111 |
|
112 |
|
113 | var time = msg.msgs[lang].time;
|
114 | timeUnits = [
|
115 | { name: time.second, plural: time.seconds, limit: 60, in_seconds: 1 },
|
116 | { name: time.minute, plural: time.minutes, limit: 3600, in_seconds: 60 },
|
117 | { name: time.hour, plural: time.hours, limit: 86400, in_seconds: 3600 },
|
118 | { name: time.day, plural: time.days, limit: 604800, in_seconds: 86400 },
|
119 | { name: time.week, plural: time.weeks, limit: 2629743, in_seconds: 604800 },
|
120 | { name: time.month, plural: time.months, limit: 31556926, in_seconds: 2629743 },
|
121 | { name: time.year, plural: time.years, limit: null, in_seconds: 31556926 }
|
122 | ];
|
123 |
|
124 | agoDefault = time.ago;
|
125 |
|
126 |
|
127 | } else {
|
128 | console.log(usage);
|
129 | process.exit(0);
|
130 | }
|
131 |
|
132 |
|
133 | if((process.argv[4]) && (process.argv[4] == '-production')){
|
134 | var cnf = config.production;
|
135 | } else {
|
136 | if(process.env.npm_package_config_production) {
|
137 | if(process.env.npm_package_config_production == 'true') {
|
138 | var cnf = config.production;
|
139 | } else {
|
140 | var cnf = config.staging;
|
141 | }
|
142 |
|
143 | } else {
|
144 | var cnf = config.staging;
|
145 | }
|
146 | }
|
147 |
|
148 |
|
149 | if(process.env.npm_package_config_verbose) {
|
150 | if(process.env.npm_package_config_verbose == 'true') {
|
151 | verbose = true;
|
152 | } else {
|
153 | verbose = false;
|
154 | }
|
155 |
|
156 | }
|
157 |
|
158 |
|
159 | if(cnf.readPort) {
|
160 | listenPort = cnf.readPort;
|
161 | }
|
162 |
|
163 |
|
164 | if(cnf.httpsKey) {
|
165 |
|
166 | httpsFlag = true;
|
167 | if(!serverOptions.key) {
|
168 | serverOptions.key = fs.readFileSync(cnf.httpsKey);
|
169 | console.log("https key loaded");
|
170 | }
|
171 | }
|
172 |
|
173 | if(cnf.httpsCert) {
|
174 |
|
175 | httpsFlag = true;
|
176 | if(!serverOptions.cert) {
|
177 | serverOptions.cert = fs.readFileSync(cnf.httpsCert);
|
178 | console.log("https cert loaded");
|
179 | }
|
180 |
|
181 | }
|
182 |
|
183 | var connections = [];
|
184 |
|
185 | var closing = false;
|
186 | function closeAllConnections() {
|
187 | if(closing == false) {
|
188 | for(var ccnt = 0; ccnt< cnf.db.hosts.length; ccnt++) {
|
189 | if(connections[0][ccnt]) {
|
190 | connections[0][ccnt].end();
|
191 | }
|
192 | }
|
193 |
|
194 | if(cnf.db.scaleUp) {
|
195 | for(var scaleCnt = 0; scaleCnt< cnf.db.scaleUp.length; scaleCnt++) {
|
196 | for(var ccnt = 0; ccnt< cnf.db.scaleUp[scaleCnt].hosts.length; ccnt++) {
|
197 | if(connections[scaleCnt+1][ccnt]) {
|
198 | connections[scaleCnt+1][ccnt].end();
|
199 | }
|
200 | }
|
201 |
|
202 | }
|
203 | }
|
204 | }
|
205 |
|
206 | }
|
207 |
|
208 |
|
209 | function handleDisconnect() {
|
210 |
|
211 |
|
212 | |
213 |
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 |
|
228 |
|
229 |
|
230 | console.log("Connecting to the database.");
|
231 | connections[0] = {};
|
232 | for(var cnt = 0; cnt< cnf.db.hosts.length; cnt++) {
|
233 |
|
234 | if(cnf.db.ssl && cnf.db.ssl.use === true) {
|
235 | var ssl = {
|
236 | ca : fs.readFileSync(cnf.db.ssl.capath)
|
237 | };
|
238 | } else {
|
239 | var ssl = null;
|
240 | }
|
241 |
|
242 | connections[0][cnt] = mysql.createConnection({
|
243 | host : cnf.db.hosts[cnt],
|
244 | user : cnf.db.user,
|
245 | password : cnf.db.pass,
|
246 | database : cnf.db.name,
|
247 | port : cnf.db.port,
|
248 | ssl : ssl
|
249 | });
|
250 |
|
251 |
|
252 | connections[0][cnt].connect(function(err) {
|
253 | if(err) {
|
254 |
|
255 | console.log('error when connecting to db:', err);
|
256 | closeAllConnections();
|
257 |
|
258 | if(closing == false) {
|
259 | closing = true;
|
260 | setTimeout(handleDisconnect, 2000);
|
261 | }
|
262 |
|
263 | }
|
264 | });
|
265 |
|
266 | connections[0][cnt].on('error', function(err) {
|
267 | console.log('db error: ', err);
|
268 |
|
269 | closeAllConnections();
|
270 |
|
271 |
|
272 | if(err.code === 'PROTOCOL_CONNECTION_LOST') {
|
273 |
|
274 |
|
275 |
|
276 | if(closing == false) {
|
277 | closing = true;
|
278 | setTimeout(handleDisconnect, 2000);
|
279 | }
|
280 | } else {
|
281 |
|
282 |
|
283 | if(closing == false) {
|
284 | closing = true;
|
285 | setTimeout(handleDisconnect, 2000);
|
286 | }
|
287 |
|
288 | }
|
289 | });
|
290 |
|
291 |
|
292 | }
|
293 |
|
294 | if(cnf.db.scaleUp) {
|
295 |
|
296 | for(var scaleCnt = 0; scaleCnt< cnf.db.scaleUp.length; scaleCnt++) {
|
297 |
|
298 | connections[scaleCnt+1] = [];
|
299 | currentDbServer[scaleCnt+1] = 0;
|
300 | dbCnf = cnf.db.scaleUp[scaleCnt];
|
301 |
|
302 | if(dbCnf.ssl && dbCnf.ssl.use === true) {
|
303 | var ssl = {
|
304 | ca : fs.readFileSync(dbCnf.ssl.capath)
|
305 | };
|
306 | } else {
|
307 | var ssl = null;
|
308 | }
|
309 |
|
310 |
|
311 | for(var cnt = 0; cnt< dbCnf.hosts.length; cnt++) {
|
312 |
|
313 | connections[scaleCnt+1][cnt] = mysql.createConnection({
|
314 | host : dbCnf.hosts[cnt],
|
315 | user : dbCnf.user,
|
316 | password : dbCnf.pass,
|
317 | database : dbCnf.name,
|
318 | port : dbCnf.port,
|
319 | ssl : ssl
|
320 | });
|
321 |
|
322 |
|
323 | connections[scaleCnt+1][cnt].connect(function(err) {
|
324 | if(err) {
|
325 | console.log('error when connecting to db:', err);
|
326 | closeAllConnections();
|
327 |
|
328 | if(closing == false) {
|
329 | closing = true;
|
330 | setTimeout(handleDisconnect, 2000);
|
331 | }
|
332 | }
|
333 | });
|
334 |
|
335 | connections[scaleCnt+1][cnt].on('error', function(err) {
|
336 | console.log('db error: ', err);
|
337 |
|
338 | closeAllConnections();
|
339 |
|
340 |
|
341 | if(err.code === 'PROTOCOL_CONNECTION_LOST') {
|
342 |
|
343 |
|
344 |
|
345 | if(closing == false) {
|
346 | closing = true;
|
347 | setTimeout(handleDisconnect, 2000);
|
348 | }
|
349 | } else {
|
350 |
|
351 |
|
352 | if(closing == false) {
|
353 | closing = true;
|
354 | setTimeout(handleDisconnect, 2000);
|
355 | }
|
356 | }
|
357 |
|
358 |
|
359 | });
|
360 |
|
361 |
|
362 | }
|
363 | }
|
364 |
|
365 | }
|
366 |
|
367 | if(closing == true) {
|
368 |
|
369 | console.log("Finished connecting to the database.");
|
370 | closing = false;
|
371 | }
|
372 |
|
373 |
|
374 | }
|
375 |
|
376 | handleDisconnect();
|
377 |
|
378 | function escapeRegExp(str) {
|
379 | return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
|
380 | }
|
381 |
|
382 |
|
383 | function cleanData(str)
|
384 | {
|
385 |
|
386 | return escapeRegExp(str);
|
387 | }
|
388 |
|
389 |
|
390 | function trimChar(string, charToRemove) {
|
391 | if(string) {
|
392 | while(string.substring(0,1) == charToRemove) {
|
393 | string = string.substring(1);
|
394 | }
|
395 |
|
396 | while(string.slice(-1) == charToRemove) {
|
397 | string = string.slice(0, -1);
|
398 | }
|
399 |
|
400 | return string;
|
401 | } else {
|
402 | return null;
|
403 | }
|
404 | }
|
405 |
|
406 |
|
407 |
|
408 |
|
409 | function readSession(params, cb)
|
410 | {
|
411 |
|
412 | |
413 |
|
414 |
|
415 |
|
416 |
|
417 | var keyValues = {};
|
418 |
|
419 | if(verbose == true) console.log("SessionID" + cleanData(params.sessionId));
|
420 |
|
421 | if(!params.connection) {
|
422 |
|
423 | cb(null);
|
424 | return;
|
425 |
|
426 | }
|
427 |
|
428 | params.connection.query("SELECT * FROM php_session WHERE session_id='" + cleanData(params.sessionId) + "'", function(err, rows, fields) {
|
429 |
|
430 | if (err) {
|
431 | console.log("Database error:" + err);
|
432 | cb(null);
|
433 | } else {
|
434 |
|
435 |
|
436 | if((rows[0])&&(rows[0].session_data)) {
|
437 |
|
438 | if(verbose == true) console.log("Session data:" + rows[0].session_data);
|
439 | var params = rows[0].session_data.split(";");
|
440 | for(var cnt=0; cnt< params.length; cnt++) {
|
441 |
|
442 | var paramData = params[cnt].split("|");
|
443 | if(paramData[1]) {
|
444 |
|
445 | var paramValues = paramData[1].split(":");
|
446 | if(paramValues[0] == 'i') {
|
447 |
|
448 | var paramValue = paramValues[1];
|
449 | } else {
|
450 |
|
451 | var paramValue = trimChar(paramValues[2], '"');
|
452 | }
|
453 |
|
454 | keyValues[paramData[0]] = paramValue;
|
455 | if(verbose == true) console.log("Key:" + paramData[0] + " = " + paramValue);
|
456 | }
|
457 | }
|
458 | }
|
459 |
|
460 | cb(keyValues);
|
461 | }
|
462 | });
|
463 |
|
464 | }
|
465 |
|
466 |
|
467 |
|
468 | function httpHttpsCreateServer(options) {
|
469 | if(httpsFlag == true) {
|
470 | console.log("Starting https server.");
|
471 | https.createServer(options, handleServer).listen(listenPort);
|
472 |
|
473 |
|
474 | } else {
|
475 | console.log("Starting http server.");
|
476 | http.createServer(handleServer).listen(listenPort);
|
477 | }
|
478 |
|
479 |
|
480 |
|
481 | }
|
482 |
|
483 |
|
484 | function determineSubdomain(req) {
|
485 |
|
486 | if(req) {
|
487 |
|
488 | if(verbose == true) console.log("Requesting: " + req.headers.host);
|
489 |
|
490 |
|
491 |
|
492 |
|
493 | var myReadURL = cnf.readURL.replace("https://", "");
|
494 | myReadURL = myReadURL.replace("http://","");
|
495 |
|
496 |
|
497 |
|
498 |
|
499 | var noSubReadURL = myReadURL.replace("[subdomain]","");
|
500 |
|
501 | var subdomain = req.headers.host.replace(noSubReadURL,"");
|
502 |
|
503 | if(verbose == true) console.log("Subdomain: " + subdomain);
|
504 |
|
505 |
|
506 | return subdomain;
|
507 | } else {
|
508 | return "";
|
509 | }
|
510 |
|
511 | }
|
512 |
|
513 |
|
514 |
|
515 |
|
516 | function handleServer(_req, _res) {
|
517 |
|
518 | var req = _req;
|
519 | var res = _res;
|
520 | var body = [];
|
521 |
|
522 | var subdomain = determineSubdomain(req);
|
523 |
|
524 |
|
525 | req.on('error', function(err) {
|
526 |
|
527 | console.error(err.stack);
|
528 |
|
529 | res.statusCode = 400;
|
530 | res.end();
|
531 | });
|
532 |
|
533 | req.on('data', function(chunk) {
|
534 | body.push(chunk);
|
535 | });
|
536 |
|
537 | req.on('end', function() {
|
538 |
|
539 |
|
540 |
|
541 |
|
542 |
|
543 |
|
544 |
|
545 | if(verbose == true) console.log("Requesting: " + req.url);
|
546 |
|
547 |
|
548 | if(req.url.indexOf(defaultPHPScript) < 0) {
|
549 | res.writeHead(200, {'content-type': 'text/html'});
|
550 | res.end("Not available");
|
551 | return;
|
552 | }
|
553 |
|
554 | var url = req.url.substring(req.url.indexOf(defaultPHPScript) + defaultPHPScriptLen);
|
555 |
|
556 |
|
557 | if(verbose == true) console.log("Parsed to query string:" + url);
|
558 | var params = querystring.parse(url);
|
559 | if(verbose == true) console.log("Query params = " + JSON.stringify(params));
|
560 |
|
561 | var cookies = parseCookies(req);
|
562 | if(!params.sessionId) {
|
563 | params.sessionId = cookies.PHPSESSID;
|
564 | }
|
565 | if(!params.sessionId) {
|
566 | res.statusCode = 400;
|
567 | res.end();
|
568 | console.log("Error: You must include a PHP Session ID");
|
569 | return;
|
570 |
|
571 | }
|
572 |
|
573 | if(params.subdomain) {
|
574 | subdomain = params.subdomain;
|
575 | }
|
576 |
|
577 | var mylang = null;
|
578 | if(cookies.lang) {
|
579 |
|
580 | mylang = cookies.lang;
|
581 | }
|
582 | if(params.lang) {
|
583 |
|
584 | mylang = params.lang;
|
585 | }
|
586 | if(mylang) {
|
587 |
|
588 | var time = msg.msgs[mylang].time;
|
589 | params.timeUnits = [
|
590 | { name: time.second, plural: time.seconds, limit: 60, in_seconds: 1 },
|
591 | { name: time.minute, plural: time.minutes, limit: 3600, in_seconds: 60 },
|
592 | { name: time.hour, plural: time.hours, limit: 86400, in_seconds: 3600 },
|
593 | { name: time.day, plural: time.days, limit: 604800, in_seconds: 86400 },
|
594 | { name: time.week, plural: time.weeks, limit: 2629743, in_seconds: 604800 },
|
595 | { name: time.month, plural: time.months, limit: 31556926, in_seconds: 2629743 },
|
596 | { name: time.year, plural: time.years, limit: null, in_seconds: 31556926 }
|
597 | ];
|
598 |
|
599 | params.ago = time.ago;
|
600 |
|
601 | if(msg.msgs[mylang].numbers) {
|
602 | params.numbersTranslation = msg.msgs[mylang].numbers;
|
603 | }
|
604 |
|
605 | }
|
606 |
|
607 | params.ip = getFakeIpAddress(params.sessionId);
|
608 |
|
609 |
|
610 | params.connection = connections[0][currentDbServer[0]];
|
611 |
|
612 |
|
613 | currentDbServer[0] ++;
|
614 | if(currentDbServer[0] >= cnf.db.hosts.length) currentDbServer[0] = 0;
|
615 |
|
616 |
|
617 | var myres = res;
|
618 |
|
619 | var jsonData = searchProcess(params, function(err, data) {
|
620 | if(err) {
|
621 | if(err == 'PHP') {
|
622 |
|
623 |
|
624 |
|
625 | if(subdomain) {
|
626 | var replaceWith = subdomain + ".";
|
627 | } else {
|
628 | var replaceWith = "";
|
629 | }
|
630 | var webRoot = cnf.webRoot.replace("[subdomain]", replaceWith);
|
631 |
|
632 | var fullUrl = webRoot + '/' + defaultPHPScript + url;
|
633 | if(verbose == true) console.log("Webroot:" + cnf.webRoot + " Default PHP script:" + defaultPHPScript + " Url:" + url + " fullUrl:" + fullUrl);
|
634 | callPHP(fullUrl, myres);
|
635 | return;
|
636 | }
|
637 |
|
638 | console.log(err);
|
639 | res.statusCode = 400;
|
640 | res.end();
|
641 | }
|
642 |
|
643 |
|
644 | var strData = params.callback + "(" + JSON.stringify( data ) + ")";
|
645 |
|
646 | res.on('error', function(err){
|
647 |
|
648 | res.statusCode = 400;
|
649 | res.end();
|
650 | })
|
651 |
|
652 | res.writeHead(200, {'content-type': 'text/html'});
|
653 |
|
654 |
|
655 | res.end(strData, function(err) {
|
656 |
|
657 | if(err) {
|
658 | console.log(err);
|
659 | } else {
|
660 |
|
661 | process.stdout.write(".");
|
662 | }
|
663 | });
|
664 | });
|
665 |
|
666 | });
|
667 |
|
668 | }
|
669 |
|
670 |
|
671 | function parseCookies (request) {
|
672 | var list = {},
|
673 | rc = request.headers.cookie;
|
674 |
|
675 | rc && rc.split(';').forEach(function( cookie ) {
|
676 | var parts = cookie.split('=');
|
677 | list[parts.shift().trim()] = decodeURI(parts.join('='));
|
678 | });
|
679 |
|
680 | return list;
|
681 | }
|
682 |
|
683 |
|
684 | function showTranslatedNumber(number, translationTable) {
|
685 | |
686 |
|
687 |
|
688 |
|
689 |
|
690 |
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 |
|
697 |
|
698 |
|
699 |
|
700 |
|
701 |
|
702 |
|
703 |
|
704 |
|
705 |
|
706 |
|
707 |
|
708 |
|
709 |
|
710 |
|
711 |
|
712 |
|
713 |
|
714 |
|
715 |
|
716 | if(translationTable) {
|
717 | if(Number.isInteger(number)) {
|
718 | if(translationTable[number]) {
|
719 | return translationTable[number];
|
720 | } else {
|
721 | return number;
|
722 | }
|
723 | } else {
|
724 | return number;
|
725 | }
|
726 | } else {
|
727 | return number;
|
728 | }
|
729 | }
|
730 |
|
731 |
|
732 |
|
733 | function ago(timeStr, thisTimeUnits, agoWord, numbersTranslation) {
|
734 |
|
735 |
|
736 |
|
737 |
|
738 | var recTime = new Date(timeStr);
|
739 | var recTimeSecs = recTime.getTime();
|
740 |
|
741 |
|
742 | var nowSecs = new Date().getTime();
|
743 | var diff = (nowSecs - recTimeSecs) / 1000;
|
744 |
|
745 | var i = 0;
|
746 | var unit = {};
|
747 |
|
748 | while (unit = thisTimeUnits[i]) {
|
749 | if ((diff < unit.limit) || (!unit.limit)){
|
750 | var diff = Math.round(diff / unit.in_seconds);
|
751 | diff = showTranslatedNumber(diff, numbersTranslation);
|
752 | var timeOut = diff + " " + (diff>1 ? unit.plural : unit.name) + " " + agoWord;
|
753 | return timeOut;
|
754 | }
|
755 | i++;
|
756 | }
|
757 |
|
758 | return "Unknown";
|
759 |
|
760 |
|
761 |
|
762 | }
|
763 |
|
764 | function md5(data) {
|
765 |
|
766 | return crypto.createHash('md5').update(data).digest("hex");
|
767 | }
|
768 |
|
769 |
|
770 | function getFakeIpAddress(sessionId) {
|
771 |
|
772 |
|
773 |
|
774 |
|
775 |
|
776 | if(sessionId) {
|
777 | var ip = "192." + parseInt(sessionId.charCodeAt(0)) + "." +
|
778 | parseInt(sessionId.charCodeAt(1)) + "." +
|
779 | parseInt(sessionId.charCodeAt(2));
|
780 | return ip;
|
781 | } else {
|
782 |
|
783 | return "192.168.10.10";
|
784 | }
|
785 | }
|
786 |
|
787 | function getRealIpAddress(req) {
|
788 |
|
789 | var ip_info = get_ip(req);
|
790 |
|
791 | return ip_info.clientIp.replace(/^[0-9.,]+$/,"");
|
792 | }
|
793 |
|
794 |
|
795 |
|
796 |
|
797 |
|
798 | function callPHP(url, res) {
|
799 |
|
800 |
|
801 | if(verbose == true) console.log("Redirecting to " + url);
|
802 |
|
803 | res.writeHead(302, {
|
804 | 'Location': url
|
805 |
|
806 | });
|
807 | res.end();
|
808 |
|
809 |
|
810 | }
|
811 |
|
812 |
|
813 |
|
814 | function foundLayer(params,
|
815 | session,
|
816 | layer,
|
817 | ip,
|
818 | userCheck,
|
819 | initialRecords,
|
820 | outputJSON,
|
821 | debug,
|
822 | cb) {
|
823 |
|
824 | if((params.units) && (params.units != '')) {
|
825 | units = params.units;
|
826 | }
|
827 |
|
828 | if((params.dbg) && (params.dbg == 'true')) {
|
829 | debug = true;
|
830 | } else {
|
831 | debug = false;
|
832 | }
|
833 |
|
834 | if(session['logged-user']) {
|
835 | userCheck = " OR int_author_id = " + session['logged-user'] + " OR int_whisper_to_id = " + session['logged-user'];
|
836 |
|
837 | }
|
838 |
|
839 | if(session['logged-group-user']) {
|
840 | userCheck = userCheck + " OR int_author_id = " + session['logged-group-user'] + " OR int_whisper_to_id = " + session['logged-group-user'];
|
841 |
|
842 | }
|
843 |
|
844 | if((params.records) && (params.records < 100)) {
|
845 | initialRecords = 100;
|
846 | } else {
|
847 | if(params.records) {
|
848 | initialRecords = params.records;
|
849 | }
|
850 | }
|
851 |
|
852 |
|
853 |
|
854 |
|
855 |
|
856 |
|
857 |
|
858 |
|
859 | var sql = "SELECT * FROM tbl_ssshout WHERE int_layer_id = " + layer + " AND enm_active = 'true' AND (var_whisper_to = '' OR ISNULL(var_whisper_to) OR var_whisper_to ='" + ip + "' OR var_ip = '" + ip + "' " + userCheck + ") ORDER BY date_when_shouted DESC, int_ssshout_id DESC LIMIT " + initialRecords;
|
860 | if(verbose == true) console.log("Query: " + sql);
|
861 | if(!params.connection) {
|
862 |
|
863 | cb(err, null);
|
864 | return;
|
865 | }
|
866 |
|
867 | params.connection.query(sql, function(err, rows, fields) {
|
868 |
|
869 |
|
870 | if (err) {
|
871 |
|
872 | console.log("Database query error:" + err);
|
873 | cb(err, null);
|
874 | return;
|
875 | }
|
876 |
|
877 |
|
878 | outputJSON.res = [];
|
879 | outputJSON.ses = params.sessionId;
|
880 |
|
881 |
|
882 | var mymaxResults = rows.length;
|
883 | if(mymaxResults > params.records) {
|
884 | mymaxResults = params.records;
|
885 | var more = true;
|
886 | }
|
887 | var actualCnt = 0;
|
888 |
|
889 |
|
890 | if((session['access-layer-granted'])&&(session['access-layer-granted'] !== "true")
|
891 | &&(session['access-layer-granted'] != true)) {
|
892 | if((session['access-layer-granted'] == 'false') || (session['access-layer-granted'] != layer)) {
|
893 |
|
894 |
|
895 | if((session['access-layers-granted'])&&(Array.isArray(session['access-layers-granted']))) {
|
896 |
|
897 | var granted = session['access-layers-granted'];
|
898 | if(granted.includes(layer)) {
|
899 |
|
900 | } else {
|
901 |
|
902 | outputJSON.res = [];
|
903 | cb(null, outputJSON);
|
904 | return;
|
905 | }
|
906 |
|
907 | } else {
|
908 |
|
909 | outputJSON.res = [];
|
910 | cb(null, outputJSON);
|
911 | return;
|
912 | }
|
913 | }
|
914 | }
|
915 |
|
916 |
|
917 | var thisTimeUnits = timeUnits;
|
918 | var thisAgo = agoDefault;
|
919 | if(params.timeUnits) {
|
920 |
|
921 | thisTimeUnits = params.timeUnits;
|
922 | thisAgo = params.ago;
|
923 | }
|
924 | if(params.numbersTranslation) {
|
925 | var numbersTranslation = params.numbersTranslation;
|
926 |
|
927 | } else {
|
928 | numbersTranslation = null;
|
929 | }
|
930 |
|
931 |
|
932 | for(var cnt = 0; cnt< rows.length; cnt++) {
|
933 |
|
934 | var whisper = true;
|
935 | var authorIP = rows[cnt].var_ip;
|
936 | var authorUserID = rows[cnt].int_author_id;
|
937 | var combinedAuthor = authorIP;
|
938 | if(authorUserID) {
|
939 | combinedAuthor = combinedAuthor + ":" + authorUserID;
|
940 | }
|
941 |
|
942 | var whisperToIP = rows[cnt].var_whisper_to;
|
943 | var whisperToUserID = rows[cnt].int_whisper_to_id;
|
944 |
|
945 |
|
946 |
|
947 |
|
948 | if((whisperToIP == '')||
|
949 | ((whisperToIP == ip)&&(whisperToUserID == null))||
|
950 | (whisperToUserID == session['logged-user'])||
|
951 | ((authorIP == ip)&&(authorUserID == null))||
|
952 | (authorUserID == session['logged-user'])||
|
953 | ((session['logged-group-user'] != "")&&(whisperToUserID != "") && (whisperToUserID == session['logged-group-user']))) {
|
954 |
|
955 |
|
956 |
|
957 | if(((whisperToIP == ip) && (whisperToUserID == null))||
|
958 | (whisperToUserID == session['logged-user'])||
|
959 | ((authorIP == ip) && ((whisperToIP != '')||(whisperToUserID)))||
|
960 | (authorUserID == session['logged-user'] && ((whisperToIP != '')|| (whisperToUserID)))) {
|
961 |
|
962 | whisper = true;
|
963 | } else {
|
964 |
|
965 | whisper = false;
|
966 | }
|
967 |
|
968 | if(session['logged-group-user']) {
|
969 | if(whisperToUserID == session['logged-group-user']) {
|
970 | whisper = true;
|
971 |
|
972 | }
|
973 | }
|
974 |
|
975 | if(!session['logged-user']) {
|
976 |
|
977 | whisper = false;
|
978 |
|
979 | }
|
980 |
|
981 |
|
982 |
|
983 | var shade = rows[cnt].int_ssshout_id %2;
|
984 | if(layer == 0) {
|
985 |
|
986 | if(shade == 0) {
|
987 | bgcolor = "public-light";
|
988 | } else {
|
989 | bgcolor = "public-dark";
|
990 | }
|
991 | } else {
|
992 |
|
993 | if(shade == 0) {
|
994 | bgcolor = "private-light";
|
995 | } else {
|
996 | bgcolor = "private-dark";
|
997 | }
|
998 |
|
999 | }
|
1000 |
|
1001 |
|
1002 |
|
1003 |
|
1004 | if(actualCnt <= mymaxResults) {
|
1005 |
|
1006 |
|
1007 |
|
1008 |
|
1009 | var newEntry = {
|
1010 | 'id': rows[cnt].int_ssshout_id,
|
1011 | 'text': rows[cnt].var_shouted_processed,
|
1012 | 'lat': rows[cnt].latitude,
|
1013 | 'lon': rows[cnt].longtiude,
|
1014 | 'dist': rows[cnt].dist,
|
1015 | 'ago': ago(rows[cnt].date_when_shouted, thisTimeUnits, thisAgo, numbersTranslation),
|
1016 | 'whisper': whisper
|
1017 |
|
1018 | }
|
1019 |
|
1020 | outputJSON.res.push(newEntry);
|
1021 |
|
1022 | actualCnt ++;
|
1023 | }
|
1024 |
|
1025 |
|
1026 | }
|
1027 |
|
1028 | }
|
1029 |
|
1030 | cb(null, outputJSON);
|
1031 |
|
1032 |
|
1033 | });
|
1034 |
|
1035 |
|
1036 | }
|
1037 |
|
1038 |
|
1039 | function checkScaleupHorizontally(layerName, params) {
|
1040 |
|
1041 | if(cnf.db.scaleUp) {
|
1042 |
|
1043 | for(var scaleCnt = 0; scaleCnt< cnf.db.scaleUp.length; scaleCnt++) {
|
1044 |
|
1045 | var regExp = new RegExp(cnf.db.scaleUp[scaleCnt].labelRegExp);
|
1046 | if(layerName.search(regExp) >= 0) {
|
1047 |
|
1048 |
|
1049 | params.connection = connections[scaleCnt+1][currentDbServer[scaleCnt+1]];
|
1050 |
|
1051 |
|
1052 | currentDbServer[scaleCnt+1] ++;
|
1053 | if(currentDbServer[scaleCnt+1] >= cnf.db.scaleUp[scaleCnt].hosts.length) currentDbServer[scaleCnt+1] = 0;
|
1054 | return;
|
1055 | }
|
1056 | }
|
1057 | }
|
1058 |
|
1059 | return;
|
1060 | }
|
1061 |
|
1062 |
|
1063 |
|
1064 | function searchProcess(params, cb) {
|
1065 |
|
1066 |
|
1067 | checkScaleupHorizontally(params.passcode, params);
|
1068 |
|
1069 |
|
1070 | readSession(params, function(session) {
|
1071 | if(verbose == true) console.log("Finished getting session data. Logged user:" + session['logged-user']);
|
1072 |
|
1073 |
|
1074 |
|
1075 |
|
1076 | if((session)&&(session['logged-user'])&&(session['logged-user'] != '')) {
|
1077 |
|
1078 | if((!session['user-ip'])||(session['user-ip'] == '')) {
|
1079 |
|
1080 | console.log('No ip. Going to PHP');
|
1081 | cb("PHP", null);
|
1082 | return;
|
1083 | } else {
|
1084 |
|
1085 |
|
1086 |
|
1087 |
|
1088 |
|
1089 | if(session['view-count'] == 0) {
|
1090 | console.log("view-count = " + session['view-count'] + " Going to PHP");
|
1091 | cb("PHP", null);
|
1092 | return;
|
1093 | }
|
1094 |
|
1095 | var layer = 1;
|
1096 | var ip = params.ip;
|
1097 | var userCheck = "";
|
1098 | var initialRecords = 100;
|
1099 | var outputJSON = {};
|
1100 | var debug = false;
|
1101 |
|
1102 |
|
1103 | if((params.passcode) && (params.passcode != '')||((params.reading) && (params.reading != ''))) {
|
1104 |
|
1105 |
|
1106 | var sql = "SELECT int_layer_id FROM tbl_layer WHERE passcode = '" + md5(params.passcode) + "'";
|
1107 |
|
1108 | if(params.connection) {
|
1109 | params.connection.query(sql, function(err, rows, fields) {
|
1110 |
|
1111 | if(err) {
|
1112 | console.log("Database error: " + err);
|
1113 | return;
|
1114 | } else {
|
1115 | if((rows)&&(rows[0])) {
|
1116 | layer = rows[0].int_layer_id;
|
1117 |
|
1118 | foundLayer(params, session, layer, ip, userCheck, initialRecords, outputJSON, debug, cb);
|
1119 | } else {
|
1120 | console.log("No layer " + md5(params.passcode) + " - likely new. Going to PHP");
|
1121 | cb("PHP", null);
|
1122 | return;
|
1123 |
|
1124 |
|
1125 |
|
1126 | }
|
1127 | }
|
1128 | });
|
1129 | }
|
1130 |
|
1131 |
|
1132 |
|
1133 |
|
1134 |
|
1135 |
|
1136 | } else {
|
1137 |
|
1138 | if(session['authenticated-layer']) {
|
1139 | layer = session['authenticated-layer'];
|
1140 | } else {
|
1141 | layer = 1;
|
1142 | }
|
1143 |
|
1144 | foundLayer(params, session, layer, ip, userCheck, initialRecords, outputJSON, debug, cb);
|
1145 | }
|
1146 |
|
1147 |
|
1148 | }
|
1149 |
|
1150 |
|
1151 | } else {
|
1152 |
|
1153 | console.log("Not logged in - back to PHP version");
|
1154 | cb("PHP", null);
|
1155 | return;
|
1156 |
|
1157 | }
|
1158 |
|
1159 |
|
1160 | });
|
1161 |
|
1162 |
|
1163 | }
|
1164 |
|
1165 |
|
1166 |
|
1167 |
|
1168 |
|
1169 |
|
1170 |
|
1171 |
|
1172 | httpHttpsCreateServer(serverOptions);
|
1173 |
|
1174 |
|