Cron.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. /* @usage - inside cli script:
  4. * $cronTaskName = 'checkInstall';
  5. * $keyToken = 'bash_install_check';
  6. * $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  7. * $output = Router::getRoute('Cron')->executeCurlTastByToken($cronTaskName, $keyToken, $token);
  8. */
  9. /* @usage - inside cli script with args:
  10. * $cronTaskName = 'forceTablePerms';
  11. * $keyToken = 'bash_force_table_perms';
  12. * $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  13. * $output = Router::getRoute('Cron')->executeCurlTastByToken($cronTaskName, $keyToken, $token, [ 'idGroup' => 3, 'table' => 'CRM_PROCES' ]);
  14. */
  15. // TEST: $ php SE/se-lib/Route/Cron-test.php biuro.biall-net.pl
  16. class Route_Cron extends RouteBase {
  17. public function handleAuth() {
  18. if (User::logged()) {
  19. } else if ($this->authByToken()) {
  20. } else throw new HttpException('Unauthorized', 401);
  21. }
  22. public function generateCliAuthToken($cliKey, $task, $ttl = 300) {
  23. $generatedToken = uniqid();
  24. $parts = array();
  25. $parts[] = $generatedToken;
  26. $parts[] = $task;
  27. $parts[] = $ttl;
  28. $parts[] = time();
  29. $token = implode(",", $parts);
  30. $sqlCliKey = "CronCliAuthToken:{$cliKey}";
  31. $sth = DB::getPDO()->prepare("
  32. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  33. values ( :cliKey, :token )
  34. on duplicate key update CONF_VAL = :token
  35. ");
  36. $sth->bindValue(':cliKey', $sqlCliKey, PDO::PARAM_STR);
  37. $sth->bindValue(':token', $token, PDO::PARAM_STR);
  38. $sth->execute();
  39. return $generatedToken;
  40. }
  41. public function authByToken() {
  42. $cliKey = V::get('_key', '', $_REQUEST);
  43. $cliToken = V::get('_token', '', $_REQUEST);
  44. $sqlCliKey = "CronCliAuthToken:{$cliKey}";
  45. $sth = DB::getPDO()->prepare("
  46. select c.CONF_VAL
  47. from CRM_CONFIG c
  48. where CONF_KEY = :cliKey
  49. order by c.ID desc
  50. limit 1
  51. ");
  52. $sth->bindValue(':cliKey', $sqlCliKey, PDO::PARAM_STR);
  53. $sth->execute();
  54. $rawToken = $sth->fetch();
  55. if (!$rawToken || !$rawToken['CONF_VAL']) throw new HttpException("Unauthorized - token not found #1-" . __LINE__, 401);
  56. $rawToken = explode(',', $rawToken['CONF_VAL']);
  57. DBG::_('DBG_CRON', '>1', 'rawToken', $rawToken, __CLASS__, __FUNCTION__, __LINE__);
  58. if (4 != count($rawToken)) throw new HttpException("Unauthorized - token not found #2-" . __LINE__, 401);
  59. if ($cliToken != $rawToken[0]) throw new HttpException("Unauthorized - token not found #3-" . __LINE__, 401);
  60. $task = $rawToken[1];
  61. $ttl = (int)$rawToken[2];
  62. $createDateTimestamp = (int)$rawToken[3];
  63. if (!$ttl) throw new HttpException("Unauthorized - token not found #4-" . __LINE__, 401);
  64. if (!$createDateTimestamp) throw new HttpException("Unauthorized - token not found #5-" . __LINE__, 401);
  65. DBG::_('DBG_CRON', '>1', 'rawToken', array('createDateTimestamp'=>$createDateTimestamp, 'ttl'=>$ttl, 'cur'=>time()), __CLASS__, __FUNCTION__, __LINE__);
  66. if ($createDateTimestamp + $ttl < time()) {
  67. // TODO: remove record from table?
  68. throw new HttpException("Unauthorized - token expired #6-" . __LINE__, 401);
  69. }
  70. session_write_close();// changes in $_SESSION visible only in current process
  71. $_SESSION['AUTHORIZE_USER'] = 'anonymous';
  72. $_SESSION['ADM_NAME'] = 'Anonymous';
  73. $_SESSION['ADM_ACCOUNT'] = $_SERVER['REMOTE_ADDR'];
  74. $_SESSION['ADM_ADMIN_LEVEL'] = 10;
  75. $_SESSION['ADM_ID'] = 9999999999;
  76. DBG::_('DBG_CRON', '>1', 'rawToken', array('createDateTimestamp'=>$createDateTimestamp, 'ttl'=>$ttl, 'cur'=>time()), __CLASS__, __FUNCTION__, __LINE__);
  77. $this->runTask($task);
  78. }
  79. public function executeCurlTastByToken($cronTaskName, $keyToken, $token, $args = []) { // @require $_SERVER['SERVER_NAME']
  80. $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
  81. if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
  82. //file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
  83. $url = "{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task={$cronTaskName}";
  84. if (!empty($args)) $url .= "&" . implode("&", array_map(function ($key, $val) {
  85. return "{$key}={$val}";
  86. }, array_keys($args), array_values($args)));
  87. $ch = curl_init();
  88. curl_setopt($ch, CURLOPT_VERBOSE, true);
  89. curl_setopt($ch, CURLOPT_URL, $url);
  90. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  91. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  92. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  93. $return = curl_exec($ch);
  94. curl_close($ch);
  95. return $return;
  96. }
  97. public function defaultAction() {
  98. Lib::loadClass('UI');
  99. UI::gora();
  100. echo UI::h('div', [ 'class' => "container" ], [
  101. UI::h('h1', [], "Cron"),
  102. "...",
  103. ]);
  104. UI::dol();
  105. }
  106. public function dbgClearNofityAction() {
  107. Lib::loadClass('UI');
  108. UI::gora();
  109. try {
  110. DB::getPDO()->execSql("update `CRM_NOTIFY` set `last_exec_time` = null");
  111. UI::alert('info', "Notify cleared");
  112. } catch (Exception $e) {
  113. UI::alert('danger', "Error: " . $e->getMessage());
  114. }
  115. UI::dol();
  116. }
  117. public function dbgChangeNofityToDayBeforeAction() {
  118. Lib::loadClass('UI');
  119. UI::gora();
  120. try {
  121. DB::getPDO()->execSql("update `CRM_NOTIFY` set `last_exec_time` = DATE_SUB(NOW(), INTERVAL 1 DAY)");
  122. UI::alert('info', "Notify cleared");
  123. } catch (Exception $e) {
  124. UI::alert('danger', "Error: " . $e->getMessage());
  125. }
  126. UI::dol();
  127. }
  128. public function sendNotifyAction() {
  129. Lib::loadClass('UI');
  130. $notify = Router::getRoute('Notify');
  131. $todoReminders = array();
  132. if (V::get('DBG_CRON', null, $_GET) > 0) UI::gora();
  133. echo '<div class="container">' . "\n";
  134. echo '<h1>Cron</h1>' . "\n";
  135. try {
  136. if (V::get('DBG_CRON', null, $_GET) > 0) DBG::table("reminders state - before", DB::getPDO()->fetchAll("select * from CRM_NOTIFY order by last_exec_time limit 20"), __CLASS__, __FUNCTION__, __LINE__);
  137. {// limit send time to 8 - 20
  138. $timeNow = time();
  139. $timeSendLimitFrom = mktime(8, 0, 0, date('n'), date('j'), date('Y'));
  140. $timeSendLimitTo = mktime(20, 0, 0, date('n'), date('j'), date('Y'));
  141. $dayNrNow = date('N');
  142. $daysAllowed = array(1, 2, 3, 4, 5);// 1 = Poniedziałek, ... , 6 - Sobota, 7 - Niedziela
  143. if ($timeNow > $timeSendLimitFrom && $timeNow < $timeSendLimitTo && in_array($dayNrNow, $daysAllowed)) {
  144. $todoReminders = $notify->getTodoList(2, array('once_a_day', 'immediately'));
  145. }
  146. }
  147. DBG::_('DBG_CRON', '>0', 'todoReminders', $todoReminders, __CLASS__, __FUNCTION__, __LINE__);
  148. foreach ($todoReminders as $who => $userReminders) {
  149. echo "<p>Sending to {$who} reminders {" . json_encode($userReminders) . "}</p>" . "\n";
  150. //$notify->sendUserReminders($who, $userReminders, $forceMail = 'plabudda@biall-net.pl');// TEST
  151. $notify->sendUserReminders($who, $userReminders);
  152. foreach ($userReminders as $when => $listWhat) {
  153. if (!empty($listWhat)) {
  154. // $reminders = array_keys($listWhat);
  155. // echo "<p>Sending to {$who} reminders [" . implode(",", $reminders) . "] at '{$when}'</p>" . "\n";
  156. // $notify->send($who, $listWhat, $when, $forceMail = 'plabudda@biall-net.pl');
  157. $notify->markAsSent($who, $listWhat, $when);
  158. }
  159. }
  160. }
  161. if (V::get('DBG_CRON', null, $_GET) > 0) DBG::table("reminders state - after", DB::getPDO()->fetchAll("select * from CRM_NOTIFY order by last_exec_time limit 20"), __CLASS__, __FUNCTION__, __LINE__);
  162. } catch (Exception $e) {
  163. UI::alert('danger', "#" . $e->getLine() . ":" . $e->getMessage());
  164. }
  165. echo "\n" . '</div>';// .container
  166. echo "\n.EOF\n";
  167. }
  168. public function checkInstallAction() {
  169. Lib::loadClass('Router');
  170. $routeToReinstallList = array();
  171. //$routeToReinstallList[] = 'Config';// Config must work before (url token)
  172. $routeToReinstallList[] = 'Msgs';
  173. $routeToReinstallList[] = 'FixProjectPath';
  174. $routeToReinstallList[] = 'FixZasobPath';
  175. $routeToReinstallList[] = 'FixCrmProcesInitIdx';
  176. $routeToReinstallList[] = 'Notify';
  177. $routeToReinstallList[] = 'UrlAction_WmsGenerate';
  178. // $routeToReinstallList[] = 'FileStorage';// reinstall in bash_install_check.php
  179. foreach ($routeToReinstallList as $routeName) {
  180. $route = Router::getRoute($routeName);
  181. $route->reinstall();
  182. echo " - {$routeName} checked\n";
  183. }
  184. echo "\n.EOF\n";
  185. }
  186. /* @usage - inside cli script with args:
  187. * $cronTaskName = 'forceTablePerms';
  188. * $keyToken = 'bash_force_table_perms';
  189. * $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  190. * $output = Router::getRoute('Cron')->executeCurlTastByToken($cronTaskName, $keyToken, $token, [ 'idGroup' => 3, 'table' => 'CRM_PROCES' ]);
  191. */
  192. public function forceTablePermsAction() {
  193. $idGroup = V::get('idGroup', 0, $_GET, 'int');
  194. if (!$idGroup) throw new Exception("Missing idGroup");
  195. $table = V::get('table', '', $_GET, 'word');
  196. if (!$table) throw new Exception("Missing table");
  197. Lib::loadClass('UsersLdapHelper');
  198. $groupsNetwork = UsersLdapHelper::getGroupsByID($idGroup);
  199. if (empty($groupsNetwork)) throw new Exception("Group {$idGroup} not found");
  200. foreach ($groupsNetwork as $vGroup) {
  201. echo "Will try to update table ".$table." set A_CLASSIFIED='".$vGroup->cn."', A_ADM_COMPANY='".$vGroup->cn."' ;" . "\n";
  202. // DB::getPDO()->execSql("update table `{$table}` set `A_CLASSIFIED`='{$vGroup->cn}', `A_ADM_COMPANY`='{$vGroup->cn}' ");
  203. }
  204. echo "DONE";
  205. }
  206. }