Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.78 KB | None | 0 0
  1. CREATE TABLE `timer` (
  2. `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  3. `user_id` INT(10) UNSIGNED NOT NULL,
  4. `action` VARCHAR(5) NOT NULL,
  5. `timestamp` INT(10) UNSIGNED NOT NULL,
  6. PRIMARY KEY(`id`)
  7. );
  8.  
  9. <script src="http://code.jquery.com/jquery.js"></script>
  10. <script>
  11. var format = function(seconds) {
  12. var tempos = {
  13. segundos: 60
  14. , minutos: 60
  15. , horas: 24
  16. , dias: ''
  17. };
  18. var parts = [], string = '', resto, dias;
  19. for (var unid in tempos) {
  20. if (typeof tempos[unid] === 'number') {
  21. resto = seconds % tempos[unid];
  22. seconds = (seconds - resto) / tempos[unid];
  23. } else {
  24. resto = seconds;
  25. }
  26. parts.unshift(resto);
  27. }
  28. dias = parts.shift();
  29. if (dias) {
  30. string = dias + (dias > 1 ? ' dias ' : ' dia ');
  31. }
  32. for (var i = 0; i < 3; i++) {
  33. parts[i] = ('0' + parts[i]).substr(-2);
  34. }
  35. string += parts.join(':');
  36. return string;
  37. };
  38. $(function(){
  39. var tempo = 0;
  40. var interval = 0;
  41. var timer = function(){
  42. $('.timer').html(format(++tempo));
  43. };
  44. $.post('get_timer.php', function(resp){
  45. $('button').text(resp.running ? 'Pausar' : 'Iniciar');
  46. tempo = resp.seconds;
  47. timer();
  48. if (resp.running) {
  49. interval = setInterval(timer, 1000);
  50. }
  51. });
  52. $('button').on('click', function(){
  53. var btn = this;
  54. btn.disabled = true;
  55. $.post('grava_acao.php', function(resp){
  56. btn.disabled = false;
  57. $(btn).text(resp.running ? 'Pausar' : 'Iniciar');
  58. if (resp.running) {
  59. timer();
  60. interval = setInterval(timer, 1000);
  61. } else {
  62. clearInterval(interval);
  63. }
  64. });
  65. });
  66. });
  67. </script>
  68. <div class="timer">0 segundos</div>
  69. <button>Iniciar</button>
  70.  
  71. <?php
  72. // definir no seu código
  73. $pdo = new PDO($dsn, $username, $passwd);
  74. $user_id = 1; // $_SESSION['user_id'];
  75.  
  76. $params = array(':user' => $user_id);
  77. $stt = $pdo->prepare('SELECT `action`, `timestamp` FROM `timer` WHERE `user_id` = :user ORDER BY `id`');
  78. $stt->execute($params);
  79. $tempos = $stt->fetchAll(PDO::FETCH_ASSOC);
  80. $seconds = 0;
  81. $action = 'pause'; // sempre inicia pausado
  82. foreach ($tempos as $tempo) {
  83. $action = $tempo['action'];
  84. switch ($action) {
  85. case 'start':
  86. $seconds -= $tempo['timestamp'];
  87. break;
  88. case 'pause':
  89. // para evitar erro se a primeira ação for pause
  90. if ($seconds !== 0) {
  91. $seconds += $tempo['timestamp'];
  92. }
  93. break;
  94. }
  95. }
  96. if ($action === 'start') {
  97. $seconds += time();
  98. }
  99. header('Content-Type: application/json');
  100. echo json_encode(array(
  101. 'seconds' => $seconds,
  102. 'running' => $action === 'start',
  103. ));
  104.  
  105. <?php
  106. // definir no seu código
  107. $pdo = new PDO($dsn, $username, $passwd);
  108. $user_id = 1; // $_SESSION['user_id'];
  109.  
  110. $params = array(':user' => $user_id);
  111. $stt1 = $pdo->prepare('SELECT `action` FROM `timer` WHERE `user_id` = :user ORDER BY `id` DESC LIMIT 1');
  112. $stt1->execute($params);
  113. $newAction = 'start';
  114. if ($stt1->rowCount() && $stt1->fetchColumn() === 'start') {
  115. $newAction = 'pause';
  116. }
  117. $stt2 = $pdo->prepare('INSERT INTO `timer` (`user_id`, `action`, `timestamp`) VALUES (:user, :action, :time)');
  118. $params[':action'] = $newAction;
  119. $params[':time'] = time();
  120. $stt2->execute($params);
  121. header('Content-Type: application/json');
  122. echo json_encode(array(
  123. 'running' => $newAction === 'start',
  124. )); // para atualizar status, no caso de concorrência
  125.  
  126. <body onload="restore_timer();">
  127. <form name="form">
  128. <input type="text" name="cronometro" value="00:00:00" />
  129. <br />
  130. <button type="button" onclick="timer(this); return false;">Play</button>
  131. </form>
  132. </body>
  133.  
  134. $(document).ready(function() {
  135. var t = form.cronometro.value;
  136. var hora = t.substring(0, 2);
  137. var minuto = t.substring(3, 5);
  138. var segundo = t.substring(6, 8);
  139.  
  140. restore_timer = function() {
  141. send_ajax("get_time");
  142. }
  143.  
  144. var interval;
  145. send_ajax = function(opt) {
  146. $.ajax({
  147. method: "POST",
  148. async: "false",
  149. url: "timer.php",
  150. data: {"opt": opt}
  151. }).done(function(msg) {
  152. if (opt == "get_time") {
  153. if (msg.status == "started") {
  154. $('button').html('Pause');
  155. interval = setInterval('tempo()', 983);
  156. }
  157. form.cronometro.value = msg.time;
  158. t = msg.time;
  159. hora = t.substring(0, 2);
  160. minuto = t.substring(3, 5);
  161. segundo = t.substring(6, 8);
  162. }
  163. });
  164. }
  165.  
  166. timer = function(obj) {
  167. var html = $(obj).html();
  168. if (html == 'Play') {
  169. interval = setInterval('tempo()', 983);
  170. send_ajax("start_timer");
  171. $(obj).html('Pause');
  172. } else {
  173. clearInterval(interval);
  174. send_ajax("save_time");
  175. $(obj).html('Play');
  176. }
  177. }
  178.  
  179. tempo = function(){
  180. if (segundo < 59) {
  181. segundo++;
  182. if (segundo < 10)
  183. segundo = "0" + segundo;
  184. } else if (segundo == 59 && minuto < 59) {
  185. segundo = 0 + "0";
  186. minuto++;
  187. if (minuto < 10)
  188. minuto = "0" + minuto;
  189. }
  190. if (minuto == 59 && segundo == 59) {
  191. segundo = 0 + "0";
  192. minuto = 0 + "0";
  193. hora++;
  194. if (hora < 10)
  195. hora = "0" + hora;
  196. }
  197. form.cronometro.value = hora + ":" + minuto + ":" + segundo;
  198. }
  199. });
  200.  
  201. if ($_POST) {
  202. $opt = $_POST['opt'];
  203.  
  204. $servername = "localhost";
  205. $username = "USUARIO";
  206. $password = "SENHA";
  207. $dbname = "BANCO_DE_DADOS";
  208.  
  209. $conn = new mysqli($servername, $username, $password, $dbname);
  210. if ($conn->connect_error) {
  211. die("Connection failed: " . $conn->connect_error);
  212. }
  213.  
  214. if ($opt == "get_time") {
  215. $sql = "SELECT * FROM time_stamps WHERE id = 1";
  216. $result = $conn->query($sql);
  217.  
  218. $old_time_stamp;
  219. header('Content-Type: application/json');
  220. if ($result->num_rows > 0) {
  221. while($row = $result->fetch_assoc()) {
  222. $old_time_stamp = $row["time_stamp"];
  223. }
  224.  
  225. $date = new DateTime();
  226. $time_stamp = $date->getTimestamp();
  227.  
  228. echo json_encode(array("status" => "started", "time" => date('H:i:s', ($time_stamp - $old_time_stamp))));
  229. } else {
  230. $sql = "SELECT * FROM timer WHERE id = 1";
  231. $result = $conn->query($sql);
  232.  
  233. if ($result->num_rows > 0) {
  234. while($row = $result->fetch_assoc()) {
  235. echo json_encode(array("time" => $row["time"]));
  236. }
  237. }
  238. }
  239. } elseif ($opt == "start_timer") {
  240. $date = new DateTime();
  241. $time_stamp = $date->getTimestamp();
  242. $sql = "INSERT INTO time_stamps VALUES (1, '{$time_stamp}')";
  243. $result = $conn->query($sql);
  244. } elseif ($opt == "save_time") {
  245. $sql = "SELECT * FROM time_stamps WHERE id = 1";
  246. $result = $conn->query($sql);
  247.  
  248. $old_time_stamp;
  249. if ($result->num_rows > 0) {
  250. while($row = $result->fetch_assoc()) {
  251. $old_time_stamp = $row["time_stamp"];
  252. }
  253. }
  254.  
  255. $sql = "DELETE FROM time_stamps WHERE id = 1";
  256. $result = $conn->query($sql);
  257.  
  258. $date = new DateTime();
  259. $time_stamp = $date->getTimestamp();
  260.  
  261. $new_time = explode(":", date('H:i:s', ($time_stamp - $old_time_stamp)));
  262.  
  263. $sql = "SELECT * FROM timer WHERE id = 1";
  264. $result = $conn->query($sql);
  265.  
  266. $old_time;
  267. if ($result->num_rows > 0) {
  268. while($row = $result->fetch_assoc()) {
  269. $old_time = explode(":", $row["time"]);
  270. }
  271. }
  272.  
  273. $hour = intval($old_time[0] + $new_time[0]);
  274. $minute = intval($old_time[1] + $new_time[1]);
  275. $second = intval($old_time[2] + $new_time[2]);
  276. while ($second >= 60) {
  277. $second = $second - 60;
  278. $minute++;
  279. }
  280. while ($minute >= 60) {
  281. $minute = $minute - 60;
  282. $hour++;
  283. }
  284. if ($second < 10)
  285. $second = "0" . strval($second);
  286. if ($minute < 10)
  287. $minute = "0" . strval($minute);
  288. if ($hour < 10)
  289. $hour = "0" . strval($hour);
  290.  
  291. $time = "{$hour}:{$minute}:{$second}";
  292.  
  293. $sql = "UPDATE timer SET time = '{$time}' WHERE id = 1";
  294. $result = $conn->query($sql);
  295. }
  296. $conn->close();
  297. }
  298.  
  299. CREATE TABLE timer (
  300. id INT PRIMARY KEY,
  301. time VARCHAR(10) NOT NULL
  302. );
  303.  
  304. CREATE TABLE time_stamps (
  305. id INT PRIMARY KEY,
  306. time_stamp VARCHAR(255) NOT NULL
  307. );
  308.  
  309. INSERT INTO timer values (1, "00:00:00");
  310.  
  311. <?php
  312.  
  313. //
  314. // Lib
  315. //
  316.  
  317. const CHRON_PATH = 'pathtodata\';
  318.  
  319. const CHRON_STOP = 0x00;
  320. const CHRON_PAUSE = 0x01;
  321. const CHRON_PLAY = 0x03;
  322.  
  323. class PersistentChronometer {
  324. // fields
  325.  
  326. private $_id;
  327. private $_elapsed;
  328. private $_status;
  329. private $_statustime;
  330.  
  331. // construtor privado
  332.  
  333. private function __construct() {}
  334.  
  335. // propriedades
  336.  
  337. function __get($prop) {
  338. switch($prop) {
  339. case 'id':
  340. return $this->_id;
  341. case 'status':
  342. return $this->_status;
  343. case 'elapsed':
  344. $elapsed = $this->_elapsed;
  345.  
  346. if ($this->_status == CHRON_PLAY)
  347. $elapsed += max(microtime(true) - $this->_statustime, 0);
  348.  
  349. return $elapsed;
  350. }
  351. }
  352.  
  353. // comandos
  354.  
  355. public function play() {
  356. if($this->_status == CHRON_PLAY)
  357. return;
  358.  
  359. $this->_statustime = microtime(true);
  360. $this->_status = CHRON_PLAY;
  361. }
  362.  
  363. public function pause() {
  364. if($this->_status != CHRON_PLAY)
  365. return;
  366.  
  367. $time = microtime(true);
  368.  
  369. $this->_elapsed += max($time - $this->_statustime, 0);
  370.  
  371. $this->_statustime = microtime(true);
  372. $this->_status = CHRON_PAUSE;
  373. }
  374.  
  375. public function stop() {
  376. if($this->_status == CHRON_STOP)
  377. return;
  378.  
  379. $this->_statustime = microtime(true);
  380. $this->_elapsed = 0;
  381. $this->_status = CHRON_STOP;
  382. }
  383.  
  384. // persistência
  385.  
  386. public static function create() {
  387. $chron = new PersistentChronometer();
  388. $chron->_statustime = microtime(true);
  389. $chron->_elapsed = 0;
  390. $chron->_status = CHRON_STOP;
  391.  
  392. $i = 0;
  393. while (true) {
  394. $chron->_id = ((int)$chron->_statustime) . '$' . $i++;
  395.  
  396. $fname = CHRON_PATH . $chron->_id . '.chron';
  397. if(file_exists($fname))
  398. continue;
  399. $f = fopen($fname, 'w');
  400. fwrite($f, $chron->serialize());
  401. fclose($f);
  402. break;
  403. }
  404.  
  405. return $chron;
  406. }
  407.  
  408. public static function load($id) {
  409. $fname = CHRON_PATH . $id . '.chron';
  410.  
  411. if(!file_exists($fname))
  412. return false;
  413. $f = fopen($fname, 'r');
  414. $chron = PersistentChronometer::unserialize(fread($f, 255));
  415. fclose($f);
  416.  
  417. return $chron;
  418. }
  419.  
  420. public function save() {
  421. $fname = CHRON_PATH . $this->_id . '.chron';
  422. $f = fopen($fname, 'w');
  423. ftruncate($f, 0);
  424. fwrite($f, $this->serialize());
  425. fclose($f);
  426. }
  427.  
  428. public function delete() {
  429. $fname = CHRON_PATH . $this->_id . '.chron';
  430. unlink($fname);
  431. }
  432.  
  433. public function serialize() {
  434. return json_encode(array(
  435. 'id' => $this->_id,
  436. 'elapsed' => $this->_elapsed,
  437. 'status' => $this->_status,
  438. 'statustime' => $this->_statustime
  439. ));
  440. }
  441.  
  442. public static function unserialize($string) {
  443. $data = json_decode($string);
  444.  
  445. $chron = new PersistentChronometer();
  446. $chron->_id = $data->id;
  447. $chron->_elapsed = $data->elapsed;
  448. $chron->_status = $data->status;
  449. $chron->_statustime = $data->statustime;
  450.  
  451. return $chron;
  452. }
  453. }
  454.  
  455. //
  456. // Comandos
  457. //
  458.  
  459. if(isset($_GET['action'])) {
  460. switch($_GET['action']) {
  461. case 'play':
  462. if(isset($_GET['id'])
  463. && (($chron = PersistentChronometer::load($_GET['id'])) !== false)) {
  464. $chron->play();
  465. $chron->save();
  466. }
  467. break;
  468. case 'pause':
  469. if(isset($_GET['id'])
  470. && (($chron = PersistentChronometer::load($_GET['id'])) !== false)) {
  471. $chron->pause();
  472. $chron->save();
  473. }
  474. break;
  475. case 'stop':
  476. if(isset($_GET['id'])
  477. && (($chron = PersistentChronometer::load($_GET['id'])) !== false)) {
  478. $chron->stop();
  479. $chron->save();
  480. }
  481. break;
  482. case 'new':
  483. PersistentChronometer::create();
  484. break;
  485. case 'delete':
  486. if(isset($_GET['id'])
  487. && (($chron = PersistentChronometer::load($_GET['id'])) !== false)) {
  488. $chron->delete();
  489. }
  490. break;
  491. case 'get':
  492. if(isset($_GET['id'])
  493. && (($chron = PersistentChronometer::load($_GET['id'])) !== false)) {
  494.  
  495. $data = new stdClass();
  496. $data->id = $chron->id;
  497. $data->elapsed = $chron->elapsed;
  498. $data->status = $chron->status;
  499. $data->result = true;
  500.  
  501. echo json_encode($data);
  502. } else {
  503. echo '{"result": false}';
  504. }
  505.  
  506. return;
  507. }
  508. }
  509.  
  510. //
  511. // Output
  512. //
  513.  
  514. ?>
  515. <!DOCTYPE html>
  516. <html>
  517. <head>
  518. <script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
  519. <script>
  520. $(function(){
  521. var cEl = $('#chron');
  522. if(!window.localStorage)
  523. cEl.text('Para esta solução é necessário o uso de localStorage. Mas também podem ser utilizados cookies ou variaveis de sessão!!!');
  524. else {
  525. var id = localStorage.getItem("chron-id");
  526.  
  527. if(!id)
  528. cEl.text('Nenhum cronômetro definido!');
  529. else {
  530. loadChronometer(id);
  531. cEl.text('Aguarde...');
  532. }
  533. }
  534. });
  535.  
  536. function setChronometer(id) {
  537. localStorage.setItem("chron-id", id);
  538. loadChronometer(id);
  539. }
  540.  
  541. function loadChronometer(id) {
  542. var status = {
  543. <?php echo CHRON_STOP ?>: 'Parado',
  544. <?php echo CHRON_PLAY ?>: 'Executando',
  545. <?php echo CHRON_PAUSE ?>: 'Interrompido'
  546. };
  547. var cEl = $('#chron');
  548. $.getJSON('?action=get&id=' + id, null, function(data) {
  549. if(data.result)
  550. cEl.text(
  551. 'ID: ' + data.id + "n" +
  552. 'Estado: ' + status[data.status] + "n" +
  553. 'Tempo (seg): ' + data.elapsed + "n"
  554. ).append(
  555. '<a href="javascript:setChronometer('' + data.id + '')">Atualizar</a> | ' +
  556. (data.status == <?php echo CHRON_STOP ?> ? '' : '<a href="?action=stop&id=' + data.id + '">Parar</a> | ') +
  557. (data.status == <?php echo CHRON_PLAY ?> ? '' : '<a href="?action=play&id=' + data.id + '">Executar</a> | ') +
  558. (data.status != <?php echo CHRON_PLAY ?> ? '' : '<a href="?action=pause&id=' + data.id + '">Interromper</a> | ') +
  559. '<a href="javascript:setChronometer(null)">Remover</a>'
  560. );
  561. else
  562. cEl.text('Nenhum cronômetro definido!');
  563. });
  564. }
  565. </script>
  566. </head>
  567. <body>
  568. <h1>Cronômetro padrão</h1>
  569.  
  570. <pre id="chron" style="white-space: pre"></pre>
  571.  
  572.  
  573. <h1>Gerenciador</h1>
  574. <table>
  575. <thead>
  576. <td>ID</td>
  577. <td>Estado</td>
  578. <td colspan="5">Comandos</td>
  579. <td>Tempo (seg)</td>
  580. </thead>
  581. <?php
  582.  
  583. $files = scandir(CHRON_PATH);
  584. $chrons = array();
  585. foreach($files as $file) {
  586. if (substr($file, -6) == '.chron')
  587. $chrons[] = PersistentChronometer::load(substr($file, 0, -6));
  588. }
  589.  
  590. $status = array(
  591. CHRON_STOP => 'Parado',
  592. CHRON_PLAY => 'Executando',
  593. CHRON_PAUSE => 'Interrompido'
  594. );
  595.  
  596. foreach($chrons as $chron) {
  597. $td = array();
  598. $td[] = $chron->id;
  599. $td[] = $status[$chron->status];
  600.  
  601. $td[] = $chron->status == CHRON_STOP ? '' : '<a href="?action=stop&id='. $chron->id .'">Parar</a>';
  602. $td[] = $chron->status == CHRON_PLAY ? '' : '<a href="?action=play&id='. $chron->id .'">Executar</a>';
  603. $td[] = $chron->status != CHRON_PLAY ? '' : '<a href="?action=pause&id='. $chron->id .'">Interromper</a>';
  604. $td[] = '<a href="?action=delete&id='. $chron->id .'">Destruir</a>';
  605. $td[] = '<a href="javascript:setChronometer(''. $chron->id .'')">Padrão</a>';
  606. $td[] = $chron->elapsed;
  607. echo '<tr id="cron-'. $chron->id .'"><td>'. implode('</td><td>', $td) .'</td></tr>';
  608. }
  609.  
  610. ?>
  611. </table>
  612. <a href="?action=new">Novo cronômetro</a>
  613. </body>
  614. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement