functions.inc.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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. $_SESSION['gal']['m'] = str_repeat('🐄', substr_count($json_return['m'], 'o'));
  1271. }
  1272. elseif ($json_return['response'] === "invalid") {
  1273. $_SESSION['gal']['valid'] = "false";
  1274. $_SESSION['gal']['c'] = $lang['mailbox']['no'];
  1275. $_SESSION['gal']['s'] = $lang['mailbox']['no'];
  1276. $_SESSION['gal']['m'] = $lang['mailbox']['no'];
  1277. }
  1278. }
  1279. else {
  1280. $_SESSION['gal']['valid'] = "false";
  1281. $_SESSION['gal']['c'] = $lang['danger']['temp_error'];
  1282. $_SESSION['gal']['s'] = $lang['danger']['temp_error'];
  1283. $_SESSION['gal']['m'] = $lang['danger']['temp_error'];
  1284. }
  1285. try {
  1286. // json_encode needs "true"/"false" instead of true/false, to not encode it to 0 or 1
  1287. $redis->Set('LICENSE_STATUS_CACHE', json_encode($_SESSION['gal']));
  1288. }
  1289. catch (RedisException $e) {
  1290. $_SESSION['return'][] = array(
  1291. 'type' => 'danger',
  1292. 'log' => array(__FUNCTION__, $_action, $_data_log),
  1293. 'msg' => array('redis_error', $e)
  1294. );
  1295. return false;
  1296. }
  1297. return $_SESSION['gal']['valid'];
  1298. break;
  1299. case "guid":
  1300. $stmt = $pdo->query("SELECT `version` FROM `versions` WHERE `application` = 'GUID'");
  1301. $versions = $stmt->fetch(PDO::FETCH_ASSOC);
  1302. return $versions['version'];
  1303. break;
  1304. }
  1305. }
  1306. function rspamd_ui($action, $data = null) {
  1307. global $lang;
  1308. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1309. $_SESSION['return'][] = array(
  1310. 'type' => 'danger',
  1311. 'log' => array(__FUNCTION__),
  1312. 'msg' => 'access_denied'
  1313. );
  1314. return false;
  1315. }
  1316. switch ($action) {
  1317. case "edit":
  1318. $rspamd_ui_pass = $data['rspamd_ui_pass'];
  1319. $rspamd_ui_pass2 = $data['rspamd_ui_pass2'];
  1320. if (empty($rspamd_ui_pass) || empty($rspamd_ui_pass2)) {
  1321. $_SESSION['return'][] = array(
  1322. 'type' => 'danger',
  1323. 'log' => array(__FUNCTION__, '*', '*'),
  1324. 'msg' => 'password_empty'
  1325. );
  1326. return false;
  1327. }
  1328. if ($rspamd_ui_pass != $rspamd_ui_pass2) {
  1329. $_SESSION['return'][] = array(
  1330. 'type' => 'danger',
  1331. 'log' => array(__FUNCTION__, '*', '*'),
  1332. 'msg' => 'password_mismatch'
  1333. );
  1334. return false;
  1335. }
  1336. if (strlen($rspamd_ui_pass) < 6) {
  1337. $_SESSION['return'][] = array(
  1338. 'type' => 'danger',
  1339. 'log' => array(__FUNCTION__, '*', '*'),
  1340. 'msg' => 'rspamd_ui_pw_length'
  1341. );
  1342. return false;
  1343. }
  1344. $docker_return = docker('post', 'rspamd-mailcow', 'exec', array('cmd' => 'rspamd', 'task' => 'worker_password', 'raw' => $rspamd_ui_pass), array('Content-Type: application/json'));
  1345. if ($docker_return_array = json_decode($docker_return, true)) {
  1346. if ($docker_return_array['type'] == 'success') {
  1347. $_SESSION['return'][] = array(
  1348. 'type' => 'success',
  1349. 'log' => array(__FUNCTION__, '*', '*'),
  1350. 'msg' => 'rspamd_ui_pw_set'
  1351. );
  1352. return true;
  1353. }
  1354. else {
  1355. $_SESSION['return'][] = array(
  1356. 'type' => $docker_return_array['type'],
  1357. 'log' => array(__FUNCTION__, '*', '*'),
  1358. 'msg' => $docker_return_array['msg']
  1359. );
  1360. return false;
  1361. }
  1362. }
  1363. else {
  1364. $_SESSION['return'][] = array(
  1365. 'type' => 'danger',
  1366. 'log' => array(__FUNCTION__, '*', '*'),
  1367. 'msg' => 'unknown'
  1368. );
  1369. return false;
  1370. }
  1371. break;
  1372. }
  1373. }
  1374. function get_u2f_registrations($username) {
  1375. global $pdo;
  1376. $sel = $pdo->prepare("SELECT * FROM `tfa` WHERE `authmech` = 'u2f' AND `username` = ? AND `active` = '1'");
  1377. $sel->execute(array($username));
  1378. return $sel->fetchAll(PDO::FETCH_OBJ);
  1379. }
  1380. function get_logs($application, $lines = false) {
  1381. if ($lines === false) {
  1382. $lines = $GLOBALS['LOG_LINES'] - 1;
  1383. }
  1384. elseif(is_numeric($lines) && $lines >= 1) {
  1385. $lines = abs(intval($lines) - 1);
  1386. }
  1387. else {
  1388. list ($from, $to) = explode('-', $lines);
  1389. $from = intval($from);
  1390. $to = intval($to);
  1391. if ($from < 1 || $to < $from) { return false; }
  1392. }
  1393. global $lang;
  1394. global $redis;
  1395. global $pdo;
  1396. if ($_SESSION['mailcow_cc_role'] != "admin") {
  1397. return false;
  1398. }
  1399. // SQL
  1400. if ($application == "mailcow-ui") {
  1401. if (isset($from) && isset($to)) {
  1402. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :from, :to");
  1403. $stmt->execute(array(
  1404. ':from' => $from - 1,
  1405. ':to' => $to
  1406. ));
  1407. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1408. }
  1409. else {
  1410. $stmt = $pdo->prepare("SELECT * FROM `logs` ORDER BY `id` DESC LIMIT :lines");
  1411. $stmt->execute(array(
  1412. ':lines' => $lines + 1,
  1413. ));
  1414. $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1415. }
  1416. if (is_array($data)) {
  1417. return $data;
  1418. }
  1419. }
  1420. // Redis
  1421. if ($application == "dovecot-mailcow") {
  1422. if (isset($from) && isset($to)) {
  1423. $data = $redis->lRange('DOVECOT_MAILLOG', $from - 1, $to - 1);
  1424. }
  1425. else {
  1426. $data = $redis->lRange('DOVECOT_MAILLOG', 0, $lines);
  1427. }
  1428. if ($data) {
  1429. foreach ($data as $json_line) {
  1430. $data_array[] = json_decode($json_line, true);
  1431. }
  1432. return $data_array;
  1433. }
  1434. }
  1435. if ($application == "postfix-mailcow") {
  1436. if (isset($from) && isset($to)) {
  1437. $data = $redis->lRange('POSTFIX_MAILLOG', $from - 1, $to - 1);
  1438. }
  1439. else {
  1440. $data = $redis->lRange('POSTFIX_MAILLOG', 0, $lines);
  1441. }
  1442. if ($data) {
  1443. foreach ($data as $json_line) {
  1444. $data_array[] = json_decode($json_line, true);
  1445. }
  1446. return $data_array;
  1447. }
  1448. }
  1449. if ($application == "sogo-mailcow") {
  1450. if (isset($from) && isset($to)) {
  1451. $data = $redis->lRange('SOGO_LOG', $from - 1, $to - 1);
  1452. }
  1453. else {
  1454. $data = $redis->lRange('SOGO_LOG', 0, $lines);
  1455. }
  1456. if ($data) {
  1457. foreach ($data as $json_line) {
  1458. $data_array[] = json_decode($json_line, true);
  1459. }
  1460. return $data_array;
  1461. }
  1462. }
  1463. if ($application == "watchdog-mailcow") {
  1464. if (isset($from) && isset($to)) {
  1465. $data = $redis->lRange('WATCHDOG_LOG', $from - 1, $to - 1);
  1466. }
  1467. else {
  1468. $data = $redis->lRange('WATCHDOG_LOG', 0, $lines);
  1469. }
  1470. if ($data) {
  1471. foreach ($data as $json_line) {
  1472. $data_array[] = json_decode($json_line, true);
  1473. }
  1474. return $data_array;
  1475. }
  1476. }
  1477. if ($application == "acme-mailcow") {
  1478. if (isset($from) && isset($to)) {
  1479. $data = $redis->lRange('ACME_LOG', $from - 1, $to - 1);
  1480. }
  1481. else {
  1482. $data = $redis->lRange('ACME_LOG', 0, $lines);
  1483. }
  1484. if ($data) {
  1485. foreach ($data as $json_line) {
  1486. $data_array[] = json_decode($json_line, true);
  1487. }
  1488. return $data_array;
  1489. }
  1490. }
  1491. if ($application == "ratelimited") {
  1492. if (isset($from) && isset($to)) {
  1493. $data = $redis->lRange('RL_LOG', $from - 1, $to - 1);
  1494. }
  1495. else {
  1496. $data = $redis->lRange('RL_LOG', 0, $lines);
  1497. }
  1498. if ($data) {
  1499. foreach ($data as $json_line) {
  1500. $data_array[] = json_decode($json_line, true);
  1501. }
  1502. return $data_array;
  1503. }
  1504. }
  1505. if ($application == "api-mailcow") {
  1506. if (isset($from) && isset($to)) {
  1507. $data = $redis->lRange('API_LOG', $from - 1, $to - 1);
  1508. }
  1509. else {
  1510. $data = $redis->lRange('API_LOG', 0, $lines);
  1511. }
  1512. if ($data) {
  1513. foreach ($data as $json_line) {
  1514. $data_array[] = json_decode($json_line, true);
  1515. }
  1516. return $data_array;
  1517. }
  1518. }
  1519. if ($application == "netfilter-mailcow") {
  1520. if (isset($from) && isset($to)) {
  1521. $data = $redis->lRange('NETFILTER_LOG', $from - 1, $to - 1);
  1522. }
  1523. else {
  1524. $data = $redis->lRange('NETFILTER_LOG', 0, $lines);
  1525. }
  1526. if ($data) {
  1527. foreach ($data as $json_line) {
  1528. $data_array[] = json_decode($json_line, true);
  1529. }
  1530. return $data_array;
  1531. }
  1532. }
  1533. if ($application == "autodiscover-mailcow") {
  1534. if (isset($from) && isset($to)) {
  1535. $data = $redis->lRange('AUTODISCOVER_LOG', $from - 1, $to - 1);
  1536. }
  1537. else {
  1538. $data = $redis->lRange('AUTODISCOVER_LOG', 0, $lines);
  1539. }
  1540. if ($data) {
  1541. foreach ($data as $json_line) {
  1542. $data_array[] = json_decode($json_line, true);
  1543. }
  1544. return $data_array;
  1545. }
  1546. }
  1547. if ($application == "rspamd-history") {
  1548. $curl = curl_init();
  1549. curl_setopt($curl, CURLOPT_UNIX_SOCKET_PATH, '/var/lib/rspamd/rspamd.sock');
  1550. if (!is_numeric($lines)) {
  1551. list ($from, $to) = explode('-', $lines);
  1552. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?from=" . intval($from) . "&to=" . intval($to));
  1553. }
  1554. else {
  1555. curl_setopt($curl, CURLOPT_URL,"http://rspamd/history?to=" . intval($lines));
  1556. }
  1557. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1558. $history = curl_exec($curl);
  1559. if (!curl_errno($curl)) {
  1560. $data_array = json_decode($history, true);
  1561. curl_close($curl);
  1562. return $data_array['rows'];
  1563. }
  1564. curl_close($curl);
  1565. return false;
  1566. }
  1567. return false;
  1568. }
  1569. function getGUID() {
  1570. if (function_exists('com_create_guid')) {
  1571. return com_create_guid();
  1572. }
  1573. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  1574. $charid = strtoupper(md5(uniqid(rand(), true)));
  1575. $hyphen = chr(45);// "-"
  1576. return substr($charid, 0, 8).$hyphen
  1577. .substr($charid, 8, 4).$hyphen
  1578. .substr($charid,12, 4).$hyphen
  1579. .substr($charid,16, 4).$hyphen
  1580. .substr($charid,20,12);
  1581. }
  1582. function solr_status() {
  1583. $curl = curl_init();
  1584. $endpoint = 'http://solr:8983/solr/admin/cores';
  1585. $params = array(
  1586. 'action' => 'STATUS',
  1587. 'core' => 'dovecot-fts',
  1588. 'indexInfo' => 'true'
  1589. );
  1590. $url = $endpoint . '?' . http_build_query($params);
  1591. curl_setopt($curl, CURLOPT_URL, $url);
  1592. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1593. curl_setopt($curl, CURLOPT_POST, 0);
  1594. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1595. $response_core = curl_exec($curl);
  1596. if ($response_core === false) {
  1597. $err = curl_error($curl);
  1598. curl_close($curl);
  1599. return false;
  1600. }
  1601. else {
  1602. curl_close($curl);
  1603. $curl = curl_init();
  1604. $status_core = json_decode($response_core, true);
  1605. $url = 'http://solr:8983/solr/admin/info/system';
  1606. curl_setopt($curl, CURLOPT_URL, $url);
  1607. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1608. curl_setopt($curl, CURLOPT_POST, 0);
  1609. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  1610. $response_sysinfo = curl_exec($curl);
  1611. if ($response_sysinfo === false) {
  1612. $err = curl_error($curl);
  1613. curl_close($curl);
  1614. return false;
  1615. }
  1616. else {
  1617. curl_close($curl);
  1618. $status_sysinfo = json_decode($response_sysinfo, true);
  1619. $status = array_merge($status_core, $status_sysinfo);
  1620. return (!empty($status['status']['dovecot-fts']) && !empty($status['jvm']['memory'])) ? $status : false;
  1621. }
  1622. return (!empty($status['status']['dovecot-fts'])) ? $status['status']['dovecot-fts'] : false;
  1623. }
  1624. return false;
  1625. }
  1626. function cleanupJS($ignore = '', $folder = '/tmp/*.js') {
  1627. foreach (glob($folder) as $filename) {
  1628. if(strpos($filename, $ignore) !== false) {
  1629. continue;
  1630. }
  1631. unlink($filename);
  1632. }
  1633. }
  1634. function cleanupCSS($ignore = '', $folder = '/tmp/*.css') {
  1635. foreach (glob($folder) as $filename) {
  1636. if(strpos($filename, $ignore) !== false) {
  1637. continue;
  1638. }
  1639. unlink($filename);
  1640. }
  1641. }
  1642. ?>