functions.inc.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. <?php
  2. function isset_has_content($var) {
  3. if (isset($var) && $var != "") {
  4. return true;
  5. }
  6. else {
  7. return false;
  8. }
  9. }
  10. function hash_password($password) {
  11. $salt_str = bin2hex(openssl_random_pseudo_bytes(8));
  12. return "{SSHA256}".base64_encode(hash('sha256', $password . $salt_str, true) . $salt_str);
  13. }
  14. function last_login($user) {
  15. global $pdo;
  16. $stmt = $pdo->prepare('SELECT `remote`, `time` FROM `logs`
  17. WHERE JSON_EXTRACT(`call`, "$[0]") = "check_login"
  18. AND JSON_EXTRACT(`call`, "$[1]") = :user
  19. AND `type` = "success" ORDER BY `time` DESC LIMIT 1');
  20. $stmt->execute(array(':user' => $user));
  21. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  22. if (!empty($row)) {
  23. return $row;
  24. }
  25. else {
  26. return false;
  27. }
  28. }
  29. function flush_memcached() {
  30. try {
  31. $m = new Memcached();
  32. $m->addServer('memcached', 11211);
  33. $m->flush();
  34. }
  35. catch ( Exception $e ) {
  36. // Dunno
  37. }
  38. }
  39. function sys_mail($_data) {
  40. if ($_SESSION['mailcow_cc_role'] != "admin") {
  41. $_SESSION['return'][] = array(
  42. 'type' => 'danger',
  43. 'log' => array(__FUNCTION__),
  44. 'msg' => 'access_denied'
  45. );
  46. return false;
  47. }
  48. $excludes = $_data['mass_exclude'];
  49. $includes = $_data['mass_include'];
  50. $mailboxes = array();
  51. $mass_from = $_data['mass_from'];
  52. $mass_text = $_data['mass_text'];
  53. $mass_subject = $_data['mass_subject'];
  54. if (!filter_var($mass_from, FILTER_VALIDATE_EMAIL)) {
  55. $_SESSION['return'][] = array(
  56. 'type' => 'danger',
  57. 'log' => array(__FUNCTION__),
  58. 'msg' => 'from_invalid'
  59. );
  60. return false;
  61. }
  62. if (empty($mass_subject)) {
  63. $_SESSION['return'][] = array(
  64. 'type' => 'danger',
  65. 'log' => array(__FUNCTION__),
  66. 'msg' => 'subject_empty'
  67. );
  68. return false;
  69. }
  70. if (empty($mass_text)) {
  71. $_SESSION['return'][] = array(
  72. 'type' => 'danger',
  73. 'log' => array(__FUNCTION__),
  74. 'msg' => 'text_empty'
  75. );
  76. return false;
  77. }
  78. $domains = array_merge(mailbox('get', 'domains'), mailbox('get', 'alias_domains'));
  79. foreach ($domains as $domain) {
  80. foreach (mailbox('get', 'mailboxes', $domain) as $mailbox) {
  81. $mailboxes[] = $mailbox;
  82. }
  83. }
  84. if (!empty($includes)) {
  85. $rcpts = array_intersect($mailboxes, $includes);
  86. }
  87. elseif (!empty($excludes)) {
  88. $rcpts = array_diff($mailboxes, $excludes);
  89. }
  90. else {
  91. $rcpts = $mailboxes;
  92. }
  93. if (!empty($rcpts)) {
  94. ini_set('max_execution_time', 0);
  95. ini_set('max_input_time', 0);
  96. $mail = new PHPMailer;
  97. $mail->Timeout = 10;
  98. $mail->SMTPOptions = array(
  99. 'ssl' => array(
  100. 'verify_peer' => false,
  101. 'verify_peer_name' => false,
  102. 'allow_self_signed' => true
  103. )
  104. );
  105. $mail->isSMTP();
  106. $mail->Host = 'dovecot-mailcow';
  107. $mail->SMTPAuth = false;
  108. $mail->Port = 24;
  109. $mail->setFrom($mass_from);
  110. $mail->Subject = $mass_subject;
  111. $mail->CharSet ="UTF-8";
  112. $mail->Body = $mass_text;
  113. $mail->XMailer = 'MooMassMail';
  114. foreach ($rcpts as $rcpt) {
  115. $mail->AddAddress($rcpt);
  116. if (!$mail->send()) {
  117. $_SESSION['return'][] = array(
  118. 'type' => 'warning',
  119. 'log' => array(__FUNCTION__),
  120. 'msg' => 'Mailer error (RCPT "' . htmlspecialchars($rcpt) . '"): ' . str_replace('https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting', '', $mail->ErrorInfo)
  121. );
  122. }
  123. $mail->ClearAllRecipients();
  124. }
  125. }
  126. $_SESSION['return'][] = array(
  127. 'type' => 'success',
  128. 'log' => array(__FUNCTION__),
  129. 'msg' => 'Mass mail job completed, sent ' . count($rcpts) . ' mails'
  130. );
  131. }
  132. function logger($_data = false) {
  133. /*
  134. logger() will be called as last function
  135. To manually log a message, logger needs to be called like below.
  136. logger(array(
  137. 'return' => array(
  138. array(
  139. 'type' => 'danger',
  140. 'log' => array(__FUNCTION__),
  141. 'msg' => $err
  142. )
  143. )
  144. ));
  145. These messages will not be printed as alert box.
  146. To do so, push them to $_SESSION['return'] and do not call logger as they will be included automatically:
  147. $_SESSION['return'][] = array(
  148. 'type' => 'danger',
  149. 'log' => array(__FUNCTION__, $user, '*'),
  150. 'msg' => $err
  151. );
  152. */
  153. global $pdo;
  154. if (!$_data) {
  155. $_data = $_SESSION;
  156. }
  157. if (!empty($_data['return'])) {
  158. $task = substr(strtoupper(md5(uniqid(rand(), true))), 0, 6);
  159. foreach ($_data['return'] as $return) {
  160. $type = $return['type'];
  161. $msg = json_encode($return['msg'], JSON_UNESCAPED_UNICODE);
  162. $call = json_encode($return['log'], JSON_UNESCAPED_UNICODE);
  163. if (!empty($_SESSION["dual-login"]["username"])) {
  164. $user = $_SESSION["dual-login"]["username"] . ' => ' . $_SESSION['mailcow_cc_username'];
  165. $role = $_SESSION["dual-login"]["role"] . ' => ' . $_SESSION['mailcow_cc_role'];
  166. }
  167. elseif (!empty($_SESSION['mailcow_cc_username'])) {
  168. $user = $_SESSION['mailcow_cc_username'];
  169. $role = $_SESSION['mailcow_cc_role'];
  170. }
  171. else {
  172. $user = 'unauthenticated';
  173. $role = 'unauthenticated';
  174. }
  175. // We cannot log when logs is missing...
  176. try {
  177. $stmt = $pdo->prepare("INSERT INTO `logs` (`type`, `task`, `msg`, `call`, `user`, `role`, `remote`, `time`) VALUES
  178. (:type, :task, :msg, :call, :user, :role, :remote, UNIX_TIMESTAMP())");
  179. $stmt->execute(array(
  180. ':type' => $type,
  181. ':task' => $task,
  182. ':call' => $call,
  183. ':msg' => $msg,
  184. ':user' => $user,
  185. ':role' => $role,
  186. ':remote' => get_remote_ip()
  187. ));
  188. }
  189. catch (Exception $e) {
  190. // Do nothing
  191. }
  192. }
  193. }
  194. else {
  195. return true;
  196. }
  197. }
  198. function hasDomainAccess($username, $role, $domain) {
  199. global $pdo;
  200. if (!filter_var($username, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  201. return false;
  202. }
  203. if (empty($domain) || !is_valid_domain_name($domain)) {
  204. return false;
  205. }
  206. if ($role != 'admin' && $role != 'domainadmin') {
  207. return false;
  208. }
  209. if ($role == 'admin') {
  210. $stmt = $pdo->prepare("SELECT `domain` FROM `domain`
  211. WHERE `domain` = :domain");
  212. $stmt->execute(array(':domain' => $domain));
  213. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  214. $stmt = $pdo->prepare("SELECT `alias_domain` FROM `alias_domain`
  215. WHERE `alias_domain` = :domain");
  216. $stmt->execute(array(':domain' => $domain));
  217. $num_results = $num_results + count($stmt->fetchAll(PDO::FETCH_ASSOC));
  218. if ($num_results != 0) {
  219. return true;
  220. }
  221. }
  222. elseif ($role == 'domainadmin') {
  223. $stmt = $pdo->prepare("SELECT `domain` FROM `domain_admins`
  224. WHERE (
  225. `active`='1'
  226. AND `username` = :username
  227. AND (`domain` = :domain1 OR `domain` = (SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain2))
  228. )");
  229. $stmt->execute(array(':username' => $username, ':domain1' => $domain, ':domain2' => $domain));
  230. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  231. if (!empty($num_results)) {
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. function hasMailboxObjectAccess($username, $role, $object) {
  238. global $pdo;
  239. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  240. return false;
  241. }
  242. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  243. return false;
  244. }
  245. if ($username == $object) {
  246. return true;
  247. }
  248. $stmt = $pdo->prepare("SELECT `domain` FROM `mailbox` WHERE `username` = :object");
  249. $stmt->execute(array(':object' => $object));
  250. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  251. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  252. return true;
  253. }
  254. return false;
  255. }
  256. function hasAliasObjectAccess($username, $role, $object) {
  257. global $pdo;
  258. if (!filter_var(html_entity_decode(rawurldecode($username)), FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $username))) {
  259. return false;
  260. }
  261. if ($role != 'admin' && $role != 'domainadmin' && $role != 'user') {
  262. return false;
  263. }
  264. if ($username == $object) {
  265. return true;
  266. }
  267. $stmt = $pdo->prepare("SELECT `domain` FROM `alias` WHERE `address` = :object");
  268. $stmt->execute(array(':object' => $object));
  269. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  270. if (isset($row['domain']) && hasDomainAccess($username, $role, $row['domain'])) {
  271. return true;
  272. }
  273. return false;
  274. }
  275. function pem_to_der($pem_key) {
  276. // Need to remove BEGIN/END PUBLIC KEY
  277. $lines = explode("\n", trim($pem_key));
  278. unset($lines[count($lines)-1]);
  279. unset($lines[0]);
  280. return base64_decode(implode('', $lines));
  281. }
  282. function generate_tlsa_digest($hostname, $port, $starttls = null) {
  283. if (!is_valid_domain_name($hostname)) {
  284. return "Not a valid hostname";
  285. }
  286. if (empty($starttls)) {
  287. $context = stream_context_create(array("ssl" => array("capture_peer_cert" => true, 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  288. $stream = stream_socket_client('ssl://' . $hostname . ':' . $port, $error_nr, $error_msg, 5, STREAM_CLIENT_CONNECT, $context);
  289. if (!$stream) {
  290. $error_msg = isset($error_msg) ? $error_msg : '-';
  291. return $error_nr . ': ' . $error_msg;
  292. }
  293. }
  294. else {
  295. $stream = stream_socket_client('tcp://' . $hostname . ':' . $port, $error_nr, $error_msg, 5);
  296. if (!$stream) {
  297. return $error_nr . ': ' . $error_msg;
  298. }
  299. $banner = fread($stream, 512 );
  300. if (preg_match("/^220/i", $banner)) { // SMTP
  301. fwrite($stream,"HELO tlsa.generator.local\r\n");
  302. fread($stream, 512);
  303. fwrite($stream,"STARTTLS\r\n");
  304. fread($stream, 512);
  305. }
  306. elseif (preg_match("/imap.+starttls/i", $banner)) { // IMAP
  307. fwrite($stream,"A1 STARTTLS\r\n");
  308. fread($stream, 512);
  309. }
  310. elseif (preg_match("/^\+OK/", $banner)) { // POP3
  311. fwrite($stream,"STLS\r\n");
  312. fread($stream, 512);
  313. }
  314. elseif (preg_match("/^OK/m", $banner)) { // Sieve
  315. fwrite($stream,"STARTTLS\r\n");
  316. fread($stream, 512);
  317. }
  318. else {
  319. return 'Unknown banner: "' . htmlspecialchars(trim($banner)) . '"';
  320. }
  321. // Upgrade connection
  322. stream_set_blocking($stream, true);
  323. stream_context_set_option($stream, 'ssl', 'capture_peer_cert', true);
  324. stream_context_set_option($stream, 'ssl', 'verify_peer', false);
  325. stream_context_set_option($stream, 'ssl', 'verify_peer_name', false);
  326. stream_context_set_option($stream, 'ssl', 'allow_self_signed', true);
  327. stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
  328. stream_set_blocking($stream, false);
  329. }
  330. $params = stream_context_get_params($stream);
  331. if (!empty($params['options']['ssl']['peer_certificate'])) {
  332. $key_resource = openssl_pkey_get_public($params['options']['ssl']['peer_certificate']);
  333. // We cannot get ['rsa']['n'], the binary data would contain BEGIN/END PUBLIC KEY
  334. $key_data = openssl_pkey_get_details($key_resource)['key'];
  335. return '3 1 1 ' . openssl_digest(pem_to_der($key_data), 'sha256');
  336. }
  337. else {
  338. return 'Error: Cannot read peer certificate';
  339. }
  340. }
  341. function alertbox_log_parser($_data){
  342. global $lang;
  343. if (isset($_data['return'])) {
  344. foreach ($_data['return'] as $return) {
  345. // Get type
  346. $type = $return['type'];
  347. // If a lang[type][msg] string exists, use it as message
  348. if (is_string($lang[$return['type']][$return['msg']])) {
  349. $msg = $lang[$return['type']][$return['msg']];
  350. }
  351. // If msg is an array, use first element as language string and run printf on it with remaining array elements
  352. elseif (is_array($return['msg'])) {
  353. $msg = array_shift($return['msg']);
  354. $msg = vsprintf(
  355. $lang[$return['type']][$msg],
  356. $return['msg']
  357. );
  358. }
  359. // If none applies, use msg as returned message
  360. else {
  361. $msg = $return['msg'];
  362. }
  363. $log_array[] = array('msg' => json_encode($msg), 'type' => json_encode($type));
  364. }
  365. if (!empty($log_array)) {
  366. return $log_array;
  367. }
  368. }
  369. return false;
  370. }
  371. function verify_hash($hash, $password) {
  372. if (preg_match('/^{SSHA256}/i', $hash)) {
  373. // Remove tag if any
  374. $hash = preg_replace('/^{SSHA256}/i', '', $hash);
  375. // Decode hash
  376. $dhash = base64_decode($hash);
  377. // Get first 32 bytes of binary which equals a SHA256 hash
  378. $ohash = substr($dhash, 0, 32);
  379. // Remove SHA256 hash from decoded hash to get original salt string
  380. $osalt = str_replace($ohash, '', $dhash);
  381. // Check single salted SHA256 hash against extracted hash
  382. if (hash_equals(hash('sha256', $password . $osalt, true), $ohash)) {
  383. return true;
  384. }
  385. }
  386. elseif (preg_match('/^{PLAIN-MD5}/i', $hash)) {
  387. $hash = preg_replace('/^{PLAIN-MD5}/i', '', $hash);
  388. if (md5($password) == $hash) {
  389. return true;
  390. }
  391. }
  392. elseif (preg_match('/^{SHA512-CRYPT}/i', $hash)) {
  393. // Remove tag if any
  394. $hash = preg_replace('/^{SHA512-CRYPT}/i', '', $hash);
  395. // Decode hash
  396. preg_match('/\\$6\\$(.*)\\$(.*)/i', $hash, $hash_array);
  397. $osalt = $hash_array[1];
  398. $ohash = $hash_array[2];
  399. if (hash_equals(crypt($password, '$6$' . $osalt . '$'), $hash)) {
  400. return true;
  401. }
  402. }
  403. elseif (preg_match('/^{SSHA512}/i', $hash)) {
  404. $hash = preg_replace('/^{SSHA512}/i', '', $hash);
  405. // Decode hash
  406. $dhash = base64_decode($hash);
  407. // Get first 64 bytes of binary which equals a SHA512 hash
  408. $ohash = substr($dhash, 0, 64);
  409. // Remove SHA512 hash from decoded hash to get original salt string
  410. $osalt = str_replace($ohash, '', $dhash);
  411. // Check single salted SHA512 hash against extracted hash
  412. if (hash_equals(hash('sha512', $password . $osalt, true), $ohash)) {
  413. return true;
  414. }
  415. }
  416. elseif (preg_match('/^{MD5-CRYPT}/i', $hash)) {
  417. $hash = preg_replace('/^{MD5-CRYPT}/i', '', $hash);
  418. if (password_verify($password, $hash)) {
  419. return true;
  420. }
  421. }
  422. return false;
  423. }
  424. function check_login($user, $pass) {
  425. global $pdo;
  426. global $redis;
  427. global $imap_server;
  428. if (!filter_var($user, FILTER_VALIDATE_EMAIL) && !ctype_alnum(str_replace(array('_', '.', '-'), '', $user))) {
  429. $_SESSION['return'][] = array(
  430. 'type' => 'danger',
  431. 'log' => array(__FUNCTION__, $user, '*'),
  432. 'msg' => 'malformed_username'
  433. );
  434. return false;
  435. }
  436. $user = strtolower(trim($user));
  437. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  438. WHERE `superadmin` = '1'
  439. AND `active` = '1'
  440. AND `username` = :user");
  441. $stmt->execute(array(':user' => $user));
  442. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  443. foreach ($rows as $row) {
  444. if (verify_hash($row['password'], $pass)) {
  445. if (get_tfa($user)['name'] != "none") {
  446. $_SESSION['pending_mailcow_cc_username'] = $user;
  447. $_SESSION['pending_mailcow_cc_role'] = "admin";
  448. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  449. unset($_SESSION['ldelay']);
  450. $_SESSION['return'][] = array(
  451. 'type' => 'info',
  452. 'log' => array(__FUNCTION__, $user, '*'),
  453. 'msg' => 'awaiting_tfa_confirmation'
  454. );
  455. return "pending";
  456. }
  457. else {
  458. unset($_SESSION['ldelay']);
  459. // Reactivate TFA if it was set to "deactivate TFA for next login"
  460. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  461. $stmt->execute(array(':user' => $user));
  462. $_SESSION['return'][] = array(
  463. 'type' => 'success',
  464. 'log' => array(__FUNCTION__, $user, '*'),
  465. 'msg' => array('logged_in_as', $user)
  466. );
  467. return "admin";
  468. }
  469. }
  470. }
  471. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  472. WHERE `superadmin` = '0'
  473. AND `active`='1'
  474. AND `username` = :user");
  475. $stmt->execute(array(':user' => $user));
  476. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  477. foreach ($rows as $row) {
  478. if (verify_hash($row['password'], $pass) !== false) {
  479. if (get_tfa($user)['name'] != "none") {
  480. $_SESSION['pending_mailcow_cc_username'] = $user;
  481. $_SESSION['pending_mailcow_cc_role'] = "domainadmin";
  482. $_SESSION['pending_tfa_method'] = get_tfa($user)['name'];
  483. unset($_SESSION['ldelay']);
  484. $_SESSION['return'][] = array(
  485. 'type' => 'info',
  486. 'log' => array(__FUNCTION__, $user, '*'),
  487. 'msg' => 'awaiting_tfa_confirmation'
  488. );
  489. return "pending";
  490. }
  491. else {
  492. unset($_SESSION['ldelay']);
  493. // Reactivate TFA if it was set to "deactivate TFA for next login"
  494. $stmt = $pdo->prepare("UPDATE `tfa` SET `active`='1' WHERE `username` = :user");
  495. $stmt->execute(array(':user' => $user));
  496. $_SESSION['return'][] = array(
  497. 'type' => 'success',
  498. 'log' => array(__FUNCTION__, $user, '*'),
  499. 'msg' => array('logged_in_as', $user)
  500. );
  501. return "domainadmin";
  502. }
  503. }
  504. }
  505. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  506. WHERE `kind` NOT REGEXP 'location|thing|group'
  507. AND `active`='1'
  508. AND `username` = :user");
  509. $stmt->execute(array(':user' => $user));
  510. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  511. foreach ($rows as $row) {
  512. if (verify_hash($row['password'], $pass) !== false) {
  513. unset($_SESSION['ldelay']);
  514. $_SESSION['return'][] = array(
  515. 'type' => 'success',
  516. 'log' => array(__FUNCTION__, $user, '*'),
  517. 'msg' => array('logged_in_as', $user)
  518. );
  519. return "user";
  520. }
  521. }
  522. if (!isset($_SESSION['ldelay'])) {
  523. $_SESSION['ldelay'] = "0";
  524. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  525. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  526. }
  527. elseif (!isset($_SESSION['mailcow_cc_username'])) {
  528. $_SESSION['ldelay'] = $_SESSION['ldelay']+0.5;
  529. $redis->publish("F2B_CHANNEL", "mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  530. error_log("mailcow UI: Invalid password for " . $user . " by " . $_SERVER['REMOTE_ADDR']);
  531. }
  532. $_SESSION['return'][] = array(
  533. 'type' => 'danger',
  534. 'log' => array(__FUNCTION__, $user, '*'),
  535. 'msg' => 'login_failed'
  536. );
  537. sleep($_SESSION['ldelay']);
  538. return false;
  539. }
  540. function formatBytes($size, $precision = 2) {
  541. if(!is_numeric($size)) {
  542. return "0";
  543. }
  544. $base = log($size, 1024);
  545. $suffixes = array(' Byte', ' KiB', ' MiB', ' GiB', ' TiB');
  546. if ($size == "0") {
  547. return "0";
  548. }
  549. return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
  550. }
  551. function update_sogo_static_view() {
  552. global $pdo;
  553. global $lang;
  554. $stmt = $pdo->query("SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES
  555. WHERE TABLE_NAME = 'sogo_view'");
  556. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  557. if ($num_results != 0) {
  558. $stmt = $pdo->query("REPLACE INTO _sogo_static_view (`c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings`)
  559. SELECT `c_uid`, `domain`, `c_name`, `c_password`, `c_cn`, `mail`, `aliases`, `ad_aliases`, `ext_acl`, `kind`, `multiple_bookings` from sogo_view");
  560. $stmt = $pdo->query("DELETE FROM _sogo_static_view WHERE `c_uid` NOT IN (SELECT `username` FROM `mailbox` WHERE `active` = '1');");
  561. }
  562. flush_memcached();
  563. }
  564. function edit_user_account($_data) {
  565. global $lang;
  566. global $pdo;
  567. $_data_log = $_data;
  568. !isset($_data_log['user_new_pass']) ?: $_data_log['user_new_pass'] = '*';
  569. !isset($_data_log['user_new_pass2']) ?: $_data_log['user_new_pass2'] = '*';
  570. !isset($_data_log['user_old_pass']) ?: $_data_log['user_old_pass'] = '*';
  571. $username = $_SESSION['mailcow_cc_username'];
  572. $role = $_SESSION['mailcow_cc_role'];
  573. $password_old = $_data['user_old_pass'];
  574. if (filter_var($username, FILTER_VALIDATE_EMAIL === false) || $role != 'user') {
  575. $_SESSION['return'][] = array(
  576. 'type' => 'danger',
  577. 'log' => array(__FUNCTION__, $_data_log),
  578. 'msg' => 'access_denied'
  579. );
  580. return false;
  581. }
  582. if (isset($_data['user_new_pass']) && isset($_data['user_new_pass2'])) {
  583. $password_new = $_data['user_new_pass'];
  584. $password_new2 = $_data['user_new_pass2'];
  585. }
  586. $stmt = $pdo->prepare("SELECT `password` FROM `mailbox`
  587. WHERE `kind` NOT REGEXP 'location|thing|group'
  588. AND `username` = :user");
  589. $stmt->execute(array(':user' => $username));
  590. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  591. if (!verify_hash($row['password'], $password_old)) {
  592. $_SESSION['return'][] = array(
  593. 'type' => 'danger',
  594. 'log' => array(__FUNCTION__, $_data_log),
  595. 'msg' => 'access_denied'
  596. );
  597. return false;
  598. }
  599. if (isset($password_new) && isset($password_new2)) {
  600. if (!empty($password_new2) && !empty($password_new)) {
  601. if ($password_new2 != $password_new) {
  602. $_SESSION['return'][] = array(
  603. 'type' => 'danger',
  604. 'log' => array(__FUNCTION__, $_data_log),
  605. 'msg' => 'password_mismatch'
  606. );
  607. return false;
  608. }
  609. if (!preg_match('/' . $GLOBALS['PASSWD_REGEP'] . '/', $password_new)) {
  610. $_SESSION['return'][] = array(
  611. 'type' => 'danger',
  612. 'log' => array(__FUNCTION__, $_data_log),
  613. 'msg' => 'password_complexity'
  614. );
  615. return false;
  616. }
  617. $password_hashed = hash_password($password_new);
  618. try {
  619. $stmt = $pdo->prepare("UPDATE `mailbox` SET `password` = :password_hashed, `attributes` = JSON_SET(`attributes`, '$.force_pw_update', '0') WHERE `username` = :username");
  620. $stmt->execute(array(
  621. ':password_hashed' => $password_hashed,
  622. ':username' => $username
  623. ));
  624. }
  625. catch (PDOException $e) {
  626. $_SESSION['return'][] = array(
  627. 'type' => 'danger',
  628. 'log' => array(__FUNCTION__, $_data_log),
  629. 'msg' => array('mysql_error', $e)
  630. );
  631. return false;
  632. }
  633. }
  634. }
  635. update_sogo_static_view();
  636. $_SESSION['return'][] = array(
  637. 'type' => 'success',
  638. 'log' => array(__FUNCTION__, $_data_log),
  639. 'msg' => array('mailbox_modified', htmlspecialchars($username))
  640. );
  641. }
  642. function user_get_alias_details($username) {
  643. global $lang;
  644. global $pdo;
  645. $data['direct_aliases'] = false;
  646. $data['shared_aliases'] = false;
  647. if ($_SESSION['mailcow_cc_role'] == "user") {
  648. $username = $_SESSION['mailcow_cc_username'];
  649. }
  650. if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
  651. return false;
  652. }
  653. $data['address'] = $username;
  654. $stmt = $pdo->prepare("SELECT `address` AS `shared_aliases`, `public_comment` FROM `alias`
  655. WHERE `goto` REGEXP :username_goto
  656. AND `address` NOT LIKE '@%'
  657. AND `goto` != :username_goto2
  658. AND `address` != :username_address");
  659. $stmt->execute(array(
  660. ':username_goto' => '(^|,)'.$username.'($|,)',
  661. ':username_goto2' => $username,
  662. ':username_address' => $username
  663. ));
  664. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  665. while ($row = array_shift($run)) {
  666. $data['shared_aliases'][$row['shared_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  667. //$data['shared_aliases'][] = $row['shared_aliases'];
  668. }
  669. $stmt = $pdo->prepare("SELECT `address` AS `direct_aliases`, `public_comment` FROM `alias`
  670. WHERE `goto` = :username_goto
  671. AND `address` NOT LIKE '@%'
  672. AND `address` != :username_address");
  673. $stmt->execute(
  674. array(
  675. ':username_goto' => $username,
  676. ':username_address' => $username
  677. ));
  678. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  679. while ($row = array_shift($run)) {
  680. $data['direct_aliases'][$row['direct_aliases']]['public_comment'] = htmlspecialchars($row['public_comment']);
  681. }
  682. $stmt = $pdo->prepare("SELECT CONCAT(local_part, '@', alias_domain) AS `ad_alias`, `alias_domain` FROM `mailbox`
  683. LEFT OUTER JOIN `alias_domain` on `target_domain` = `domain`
  684. WHERE `username` = :username ;");
  685. $stmt->execute(array(':username' => $username));
  686. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  687. while ($row = array_shift($run)) {
  688. if (empty($row['ad_alias'])) {
  689. continue;
  690. }
  691. $data['direct_aliases'][$row['ad_alias']]['public_comment'] = '↪ ' . $row['alias_domain'];
  692. }
  693. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`send_as` SEPARATOR ', '), '&#10008;') AS `send_as` FROM `sender_acl` WHERE `logged_in_as` = :username AND `send_as` NOT LIKE '@%';");
  694. $stmt->execute(array(':username' => $username));
  695. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  696. while ($row = array_shift($run)) {
  697. $data['aliases_also_send_as'] = $row['send_as'];
  698. }
  699. $stmt = $pdo->prepare("SELECT CONCAT_WS(', ', IFNULL(GROUP_CONCAT(DISTINCT `send_as` SEPARATOR ', '), '&#10008;'), GROUP_CONCAT(DISTINCT CONCAT('@',`alias_domain`) SEPARATOR ', ')) AS `send_as` FROM `sender_acl` LEFT JOIN `alias_domain` ON `alias_domain`.`target_domain` = TRIM(LEADING '@' FROM `send_as`) WHERE `logged_in_as` = :username AND `send_as` LIKE '@%';");
  700. $stmt->execute(array(':username' => $username));
  701. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  702. while ($row = array_shift($run)) {
  703. $data['aliases_send_as_all'] = $row['send_as'];
  704. }
  705. $stmt = $pdo->prepare("SELECT IFNULL(GROUP_CONCAT(`address` SEPARATOR ', '), '&#10008;') as `address` FROM `alias` WHERE `goto` REGEXP :username AND `address` LIKE '@%';");
  706. $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));
  707. $run = $stmt->fetchAll(PDO::FETCH_ASSOC);
  708. while ($row = array_shift($run)) {
  709. $data['is_catch_all'] = $row['address'];
  710. }
  711. return $data;
  712. }
  713. function is_valid_domain_name($domain_name) {
  714. if (empty($domain_name)) {
  715. return false;
  716. }
  717. $domain_name = idn_to_ascii($domain_name, 0, INTL_IDNA_VARIANT_UTS46);
  718. return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name)
  719. && preg_match("/^.{1,253}$/", $domain_name)
  720. && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
  721. }
  722. function set_tfa($_data) {
  723. global $lang;
  724. global $pdo;
  725. global $yubi;
  726. global $u2f;
  727. global $tfa;
  728. $_data_log = $_data;
  729. !isset($_data_log['confirm_password']) ?: $_data_log['confirm_password'] = '*';
  730. $username = $_SESSION['mailcow_cc_username'];
  731. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  732. $_SESSION['mailcow_cc_role'] != "admin") {
  733. $_SESSION['return'][] = array(
  734. 'type' => 'danger',
  735. 'log' => array(__FUNCTION__, $_data_log),
  736. 'msg' => 'access_denied'
  737. );
  738. return false;
  739. }
  740. $stmt = $pdo->prepare("SELECT `password` FROM `admin`
  741. WHERE `username` = :user");
  742. $stmt->execute(array(':user' => $username));
  743. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  744. if (!verify_hash($row['password'], $_data["confirm_password"])) {
  745. $_SESSION['return'][] = array(
  746. 'type' => 'danger',
  747. 'log' => array(__FUNCTION__, $_data_log),
  748. 'msg' => 'access_denied'
  749. );
  750. return false;
  751. }
  752. switch ($_data["tfa_method"]) {
  753. case "yubi_otp":
  754. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  755. $yubico_id = $_data['yubico_id'];
  756. $yubico_key = $_data['yubico_key'];
  757. $yubi = new Auth_Yubico($yubico_id, $yubico_key);
  758. if (!$yubi) {
  759. $_SESSION['return'][] = array(
  760. 'type' => 'danger',
  761. 'log' => array(__FUNCTION__, $_data_log),
  762. 'msg' => 'access_denied'
  763. );
  764. return false;
  765. }
  766. if (!ctype_alnum($_data["otp_token"]) || strlen($_data["otp_token"]) != 44) {
  767. $_SESSION['return'][] = array(
  768. 'type' => 'danger',
  769. 'log' => array(__FUNCTION__, $_data_log),
  770. 'msg' => 'tfa_token_invalid'
  771. );
  772. return false;
  773. }
  774. $yauth = $yubi->verify($_data["otp_token"]);
  775. if (PEAR::isError($yauth)) {
  776. $_SESSION['return'][] = array(
  777. 'type' => 'danger',
  778. 'log' => array(__FUNCTION__, $_data_log),
  779. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  780. );
  781. return false;
  782. }
  783. try {
  784. // We could also do a modhex translation here
  785. $yubico_modhex_id = substr($_data["otp_token"], 0, 12);
  786. $stmt = $pdo->prepare("DELETE FROM `tfa`
  787. WHERE `username` = :username
  788. AND (`authmech` != 'yubi_otp')
  789. OR (`authmech` = 'yubi_otp' AND `secret` LIKE :modhex)");
  790. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  791. $stmt = $pdo->prepare("INSERT INTO `tfa` (`key_id`, `username`, `authmech`, `active`, `secret`) VALUES
  792. (:key_id, :username, 'yubi_otp', '1', :secret)");
  793. $stmt->execute(array(':key_id' => $key_id, ':username' => $username, ':secret' => $yubico_id . ':' . $yubico_key . ':' . $yubico_modhex_id));
  794. }
  795. catch (PDOException $e) {
  796. $_SESSION['return'][] = array(
  797. 'type' => 'danger',
  798. 'log' => array(__FUNCTION__, $_data_log),
  799. 'msg' => array('mysql_error', $e)
  800. );
  801. return false;
  802. }
  803. $_SESSION['return'][] = array(
  804. 'type' => 'success',
  805. 'log' => array(__FUNCTION__, $_data_log),
  806. 'msg' => array('object_modified', htmlspecialchars($username))
  807. );
  808. break;
  809. case "u2f":
  810. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  811. try {
  812. $reg = $u2f->doRegister(json_decode($_SESSION['regReq']), json_decode($_data['token']));
  813. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `authmech` != 'u2f'");
  814. $stmt->execute(array(':username' => $username));
  815. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `keyHandle`, `publicKey`, `certificate`, `counter`, `active`) VALUES (?, ?, 'u2f', ?, ?, ?, ?, '1')");
  816. $stmt->execute(array($username, $key_id, $reg->keyHandle, $reg->publicKey, $reg->certificate, $reg->counter));
  817. $_SESSION['return'][] = array(
  818. 'type' => 'success',
  819. 'log' => array(__FUNCTION__, $_data_log),
  820. 'msg' => array('object_modified', $username)
  821. );
  822. $_SESSION['regReq'] = null;
  823. }
  824. catch (Exception $e) {
  825. $_SESSION['return'][] = array(
  826. 'type' => 'danger',
  827. 'log' => array(__FUNCTION__, $_data_log),
  828. 'msg' => array('u2f_verification_failed', $e->getMessage())
  829. );
  830. $_SESSION['regReq'] = null;
  831. return false;
  832. }
  833. break;
  834. case "totp":
  835. $key_id = (!isset($_data["key_id"])) ? 'unidentified' : $_data["key_id"];
  836. if ($tfa->verifyCode($_POST['totp_secret'], $_POST['totp_confirm_token']) === true) {
  837. try {
  838. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  839. $stmt->execute(array(':username' => $username));
  840. $stmt = $pdo->prepare("INSERT INTO `tfa` (`username`, `key_id`, `authmech`, `secret`, `active`) VALUES (?, ?, 'totp', ?, '1')");
  841. $stmt->execute(array($username, $key_id, $_POST['totp_secret']));
  842. }
  843. catch (PDOException $e) {
  844. $_SESSION['return'][] = array(
  845. 'type' => 'danger',
  846. 'log' => array(__FUNCTION__, $_data_log),
  847. 'msg' => array('mysql_error', $e)
  848. );
  849. return false;
  850. }
  851. $_SESSION['return'][] = array(
  852. 'type' => 'success',
  853. 'log' => array(__FUNCTION__, $_data_log),
  854. 'msg' => array('object_modified', $username)
  855. );
  856. }
  857. else {
  858. $_SESSION['return'][] = array(
  859. 'type' => 'danger',
  860. 'log' => array(__FUNCTION__, $_data_log),
  861. 'msg' => 'totp_verification_failed'
  862. );
  863. }
  864. break;
  865. case "none":
  866. try {
  867. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username");
  868. $stmt->execute(array(':username' => $username));
  869. }
  870. catch (PDOException $e) {
  871. $_SESSION['return'][] = array(
  872. 'type' => 'danger',
  873. 'log' => array(__FUNCTION__, $_data_log),
  874. 'msg' => array('mysql_error', $e)
  875. );
  876. return false;
  877. }
  878. $_SESSION['return'][] = array(
  879. 'type' => 'success',
  880. 'log' => array(__FUNCTION__, $_data_log),
  881. 'msg' => array('object_modified', htmlspecialchars($username))
  882. );
  883. break;
  884. }
  885. }
  886. function unset_tfa_key($_data) {
  887. // Can only unset own keys
  888. // Needs at least one key left
  889. global $pdo;
  890. global $lang;
  891. $_data_log = $_data;
  892. $id = intval($_data['unset_tfa_key']);
  893. $username = $_SESSION['mailcow_cc_username'];
  894. if ($_SESSION['mailcow_cc_role'] != "domainadmin" &&
  895. $_SESSION['mailcow_cc_role'] != "admin") {
  896. $_SESSION['return'][] = array(
  897. 'type' => 'danger',
  898. 'log' => array(__FUNCTION__, $_data_log),
  899. 'msg' => 'access_denied'
  900. );
  901. return false;
  902. }
  903. try {
  904. if (!is_numeric($id)) {
  905. $_SESSION['return'][] = array(
  906. 'type' => 'danger',
  907. 'log' => array(__FUNCTION__, $_data_log),
  908. 'msg' => 'access_denied'
  909. );
  910. return false;
  911. }
  912. $stmt = $pdo->prepare("SELECT COUNT(*) AS `keys` FROM `tfa`
  913. WHERE `username` = :username AND `active` = '1'");
  914. $stmt->execute(array(':username' => $username));
  915. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  916. if ($row['keys'] == "1") {
  917. $_SESSION['return'][] = array(
  918. 'type' => 'danger',
  919. 'log' => array(__FUNCTION__, $_data_log),
  920. 'msg' => 'last_key'
  921. );
  922. return false;
  923. }
  924. $stmt = $pdo->prepare("DELETE FROM `tfa` WHERE `username` = :username AND `id` = :id");
  925. $stmt->execute(array(':username' => $username, ':id' => $id));
  926. $_SESSION['return'][] = array(
  927. 'type' => 'success',
  928. 'log' => array(__FUNCTION__, $_data_log),
  929. 'msg' => array('object_modified', $username)
  930. );
  931. }
  932. catch (PDOException $e) {
  933. $_SESSION['return'][] = array(
  934. 'type' => 'danger',
  935. 'log' => array(__FUNCTION__, $_data_log),
  936. 'msg' => array('mysql_error', $e)
  937. );
  938. return false;
  939. }
  940. }
  941. function get_tfa($username = null) {
  942. global $pdo;
  943. if (isset($_SESSION['mailcow_cc_username'])) {
  944. $username = $_SESSION['mailcow_cc_username'];
  945. }
  946. elseif (empty($username)) {
  947. return false;
  948. }
  949. $stmt = $pdo->prepare("SELECT * FROM `tfa`
  950. WHERE `username` = :username AND `active` = '1'");
  951. $stmt->execute(array(':username' => $username));
  952. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  953. switch ($row["authmech"]) {
  954. case "yubi_otp":
  955. $data['name'] = "yubi_otp";
  956. $data['pretty'] = "Yubico OTP";
  957. $stmt = $pdo->prepare("SELECT `id`, `key_id`, RIGHT(`secret`, 12) AS 'modhex' FROM `tfa` WHERE `authmech` = 'yubi_otp' AND `username` = :username");
  958. $stmt->execute(array(
  959. ':username' => $username,
  960. ));
  961. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  962. while($row = array_shift($rows)) {
  963. $data['additional'][] = $row;
  964. }
  965. return $data;
  966. break;
  967. case "u2f":
  968. $data['name'] = "u2f";
  969. $data['pretty'] = "Fido U2F";
  970. $stmt = $pdo->prepare("SELECT `id`, `key_id` FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = :username");
  971. $stmt->execute(array(
  972. ':username' => $username,
  973. ));
  974. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  975. while($row = array_shift($rows)) {
  976. $data['additional'][] = $row;
  977. }
  978. return $data;
  979. break;
  980. case "hotp":
  981. $data['name'] = "hotp";
  982. $data['pretty'] = "HMAC-based OTP";
  983. return $data;
  984. break;
  985. case "totp":
  986. $data['name'] = "totp";
  987. $data['pretty'] = "Time-based OTP";
  988. $stmt = $pdo->prepare("SELECT `id`, `key_id`, `secret` FROM `tfa` WHERE `authmech` = 'totp' AND `username` = :username");
  989. $stmt->execute(array(
  990. ':username' => $username,
  991. ));
  992. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  993. while($row = array_shift($rows)) {
  994. $data['additional'][] = $row;
  995. }
  996. return $data;
  997. break;
  998. default:
  999. $data['name'] = 'none';
  1000. $data['pretty'] = "-";
  1001. return $data;
  1002. break;
  1003. }
  1004. }
  1005. function verify_tfa_login($username, $token) {
  1006. global $pdo;
  1007. global $lang;
  1008. global $yubi;
  1009. global $u2f;
  1010. global $tfa;
  1011. $stmt = $pdo->prepare("SELECT `authmech` FROM `tfa`
  1012. WHERE `username` = :username AND `active` = '1'");
  1013. $stmt->execute(array(':username' => $username));
  1014. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1015. switch ($row["authmech"]) {
  1016. case "yubi_otp":
  1017. if (!ctype_alnum($token) || strlen($token) != 44) {
  1018. $_SESSION['return'][] = array(
  1019. 'type' => 'danger',
  1020. 'log' => array(__FUNCTION__, $username, '*'),
  1021. 'msg' => array('yotp_verification_failed', 'token length error')
  1022. );
  1023. return false;
  1024. }
  1025. $yubico_modhex_id = substr($token, 0, 12);
  1026. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1027. WHERE `username` = :username
  1028. AND `authmech` = 'yubi_otp'
  1029. AND `active`='1'
  1030. AND `secret` LIKE :modhex");
  1031. $stmt->execute(array(':username' => $username, ':modhex' => '%' . $yubico_modhex_id));
  1032. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1033. $yubico_auth = explode(':', $row['secret']);
  1034. $yubi = new Auth_Yubico($yubico_auth[0], $yubico_auth[1]);
  1035. $yauth = $yubi->verify($token);
  1036. if (PEAR::isError($yauth)) {
  1037. $_SESSION['return'][] = array(
  1038. 'type' => 'danger',
  1039. 'log' => array(__FUNCTION__, $username, '*'),
  1040. 'msg' => array('yotp_verification_failed', $yauth->getMessage())
  1041. );
  1042. return false;
  1043. }
  1044. else {
  1045. $_SESSION['tfa_id'] = $row['id'];
  1046. $_SESSION['return'][] = array(
  1047. 'type' => 'success',
  1048. 'log' => array(__FUNCTION__, $username, '*'),
  1049. 'msg' => 'verified_yotp_login'
  1050. );
  1051. return true;
  1052. }
  1053. $_SESSION['return'][] = array(
  1054. 'type' => 'danger',
  1055. 'log' => array(__FUNCTION__, $username, '*'),
  1056. 'msg' => array('yotp_verification_failed', 'unknown')
  1057. );
  1058. return false;
  1059. break;
  1060. case "u2f":
  1061. try {
  1062. $reg = $u2f->doAuthenticate(json_decode($_SESSION['authReq']), get_u2f_registrations($username), json_decode($token));
  1063. $stmt = $pdo->prepare("SELECT `id` FROM `tfa` WHERE `keyHandle` = ?");
  1064. $stmt->execute(array($reg->keyHandle));
  1065. $row_key_id = $stmt->fetch(PDO::FETCH_ASSOC);
  1066. $_SESSION['tfa_id'] = $row_key_id['id'];
  1067. $_SESSION['authReq'] = null;
  1068. $_SESSION['return'][] = array(
  1069. 'type' => 'success',
  1070. 'log' => array(__FUNCTION__, $username, '*'),
  1071. 'msg' => 'verified_u2f_login'
  1072. );
  1073. return true;
  1074. }
  1075. catch (Exception $e) {
  1076. $_SESSION['return'][] = array(
  1077. 'type' => 'danger',
  1078. 'log' => array(__FUNCTION__, $username, '*'),
  1079. 'msg' => array('u2f_verification_failed', $e->getMessage())
  1080. );
  1081. $_SESSION['regReq'] = null;
  1082. return false;
  1083. }
  1084. $_SESSION['return'][] = array(
  1085. 'type' => 'danger',
  1086. 'log' => array(__FUNCTION__, $username, '*'),
  1087. 'msg' => array('u2f_verification_failed', 'unknown')
  1088. );
  1089. return false;
  1090. break;
  1091. case "hotp":
  1092. return false;
  1093. break;
  1094. case "totp":
  1095. try {
  1096. $stmt = $pdo->prepare("SELECT `id`, `secret` FROM `tfa`
  1097. WHERE `username` = :username
  1098. AND `authmech` = 'totp'
  1099. AND `active`='1'");
  1100. $stmt->execute(array(':username' => $username));
  1101. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  1102. if ($tfa->verifyCode($row['secret'], $_POST['token']) === true) {
  1103. $_SESSION['tfa_id'] = $row['id'];
  1104. $_SESSION['return'][] = array(
  1105. 'type' => 'success',
  1106. 'log' => array(__FUNCTION__, $username, '*'),
  1107. 'msg' => 'verified_totp_login'
  1108. );
  1109. return true;
  1110. }
  1111. $_SESSION['return'][] = array(
  1112. 'type' => 'danger',
  1113. 'log' => array(__FUNCTION__, $username, '*'),
  1114. 'msg' => 'totp_verification_failed'
  1115. );
  1116. return false;
  1117. }
  1118. catch (PDOException $e) {
  1119. $_SESSION['return'][] = array(
  1120. 'type' => 'danger',
  1121. 'log' => array(__FUNCTION__, $username, '*'),
  1122. 'msg' => array('mysql_error', $e)
  1123. );
  1124. return false;
  1125. }
  1126. break;
  1127. default:
  1128. $_SESSION['return'][] = array(
  1129. 'type' => 'danger',
  1130. 'log' => array(__FUNCTION__, $username, '*'),
  1131. 'msg' => 'unknown_tfa_method'
  1132. );
  1133. return false;
  1134. break;
  1135. }
  1136. return false;
  1137. }
  1138. function admin_api($action, $data = null) {
  1139. global $pdo;
  1140. global $lang;
  1141. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1142. $_SESSION['return'][] = array(
  1143. 'type' => 'danger',
  1144. 'log' => array(__FUNCTION__),
  1145. 'msg' => 'access_denied'
  1146. );
  1147. return false;
  1148. }
  1149. switch ($action) {
  1150. case "edit":
  1151. $regen_key = $data['admin_api_regen_key'];
  1152. $active = (isset($data['active'])) ? 1 : 0;
  1153. $skip_ip_check = (isset($data['skip_ip_check'])) ? 1 : 0;
  1154. $allow_from = array_map('trim', preg_split( "/( |,|;|\n)/", $data['allow_from']));
  1155. foreach ($allow_from as $key => $val) {
  1156. if (empty($val)) {
  1157. continue;
  1158. }
  1159. if (!filter_var($val, FILTER_VALIDATE_IP)) {
  1160. $_SESSION['return'][] = array(
  1161. 'type' => 'warning',
  1162. 'log' => array(__FUNCTION__, $data),
  1163. 'msg' => array('ip_invalid', htmlspecialchars($allow_from[$key]))
  1164. );
  1165. unset($allow_from[$key]);
  1166. continue;
  1167. }
  1168. }
  1169. $allow_from = implode(',', array_unique(array_filter($allow_from)));
  1170. if (empty($allow_from) && $skip_ip_check == 0) {
  1171. $_SESSION['return'][] = array(
  1172. 'type' => 'danger',
  1173. 'log' => array(__FUNCTION__, $data),
  1174. 'msg' => 'ip_list_empty'
  1175. );
  1176. return false;
  1177. }
  1178. $api_key = implode('-', array(
  1179. strtoupper(bin2hex(random_bytes(3))),
  1180. strtoupper(bin2hex(random_bytes(3))),
  1181. strtoupper(bin2hex(random_bytes(3))),
  1182. strtoupper(bin2hex(random_bytes(3))),
  1183. strtoupper(bin2hex(random_bytes(3)))
  1184. ));
  1185. $stmt = $pdo->query("SELECT `api_key` FROM `api`");
  1186. $num_results = count($stmt->fetchAll(PDO::FETCH_ASSOC));
  1187. if (empty($num_results)) {
  1188. $stmt = $pdo->prepare("INSERT INTO `api` (`api_key`, `skip_ip_check`, `active`, `allow_from`)
  1189. VALUES (:api_key, :skip_ip_check, :active, :allow_from);");
  1190. $stmt->execute(array(
  1191. ':api_key' => $api_key,
  1192. ':skip_ip_check' => $skip_ip_check,
  1193. ':active' => $active,
  1194. ':allow_from' => $allow_from
  1195. ));
  1196. }
  1197. else {
  1198. if ($skip_ip_check == 0) {
  1199. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check, `active` = :active, `allow_from` = :allow_from ;");
  1200. $stmt->execute(array(
  1201. ':active' => $active,
  1202. ':skip_ip_check' => $skip_ip_check,
  1203. ':allow_from' => $allow_from
  1204. ));
  1205. }
  1206. else {
  1207. $stmt = $pdo->prepare("UPDATE `api` SET `skip_ip_check` = :skip_ip_check, `active` = :active ;");
  1208. $stmt->execute(array(
  1209. ':active' => $active,
  1210. ':skip_ip_check' => $skip_ip_check
  1211. ));
  1212. }
  1213. }
  1214. break;
  1215. case "regen_key":
  1216. $api_key = implode('-', array(
  1217. strtoupper(bin2hex(random_bytes(3))),
  1218. strtoupper(bin2hex(random_bytes(3))),
  1219. strtoupper(bin2hex(random_bytes(3))),
  1220. strtoupper(bin2hex(random_bytes(3))),
  1221. strtoupper(bin2hex(random_bytes(3)))
  1222. ));
  1223. $stmt = $pdo->prepare("UPDATE `api` SET `api_key` = :api_key");
  1224. $stmt->execute(array(
  1225. ':api_key' => $api_key
  1226. ));
  1227. break;
  1228. case "get":
  1229. $stmt = $pdo->query("SELECT * FROM `api`");
  1230. $apidata = $stmt->fetch(PDO::FETCH_ASSOC);
  1231. return $apidata;
  1232. break;
  1233. }
  1234. $_SESSION['return'][] = array(
  1235. 'type' => 'success',
  1236. 'log' => array(__FUNCTION__, $data),
  1237. 'msg' => 'admin_api_modified'
  1238. );
  1239. }
  1240. function license($action, $data = null) {
  1241. global $pdo;
  1242. global $redis;
  1243. global $lang;
  1244. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1245. $_SESSION['return'][] = array(
  1246. 'type' => 'danger',
  1247. 'log' => array(__FUNCTION__),
  1248. 'msg' => 'access_denied'
  1249. );
  1250. return false;
  1251. }
  1252. switch ($action) {
  1253. case "verify":
  1254. // Keep result until revalidate button is pressed or session expired
  1255. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1256. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1257. $post = array('guid' => $versions['version']);
  1258. $curl = curl_init('https://verify.mailcow.email');
  1259. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1260. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
  1261. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  1262. $response = curl_exec($curl);
  1263. curl_close($curl);
  1264. $json_return = json_decode($response, true);
  1265. if ($response && $json_return) {
  1266. if ($json_return['response'] === "ok") {
  1267. $_SESSION['gal']['valid'] = "true";
  1268. $_SESSION['gal']['c'] = $json_return['c'];
  1269. $_SESSION['gal']['s'] = $json_return['s'];
  1270. if ($json_return['m'] == 'NoMoore') {
  1271. $_SESSION['gal']['m'] = '🐄';
  1272. }
  1273. else {
  1274. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1275. }
  1276. }
  1277. elseif ($json_return['response'] === "invalid") {
  1278. $_SESSION['gal']['valid'] = "false";
  1279. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1280. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1281. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1282. }
  1283. }
  1284. else {
  1285. $_SESSION['gal']['valid'] = "false";
  1286. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1287. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1288. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1289. }
  1290. try {
  1291. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1292. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1293. }
  1294. catch (RedisException $e) {
  1295. $_SESSION['return'][] = array(
  1296. 'type' => 'danger',
  1297. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1298. 'msg' => array('redis_error', $e)
  1299. );
  1300. return false;
  1301. }
  1302. return $_SESSION['gal']['valid'];
  1303. break;
  1304. case "guid":
  1305. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1306. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1307. return $versions['version'];
  1308. break;
  1309. }
  1310. }
  1311. function rspamd_ui($action, $data = null) {
  1312. global $lang;
  1313. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1314. $_SESSION['return'][] = array(
  1315. 'type' => 'danger',
  1316. 'log' => array(__FUNCTION__),
  1317. 'msg' => 'access_denied'
  1318. );
  1319. return false;
  1320. }
  1321. switch ($action) {
  1322. case "edit":
  1323. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1324. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1325. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1326. $_SESSION['return'][] = array(
  1327. 'type' => 'danger',
  1328. 'log' => array(__FUNCTION__, '*', '*'),
  1329. 'msg' => 'password_empty'
  1330. );
  1331. return false;
  1332. }
  1333. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1334. $_SESSION['return'][] = array(
  1335. 'type' => 'danger',
  1336. 'log' => array(__FUNCTION__, '*', '*'),
  1337. 'msg' => 'password_mismatch'
  1338. );
  1339. return false;
  1340. }
  1341. if (strlen($rspamd_ui_pass) < 6) {
  1342. $_SESSION['return'][] = array(
  1343. 'type' => 'danger',
  1344. 'log' => array(__FUNCTION__, '*', '*'),
  1345. 'msg' => 'rspamd_ui_pw_length'
  1346. );
  1347. return false;
  1348. }
  1349. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1350. if ($docker_return_array = json_decode($docker_return, true)) {
  1351. if ($docker_return_array['type'] == 'success') {
  1352. $_SESSION['return'][] = array(
  1353. 'type' => 'success',
  1354. 'log' => array(__FUNCTION__, '*', '*'),
  1355. 'msg' => 'rspamd_ui_pw_set'
  1356. );
  1357. return true;
  1358. }
  1359. else {
  1360. $_SESSION['return'][] = array(
  1361. 'type' => $docker_return_array['type'],
  1362. 'log' => array(__FUNCTION__, '*', '*'),
  1363. 'msg' => $docker_return_array['msg']
  1364. );
  1365. return false;
  1366. }
  1367. }
  1368. else {
  1369. $_SESSION['return'][] = array(
  1370. 'type' => 'danger',
  1371. 'log' => array(__FUNCTION__, '*', '*'),
  1372. 'msg' => 'unknown'
  1373. );
  1374. return false;
  1375. }
  1376. break;
  1377. }
  1378. }
  1379. function get_u2f_registrations($username) {
  1380. global $pdo;
  1381. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1382. $sel->execute(array($username));
  1383. return $sel->fetchAll(PDO::FETCH_OBJ);
  1384. }
  1385. function get_logs($application, $lines = false) {
  1386. if ($lines === false) {
  1387. $lines = $GLOBALS['LOG_LINES'] - 1;
  1388. }
  1389. elseif(is_numeric($lines) && $lines >= 1) {
  1390. $lines = abs(intval($lines) - 1);
  1391. }
  1392. else {
  1393. list ($from, $to) = explode('-', $lines);
  1394. $from = intval($from);
  1395. $to = intval($to);
  1396. if ($from < 1 || $to < $from) { return false; }
  1397. }
  1398. global $lang;
  1399. global $redis;
  1400. global $pdo;
  1401. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1402. return false;
  1403. }
  1404. // SQL
  1405. if ($application == "mailcow-ui") {
  1406. if (isset($from) && isset($to)) {
  1407. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1408. $stmt->execute(array(
  1409. ':from' => $from - 1,
  1410. ':to' => $to
  1411. ));
  1412. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1413. }
  1414. else {
  1415. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1416. $stmt->execute(array(
  1417. ':lines' => $lines + 1,
  1418. ));
  1419. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1420. }
  1421. if (is_array($data)) {
  1422. return $data;
  1423. }
  1424. }
  1425. // Redis
  1426. if ($application == "dovecot-mailcow") {
  1427. if (isset($from) && isset($to)) {
  1428. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1429. }
  1430. else {
  1431. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1432. }
  1433. if ($data) {
  1434. foreach ($data as $json_line) {
  1435. $data_array[] = json_decode($json_line, true);
  1436. }
  1437. return $data_array;
  1438. }
  1439. }
  1440. if ($application == "postfix-mailcow") {
  1441. if (isset($from) && isset($to)) {
  1442. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1443. }
  1444. else {
  1445. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1446. }
  1447. if ($data) {
  1448. foreach ($data as $json_line) {
  1449. $data_array[] = json_decode($json_line, true);
  1450. }
  1451. return $data_array;
  1452. }
  1453. }
  1454. if ($application == "sogo-mailcow") {
  1455. if (isset($from) && isset($to)) {
  1456. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1457. }
  1458. else {
  1459. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1460. }
  1461. if ($data) {
  1462. foreach ($data as $json_line) {
  1463. $data_array[] = json_decode($json_line, true);
  1464. }
  1465. return $data_array;
  1466. }
  1467. }
  1468. if ($application == "watchdog-mailcow") {
  1469. if (isset($from) && isset($to)) {
  1470. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1471. }
  1472. else {
  1473. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1474. }
  1475. if ($data) {
  1476. foreach ($data as $json_line) {
  1477. $data_array[] = json_decode($json_line, true);
  1478. }
  1479. return $data_array;
  1480. }
  1481. }
  1482. if ($application == "acme-mailcow") {
  1483. if (isset($from) && isset($to)) {
  1484. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1485. }
  1486. else {
  1487. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1488. }
  1489. if ($data) {
  1490. foreach ($data as $json_line) {
  1491. $data_array[] = json_decode($json_line, true);
  1492. }
  1493. return $data_array;
  1494. }
  1495. }
  1496. if ($application == "ratelimited") {
  1497. if (isset($from) && isset($to)) {
  1498. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1499. }
  1500. else {
  1501. $data = $redis->lRange('RL_LOG', 0, $lines);
  1502. }
  1503. if ($data) {
  1504. foreach ($data as $json_line) {
  1505. $data_array[] = json_decode($json_line, true);
  1506. }
  1507. return $data_array;
  1508. }
  1509. }
  1510. if ($application == "api-mailcow") {
  1511. if (isset($from) && isset($to)) {
  1512. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1513. }
  1514. else {
  1515. $data = $redis->lRange('API_LOG', 0, $lines);
  1516. }
  1517. if ($data) {
  1518. foreach ($data as $json_line) {
  1519. $data_array[] = json_decode($json_line, true);
  1520. }
  1521. return $data_array;
  1522. }
  1523. }
  1524. if ($application == "netfilter-mailcow") {
  1525. if (isset($from) && isset($to)) {
  1526. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1527. }
  1528. else {
  1529. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1530. }
  1531. if ($data) {
  1532. foreach ($data as $json_line) {
  1533. $data_array[] = json_decode($json_line, true);
  1534. }
  1535. return $data_array;
  1536. }
  1537. }
  1538. if ($application == "autodiscover-mailcow") {
  1539. if (isset($from) && isset($to)) {
  1540. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1541. }
  1542. else {
  1543. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1544. }
  1545. if ($data) {
  1546. foreach ($data as $json_line) {
  1547. $data_array[] = json_decode($json_line, true);
  1548. }
  1549. return $data_array;
  1550. }
  1551. }
  1552. if ($application == "rspamd-history") {
  1553. $curl = curl_init();
  1554. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1555. if (!is_numeric($lines)) {
  1556. list ($from, $to) = explode('-', $lines);
  1557. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1558. }
  1559. else {
  1560. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1561. }
  1562. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1563. $history = curl_exec($curl);
  1564. if (!curl_errno($curl)) {
  1565. $data_array = json_decode($history, true);
  1566. curl_close($curl);
  1567. return $data_array['rows'];
  1568. }
  1569. curl_close($curl);
  1570. return false;
  1571. }
  1572. return false;
  1573. }
  1574. function getGUID() {
  1575. if (function_exists('com_create_guid')) {
  1576. return com_create_guid();
  1577. }
  1578. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1579. $charid = strtoupper(md5(uniqid(rand(), true)));
  1580. $hyphen = chr(45);// "-"
  1581. return substr($charid, 0, 8).$hyphen
  1582. .substr($charid, 8, 4).$hyphen
  1583. .substr($charid,12, 4).$hyphen
  1584. .substr($charid,16, 4).$hyphen
  1585. .substr($charid,20,12);
  1586. }
  1587. function solr_status() {
  1588. $curl = curl_init();
  1589. $endpoint = 'http://solr:8983/solr/admin/cores';
  1590. $params = array(
  1591. 'action' => 'STATUS',
  1592. 'core' => 'dovecot-fts',
  1593. 'indexInfo' => 'true'
  1594. );
  1595. $url = $endpoint . '?' . http_build_query($params);
  1596. curl_setopt($curl, CURLOPT_URL, $url);
  1597. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1598. curl_setopt($curl, CURLOPT_POST, 0);
  1599. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1600. $response_core = curl_exec($curl);
  1601. if ($response_core === false) {
  1602. $err = curl_error($curl);
  1603. curl_close($curl);
  1604. return false;
  1605. }
  1606. else {
  1607. curl_close($curl);
  1608. $curl = curl_init();
  1609. $status_core = json_decode($response_core, true);
  1610. $url = 'http://solr:8983/solr/admin/info/system';
  1611. curl_setopt($curl, CURLOPT_URL, $url);
  1612. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1613. curl_setopt($curl, CURLOPT_POST, 0);
  1614. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1615. $response_sysinfo = curl_exec($curl);
  1616. if ($response_sysinfo === false) {
  1617. $err = curl_error($curl);
  1618. curl_close($curl);
  1619. return false;
  1620. }
  1621. else {
  1622. curl_close($curl);
  1623. $status_sysinfo = json_decode($response_sysinfo, true);
  1624. $status = array_merge($status_core, $status_sysinfo);
  1625. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  1626. }
  1627. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  1628. }
  1629. return false;
  1630. }
  1631. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  1632. $now = time();
  1633. foreach (glob($folder) as $filename) {
  1634. if(strpos($filename, $ignore) !== false) {
  1635. continue;
  1636. }
  1637. if (is_file($filename)) {
  1638. if ($now - filemtime($filename) >= 60 * 60) {
  1639. unlink($filename);
  1640. }
  1641. }
  1642. }
  1643. }
  1644. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  1645. $now = time();
  1646. foreach (glob($folder) as $filename) {
  1647. if(strpos($filename, $ignore) !== false) {
  1648. continue;
  1649. }
  1650. if (is_file($filename)) {
  1651. if ($now - filemtime($filename) >= 60 * 60) {
  1652. unlink($filename);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. ?>