PostfixAdmin - web based virtual user administration interface for Postfix mail servers https://postfixadmin.github.io/postfixadmin/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2296 lines
72 KiB

8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
5 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
  1. <?php
  2. /**
  3. * Postfix Admin
  4. *
  5. * LICENSE
  6. * This source file is subject to the GPL license that is bundled with
  7. * this package in the file LICENSE.TXT.
  8. *
  9. * Further details on the project are available at http://postfixadmin.sf.net
  10. *
  11. * @license GNU GPL v2 or later.
  12. *
  13. * File: functions.inc.php
  14. * Contains re-usable code.
  15. */
  16. $min_db_version = 1843; # update (at least) before a release with the latest function numbrer in upgrade.php
  17. /**
  18. * check_session
  19. * Action: Check if a session already exists, if not redirect to login.php
  20. * Call: check_session ()
  21. * @return String username (e.g. foo@example.com)
  22. */
  23. function authentication_get_username() {
  24. if (defined('POSTFIXADMIN_CLI')) {
  25. return 'CLI';
  26. }
  27. if (defined('POSTFIXADMIN_SETUP')) {
  28. return 'SETUP.PHP';
  29. }
  30. if (!isset($_SESSION['sessid'])) {
  31. header("Location: login.php");
  32. exit(0);
  33. }
  34. $SESSID_USERNAME = $_SESSION['sessid']['username'];
  35. return $SESSID_USERNAME;
  36. }
  37. /**
  38. * Returns the type of user - either 'user' or 'admin'
  39. * Returns false if neither (E.g. if not logged in)
  40. * @return string|bool admin or user or (boolean) false.
  41. */
  42. function authentication_get_usertype() {
  43. if (isset($_SESSION['sessid'])) {
  44. if (isset($_SESSION['sessid']['type'])) {
  45. return $_SESSION['sessid']['type'];
  46. }
  47. }
  48. return false;
  49. }
  50. /**
  51. *
  52. * Used to determine whether a user has a particular role.
  53. * @param string $role role-name. (E.g. admin, global-admin or user)
  54. * @return boolean True if they have the requested role in their session.
  55. * Note, user < admin < global-admin
  56. */
  57. function authentication_has_role($role) {
  58. if (isset($_SESSION['sessid'])) {
  59. if (isset($_SESSION['sessid']['roles'])) {
  60. if (in_array($role, $_SESSION['sessid']['roles'])) {
  61. return true;
  62. }
  63. }
  64. }
  65. return false;
  66. }
  67. /**
  68. * Used to enforce that $user has a particular role when
  69. * viewing a page.
  70. * If they are lacking a role, redirect them to login.php
  71. *
  72. * Note, user < admin < global-admin
  73. * @param string $role
  74. * @return bool
  75. */
  76. function authentication_require_role($role) {
  77. // redirect to appropriate page?
  78. if (authentication_has_role($role)) {
  79. return true;
  80. }
  81. header("Location: login.php");
  82. exit(0);
  83. }
  84. /**
  85. * Initialize a user or admin session
  86. *
  87. * @param String $username the user or admin name
  88. * @param boolean $is_admin true if the user is an admin, false otherwise
  89. * @return boolean true on success
  90. */
  91. function init_session($username, $is_admin = false) {
  92. $status = session_regenerate_id(true);
  93. $_SESSION['sessid'] = array();
  94. $_SESSION['sessid']['roles'] = array();
  95. $_SESSION['sessid']['roles'][] = $is_admin ? 'admin' : 'user';
  96. $_SESSION['sessid']['username'] = $username;
  97. $_SESSION['PFA_token'] = md5(uniqid("", true));
  98. return $status;
  99. }
  100. /**
  101. * Add an error message for display on the next page that is rendered.
  102. * @param string|array $string message(s) to show.
  103. *
  104. * Stores string in session. Flushed through header template.
  105. * @see _flash_string()
  106. * @return void
  107. */
  108. function flash_error($string) {
  109. _flash_string('error', $string);
  110. }
  111. /**
  112. * Used to display an info message on successful update.
  113. * @param string|array $string message(s) to show.
  114. * Stores data in session.
  115. * @see _flash_string()
  116. * @return void
  117. */
  118. function flash_info($string) {
  119. _flash_string('info', $string);
  120. }
  121. /**
  122. * 'Private' method used for flash_info() and flash_error().
  123. * @param string $type
  124. * @param array|string $string
  125. * @retrn void
  126. */
  127. function _flash_string($type, $string) {
  128. if (is_array($string)) {
  129. foreach ($string as $singlestring) {
  130. _flash_string($type, $singlestring);
  131. }
  132. return;
  133. }
  134. if (!isset($_SESSION['flash'])) {
  135. $_SESSION['flash'] = array();
  136. }
  137. if (!isset($_SESSION['flash'][$type])) {
  138. $_SESSION['flash'][$type] = array();
  139. }
  140. $_SESSION['flash'][$type][] = $string;
  141. }
  142. /**
  143. * @param bool $use_post - set to 0 if $_POST should NOT be read
  144. * @return string e.g en
  145. * Try to figure out what language the user wants based on browser / cookie
  146. */
  147. function check_language($use_post = true) {
  148. global $supported_languages; # from languages/languages.php
  149. // prefer a $_POST['lang'] if present
  150. if ($use_post && safepost('lang')) {
  151. $lang = safepost('lang');
  152. if (is_string($lang) && array_key_exists($lang, $supported_languages)) {
  153. return $lang;
  154. }
  155. }
  156. // Failing that, is there a $_COOKIE['lang'] ?
  157. if (safecookie('lang')) {
  158. $lang = safecookie('lang');
  159. if (is_string($lang) && array_key_exists($lang, $supported_languages)) {
  160. return $lang;
  161. }
  162. }
  163. $lang = Config::read_string('default_language');
  164. // If not, did the browser give us any hint(s)?
  165. if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  166. $lang_array = preg_split('/(\s*,\s*)/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
  167. foreach ($lang_array as $value) {
  168. $lang_next = strtolower(trim($value));
  169. $lang_next = preg_replace('/;.*$/', '', $lang_next); # remove things like ";q=0.8"
  170. if (array_key_exists($lang_next, $supported_languages)) {
  171. return $lang_next;
  172. }
  173. }
  174. }
  175. return $lang;
  176. }
  177. /**
  178. * Action: returns a language selector dropdown with the browser (or cookie) language preselected
  179. * @return string
  180. *
  181. *
  182. */
  183. function language_selector() {
  184. global $supported_languages; # from languages/languages.php
  185. $current_lang = check_language();
  186. $selector = '<select name="lang" xml:lang="en" dir="ltr">';
  187. foreach ($supported_languages as $lang => $lang_name) {
  188. if ($lang == $current_lang) {
  189. $selected = ' selected="selected"';
  190. } else {
  191. $selected = '';
  192. }
  193. $selector .= "<option value='$lang'$selected>$lang_name</option>";
  194. }
  195. $selector .= "</select>";
  196. return $selector;
  197. }
  198. /**
  199. * Checks if a domain is valid
  200. * @param string $domain
  201. * @return string empty if the domain is valid, otherwise string with the errormessage
  202. *
  203. * @todo make check_domain able to handle as example .local domains
  204. * @todo skip DNS check if the domain exists in PostfixAdmin?
  205. */
  206. function check_domain($domain) {
  207. if (!preg_match('/^([-0-9A-Z]+\.)+' . '([-0-9A-Z]){1,13}$/i', ($domain))) {
  208. return sprintf(Config::lang('pInvalidDomainRegex'), htmlentities($domain));
  209. }
  210. if (Config::bool('emailcheck_resolve_domain') && 'WINDOWS'!=(strtoupper(substr(php_uname('s'), 0, 7)))) {
  211. // Look for an AAAA, A, or MX record for the domain
  212. if (function_exists('checkdnsrr')) {
  213. $start = microtime(true); # check for slow nameservers, part 1
  214. // AAAA (IPv6) is only available in PHP v. >= 5
  215. if (version_compare(phpversion(), "5.0.0", ">=") && checkdnsrr($domain, 'AAAA')) {
  216. $retval = '';
  217. } elseif (checkdnsrr($domain, 'A')) {
  218. $retval = '';
  219. } elseif (checkdnsrr($domain, 'MX')) {
  220. $retval = '';
  221. } elseif (checkdnsrr($domain, 'NS')) {
  222. error_log("DNS is not correctly configured for $domain to send or receive email");
  223. $retval = '';
  224. } else {
  225. $retval = sprintf(Config::lang('pInvalidDomainDNS'), htmlentities($domain));
  226. }
  227. $end = microtime(true); # check for slow nameservers, part 2
  228. $time_needed = $end - $start;
  229. if ($time_needed > 2) {
  230. error_log("Warning: slow nameserver - lookup for $domain took $time_needed seconds");
  231. }
  232. return $retval;
  233. } else {
  234. return 'emailcheck_resolve_domain is enabled, but function (checkdnsrr) missing!';
  235. }
  236. }
  237. return '';
  238. }
  239. /**
  240. * Get password expiration value for a domain
  241. * @param string $domain - a string that may be a domain
  242. * @return int password expiration value for this domain (DAYS, or zero if not enabled)
  243. */
  244. function get_password_expiration_value($domain) {
  245. $table_domain = table_by_key('domain');
  246. $query = "SELECT password_expiry FROM $table_domain WHERE domain= :domain";
  247. $result = db_query_one($query, array('domain' => $domain));
  248. if (is_array($result) && isset($result['password_expiry'])) {
  249. return $result['password_expiry'];
  250. }
  251. return 0;
  252. }
  253. /**
  254. * check_email
  255. * Checks if an email is valid - if it is, return true, else false.
  256. * @todo make check_email able to handle already added domains
  257. * @param string $email - a string that may be an email address.
  258. * @return string empty if it's a valid email address, otherwise string with the errormessage
  259. */
  260. function check_email($email) {
  261. $ce_email=$email;
  262. //strip the vacation domain out if we are using it
  263. //and change from blah#foo.com@autoreply.foo.com to blah@foo.com
  264. if (Config::bool('vacation')) {
  265. $vacation_domain = Config::read_string('vacation_domain');
  266. $ce_email = preg_replace("/@$vacation_domain\$/", '', $ce_email);
  267. $ce_email = preg_replace("/#/", '@', $ce_email);
  268. }
  269. // Perform non-domain-part sanity checks
  270. if (!preg_match('/^[-!#$%&\'*+\\.\/0-9=?A-Z^_{|}~]+' . '@' . '[^@]+$/i', $ce_email)) {
  271. return "" . Config::lang_f('pInvalidMailRegex', $email);
  272. }
  273. if (function_exists('filter_var')) {
  274. $check = filter_var($email, FILTER_VALIDATE_EMAIL);
  275. if (!$check) {
  276. return "" . Config::lang_f('pInvalidMailRegex', $email);
  277. }
  278. }
  279. // Determine domain name
  280. $matches = array();
  281. if (preg_match('|@(.+)$|', $ce_email, $matches)) {
  282. $domain=$matches[1];
  283. # check domain name
  284. return "" . check_domain($domain);
  285. }
  286. return "" . Config::lang_f('pInvalidMailRegex', $email);
  287. }
  288. /**
  289. * Clean a string, escaping any meta characters that could be
  290. * used to disrupt an SQL string. The method of the escaping is dependent on the underlying DB
  291. * and MAY NOT be just \' ing. (e.g. sqlite and PgSQL change "it's" to "it''s".
  292. *
  293. * The PDO quote function surrounds what you pass in with quote marks; for legacy reasons we remove these,
  294. * but assume the caller will actually add them back in (!).
  295. *
  296. * e.g. caller code looks like :
  297. *
  298. * <code>
  299. * $sql = "SELECT * FROM foo WHERE x = '" . escape_string('fish') . "'";
  300. * </code>
  301. *
  302. * @param int|string $string_or_int parameters to escape
  303. * @return string cleaned data, suitable for use within an SQL statement.
  304. */
  305. function escape_string($string_or_int) {
  306. $link = db_connect();
  307. $string_or_int = (string) $string_or_int;
  308. $quoted = $link->quote($string_or_int);
  309. return trim($quoted, "'");
  310. }
  311. /**
  312. * safeget
  313. * Action: get value from $_GET[$param], or $default if $_GET[$param] is not set
  314. * Call: $param = safeget('param') # replaces $param = $_GET['param']
  315. * - or -
  316. * $param = safeget('param', 'default')
  317. *
  318. * @param string $param parameter name.
  319. * @param string $default (optional) - default value if key is not set.
  320. * @return string
  321. */
  322. function safeget($param, $default = "") {
  323. $retval = $default;
  324. if (isset($_GET[$param]) && is_string($_GET[$param])) {
  325. $retval = $_GET[$param];
  326. }
  327. return $retval;
  328. }
  329. /**
  330. * safepost - similar to safeget() but for $_POST
  331. * @see safeget()
  332. * @param string $param parameter name
  333. * @param string $default (optional) default value (defaults to "")
  334. * @return string - value in $_POST[$param] or $default
  335. */
  336. function safepost($param, $default = "") {
  337. $retval = $default;
  338. if (isset($_POST[$param]) && is_string($_POST[$param])) {
  339. $retval = $_POST[$param];
  340. }
  341. return $retval;
  342. }
  343. /**
  344. * safeserver
  345. * @see safeget()
  346. * @param string $param
  347. * @param string $default (optional)
  348. * @return string value from $_SERVER[$param] or $default
  349. */
  350. function safeserver($param, $default = "") {
  351. $retval = $default;
  352. if (isset($_SERVER[$param])) {
  353. $retval = $_SERVER[$param];
  354. }
  355. return $retval;
  356. }
  357. /**
  358. * safecookie
  359. * @see safeget()
  360. * @param string $param
  361. * @param string $default (optional)
  362. * @return string value from $_COOKIE[$param] or $default
  363. */
  364. function safecookie($param, $default = "") {
  365. $retval = $default;
  366. if (isset($_COOKIE[$param]) && is_string($_COOKIE[$param])) {
  367. $retval = $_COOKIE[$param];
  368. }
  369. return $retval;
  370. }
  371. /**
  372. * safesession
  373. * @see safeget()
  374. * @param string $param
  375. * @param string $default (optional)
  376. * @return string value from $_SESSION[$param] or $default
  377. */
  378. function safesession($param, $default = "") {
  379. $retval = $default;
  380. if (isset($_SESSION[$param]) && is_string($_SESSION[$param])) {
  381. $retval = $_SESSION[$param];
  382. }
  383. return $retval;
  384. }
  385. /**
  386. * pacol
  387. * @param int $allow_editing
  388. * @param int $display_in_form
  389. * @param int display_in_list
  390. * @param string $type
  391. * @param string PALANG_label
  392. * @param string PALANG_desc
  393. * @param any optional $default
  394. * @param array $options optional options
  395. * @param int or $not_in_db - if array, can contain the remaining parameters as associated array. Otherwise counts as $not_in_db
  396. * @return array for $struct
  397. */
  398. function pacol($allow_editing, $display_in_form, $display_in_list, $type, $PALANG_label, $PALANG_desc, $default = "", $options = array(), $multiopt=0, $dont_write_to_db=0, $select="", $extrafrom="", $linkto="") {
  399. if ($PALANG_label != '') {
  400. $PALANG_label = Config::lang($PALANG_label);
  401. }
  402. if ($PALANG_desc != '') {
  403. $PALANG_desc = Config::lang($PALANG_desc);
  404. }
  405. if (is_array($multiopt)) { # remaining parameters provided in named array
  406. $not_in_db = 0; # keep default value
  407. foreach ($multiopt as $key => $value) {
  408. $$key = $value; # extract everything to the matching variable
  409. }
  410. } else {
  411. $not_in_db = $multiopt;
  412. }
  413. return array(
  414. 'editable' => $allow_editing,
  415. 'display_in_form' => $display_in_form,
  416. 'display_in_list' => $display_in_list,
  417. 'type' => $type,
  418. 'label' => $PALANG_label, # $PALANG field label
  419. 'desc' => $PALANG_desc, # $PALANG field description
  420. 'default' => $default,
  421. 'options' => $options,
  422. 'not_in_db' => $not_in_db,
  423. 'dont_write_to_db' => $dont_write_to_db,
  424. 'select' => $select, # replaces the field name after SELECT
  425. 'extrafrom' => $extrafrom, # added after FROM xy - useful for JOINs etc.
  426. 'linkto' => $linkto, # make the value a link - %s will be replaced with the ID
  427. );
  428. }
  429. /**
  430. * Action: Get all the properties of a domain.
  431. * @param string $domain
  432. * @return array
  433. */
  434. function get_domain_properties($domain) {
  435. $handler = new DomainHandler();
  436. if (!$handler->init($domain)) {
  437. throw new Exception("Error: " . join("\n", $handler->errormsg));
  438. }
  439. if (!$handler->view()) {
  440. throw new Exception("Error: " . join("\n", $handler->errormsg));
  441. }
  442. $result = $handler->result();
  443. return $result;
  444. }
  445. /**
  446. * create_page_browser
  447. * Action: Get page browser for a long list of mailboxes, aliases etc.
  448. *
  449. * @param string $idxfield - database field name to use as title e.g. alias.address
  450. * @param string $querypart - core part of the query (starting at "FROM") e.g. FROM alias WHERE address like ...
  451. * @return array
  452. */
  453. function create_page_browser($idxfield, $querypart, $sql_params = []) {
  454. global $CONF;
  455. $page_size = (int) $CONF['page_size'];
  456. $label_len = 2;
  457. $pagebrowser = array();
  458. $count_results = 0;
  459. if ($page_size < 2) { # will break the page browser
  460. throw new Exception('$CONF[\'page_size\'] must be 2 or more!');
  461. }
  462. # get number of rows
  463. $query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp";
  464. $result = db_query_one($query, $sql_params);
  465. if ($result && isset($result['counter'])) {
  466. $count_results = $result['counter'] -1; # we start counting at 0, not 1
  467. }
  468. if ($count_results < $page_size) {
  469. return array(); # only one page - no pagebrowser required
  470. }
  471. # init row counter
  472. $initcount = "SET @r=-1";
  473. if (db_pgsql()) {
  474. $initcount = "CREATE TEMPORARY SEQUENCE rowcount MINVALUE 0";
  475. }
  476. if (!db_sqlite()) {
  477. db_execute($initcount);
  478. }
  479. # get labels for relevant rows (first and last of each page)
  480. $page_size_zerobase = $page_size - 1;
  481. $query = "
  482. SELECT * FROM (
  483. SELECT $idxfield AS label, @r := @r + 1 AS 'r' $querypart
  484. ) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
  485. ";
  486. if (db_pgsql()) {
  487. $query = "
  488. SELECT * FROM (
  489. SELECT $idxfield AS label, nextval('rowcount') AS r $querypart
  490. ) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
  491. ";
  492. }
  493. if (db_sqlite()) {
  494. $end = $idxfield;
  495. if (strpos($idxfield, '.') !== false) {
  496. $bits = explode('.', $idxfield);
  497. $end = $bits[1];
  498. }
  499. $query = "
  500. WITH idx AS (SELECT * $querypart)
  501. SELECT $end AS label, (SELECT (COUNT(*) - 1) FROM idx t1 WHERE t1.$end <= t2.$end ) AS r
  502. FROM idx t2
  503. WHERE (r % $page_size) IN (0,$page_size_zerobase) OR r = $count_results";
  504. }
  505. # PostgreSQL:
  506. # http://www.postgresql.org/docs/8.1/static/sql-createsequence.html
  507. # http://www.postgresonline.com/journal/archives/79-Simulating-Row-Number-in-PostgreSQL-Pre-8.4.html
  508. # http://www.pg-forum.de/sql/1518-nummerierung-der-abfrageergebnisse.html
  509. # CREATE TEMPORARY SEQUENCE foo MINVALUE 0 MAXVALUE $page_size_zerobase CYCLE
  510. # afterwards: DROP SEQUENCE foo
  511. $result = db_query_all($query, $sql_params);
  512. for ($k = 0; $k < count($result); $k+=2) {
  513. if (isset($result[$k + 1])) {
  514. $label = substr($result[$k]['label'], 0, $label_len) . '-' . substr($result[$k+1]['label'], 0, $label_len);
  515. } else {
  516. $label = substr($result[$k]['label'], 0, $label_len);
  517. }
  518. $pagebrowser[] = $label;
  519. }
  520. if (db_pgsql()) {
  521. db_execute("DROP SEQUENCE rowcount");
  522. }
  523. return $pagebrowser;
  524. }
  525. /**
  526. * Recalculates the quota from MBs to bytes (divide, /)
  527. * @param int $quota
  528. * @return float
  529. */
  530. function divide_quota($quota) {
  531. if ($quota == -1) {
  532. return $quota;
  533. }
  534. $value = round($quota / (int) Config::read_string('quota_multiplier'), 2);
  535. return $value;
  536. }
  537. /**
  538. * Checks if the admin is the owner of the domain (or global-admin)
  539. * @param string $username
  540. * @param string $domain
  541. * @return bool
  542. */
  543. function check_owner($username, $domain) {
  544. $table_domain_admins = table_by_key('domain_admins');
  545. $result = db_query_all(
  546. "SELECT 1 FROM $table_domain_admins WHERE username= ? AND (domain = ? OR domain = 'ALL') AND active = ?" ,
  547. array($username, $domain, db_get_boolean(true))
  548. );
  549. if (sizeof($result) == 1 || sizeof($result) == 2) { # "ALL" + specific domain permissions is possible
  550. # TODO: if superadmin, check if given domain exists in the database
  551. return true;
  552. } else {
  553. if (sizeof($result) > 2) { # more than 2 results means something really strange happened...
  554. flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save "
  555. . "button once to fix the database. If this doesn't help, open a bugreport.");
  556. }
  557. return false;
  558. }
  559. }
  560. /**
  561. * List domains for an admin user.
  562. * @param String $username
  563. * @return array of domain names.
  564. */
  565. function list_domains_for_admin($username) {
  566. $table_domain = table_by_key('domain');
  567. $table_domain_admins = table_by_key('domain_admins');
  568. $condition = array();
  569. $E_username = escape_string($username);
  570. $query = "SELECT $table_domain.domain FROM $table_domain ";
  571. $condition[] = "$table_domain.domain != 'ALL'";
  572. $pvalues = array();
  573. $result = db_query_one("SELECT username FROM $table_domain_admins WHERE username= :username AND domain='ALL'", array('username' => $username));
  574. if (empty($result)) { # not a superadmin
  575. $pvalues['username'] = $username;
  576. $pvalues['active'] = db_get_boolean(true);
  577. $pvalues['backupmx'] = db_get_boolean(false);
  578. $query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain ";
  579. $condition[] = "$table_domain_admins.username = :username ";
  580. $condition[] = "$table_domain.active = :active "; # TODO: does it really make sense to exclude inactive...
  581. $condition[] = "$table_domain.backupmx = :backupmx" ; # TODO: ... and backupmx domains for non-superadmins?
  582. }
  583. $query .= " WHERE " . join(' AND ', $condition);
  584. $query .= " ORDER BY $table_domain.domain";
  585. $result = db_query_all($query, $pvalues);
  586. return array_column($result, 'domain');
  587. }
  588. /**
  589. * List all available domains.
  590. *
  591. * @return array
  592. */
  593. function list_domains() {
  594. $list = array();
  595. $table_domain = table_by_key('domain');
  596. $result = db_query_all("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
  597. $i = 0;
  598. foreach ($result as $row) {
  599. $list[$i] = $row['domain'];
  600. $i++;
  601. }
  602. return $list;
  603. }
  604. //
  605. // list_admins
  606. // Action: Lists all the admins
  607. // Call: list_admins ()
  608. //
  609. // was admin_list_admins
  610. //
  611. function list_admins() {
  612. $handler = new AdminHandler();
  613. $handler->getList('');
  614. return $handler->result();
  615. }
  616. //
  617. // encode_header
  618. // Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters.
  619. // Call: encode_header (string header, string charset)
  620. //
  621. function encode_header($string, $default_charset = "utf-8") {
  622. if (strtolower($default_charset) == 'iso-8859-1') {
  623. $string = str_replace("\240", ' ', $string);
  624. }
  625. $j = strlen($string);
  626. $max_l = 75 - strlen($default_charset) - 7;
  627. $aRet = array();
  628. $ret = '';
  629. $iEncStart = $enc_init = false;
  630. $cur_l = $iOffset = 0;
  631. for ($i = 0; $i < $j; ++$i) {
  632. switch ($string[$i]) {
  633. case '=':
  634. case '<':
  635. case '>':
  636. case ',':
  637. case '?':
  638. case '_':
  639. if ($iEncStart === false) {
  640. $iEncStart = $i;
  641. }
  642. $cur_l+=3;
  643. if ($cur_l > ($max_l-2)) {
  644. $aRet[] = substr($string, $iOffset, $iEncStart-$iOffset);
  645. $aRet[] = "=?$default_charset?Q?$ret?=";
  646. $iOffset = $i;
  647. $cur_l = 0;
  648. $ret = '';
  649. $iEncStart = false;
  650. } else {
  651. $ret .= sprintf("=%02X", ord($string[$i]));
  652. }
  653. break;
  654. case '(':
  655. case ')':
  656. if ($iEncStart !== false) {
  657. $aRet[] = substr($string, $iOffset, $iEncStart-$iOffset);
  658. $aRet[] = "=?$default_charset?Q?$ret?=";
  659. $iOffset = $i;
  660. $cur_l = 0;
  661. $ret = '';
  662. $iEncStart = false;
  663. }
  664. break;
  665. case ' ':
  666. if ($iEncStart !== false) {
  667. $cur_l++;
  668. if ($cur_l > $max_l) {
  669. $aRet[] = substr($string, $iOffset, $iEncStart-$iOffset);
  670. $aRet[] = "=?$default_charset?Q?$ret?=";
  671. $iOffset = $i;
  672. $cur_l = 0;
  673. $ret = '';
  674. $iEncStart = false;
  675. } else {
  676. $ret .= '_';
  677. }
  678. }
  679. break;
  680. default:
  681. $k = ord($string[$i]);
  682. if ($k > 126) {
  683. if ($iEncStart === false) {
  684. // do not start encoding in the middle of a string, also take the rest of the word.
  685. $sLeadString = substr($string, 0, $i);
  686. $aLeadString = explode(' ', $sLeadString);
  687. $sToBeEncoded = array_pop($aLeadString);
  688. $iEncStart = $i - strlen($sToBeEncoded);
  689. $ret .= $sToBeEncoded;
  690. $cur_l += strlen($sToBeEncoded);
  691. }
  692. $cur_l += 3;
  693. // first we add the encoded string that reached it's max size
  694. if ($cur_l > ($max_l-2)) {
  695. $aRet[] = substr($string, $iOffset, $iEncStart-$iOffset);
  696. $aRet[] = "=?$default_charset?Q?$ret?= ";
  697. $cur_l = 3;
  698. $ret = '';
  699. $iOffset = $i;
  700. $iEncStart = $i;
  701. }
  702. $enc_init = true;
  703. $ret .= sprintf("=%02X", $k);
  704. } else {
  705. if ($iEncStart !== false) {
  706. $cur_l++;
  707. if ($cur_l > $max_l) {
  708. $aRet[] = substr($string, $iOffset, $iEncStart-$iOffset);
  709. $aRet[] = "=?$default_charset?Q?$ret?=";
  710. $iEncStart = false;
  711. $iOffset = $i;
  712. $cur_l = 0;
  713. $ret = '';
  714. } else {
  715. $ret .= $string[$i];
  716. }
  717. }
  718. }
  719. break;
  720. # end switch
  721. }
  722. }
  723. if ($enc_init) {
  724. if ($iEncStart !== false) {
  725. $aRet[] = substr($string, $iOffset, $iEncStart-$iOffset);
  726. $aRet[] = "=?$default_charset?Q?$ret?=";
  727. } else {
  728. $aRet[] = substr($string, $iOffset);
  729. }
  730. $string = implode('', $aRet);
  731. }
  732. return $string;
  733. }
  734. /**
  735. * Generate a random password of $length characters.
  736. * @param int $length (optional, default: 12)
  737. * @return string
  738. *
  739. */
  740. function generate_password($length = 12) {
  741. // define possible characters
  742. $possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l
  743. // add random characters to $password until $length is reached
  744. $password = "";
  745. while (strlen($password) < $length) {
  746. $random = random_int(0, strlen($possible) -1);
  747. $char = substr($possible, $random, 1);
  748. // we don't want this character if it's already in the password
  749. if (!strstr($password, $char)) {
  750. $password .= $char;
  751. }
  752. }
  753. return $password;
  754. }
  755. /**
  756. * Check if a password is strong enough based on the conditions in $CONF['password_validation']
  757. * @param string $password
  758. * @return array of error messages, or empty array if the password is ok
  759. */
  760. function validate_password($password) {
  761. $result = array();
  762. $val_conf = Config::read_array('password_validation');
  763. if (Config::has('min_password_length')) {
  764. $minlen = (int)Config::read_string('min_password_length'); # used up to 2.3.x - check it for backward compatibility
  765. if ($minlen > 0) {
  766. $val_conf['/.{' . $minlen . '}/'] = "password_too_short $minlen";
  767. }
  768. }
  769. foreach ($val_conf as $regex => $message) {
  770. if (is_callable($message)) {
  771. $ret = $message($password);
  772. if (!empty($ret)) {
  773. $result[] = $ret;
  774. }
  775. continue;
  776. }
  777. if (!preg_match($regex, $password)) {
  778. $msgparts = preg_split("/ /", $message, 2);
  779. if (count($msgparts) == 1) {
  780. $result[] = Config::lang($msgparts[0]);
  781. } else {
  782. $result[] = sprintf(Config::lang($msgparts[0]), $msgparts[1]);
  783. }
  784. }
  785. }
  786. return $result;
  787. }
  788. /**
  789. * @param string $pw
  790. * @param string $pw_db - encrypted hash
  791. * @return string crypt'ed password, should equal $pw_db if $pw matches the original
  792. */
  793. function _pacrypt_md5crypt($pw, $pw_db = '') {
  794. if ($pw_db) {
  795. $split_salt = preg_split('/\$/', $pw_db);
  796. if (isset($split_salt[2])) {
  797. $salt = $split_salt[2];
  798. return md5crypt($pw, $salt);
  799. }
  800. }
  801. return md5crypt($pw);
  802. }
  803. /**
  804. * @todo fix this to not throw an E_NOTICE or deprecate/remove.
  805. */
  806. function _pacrypt_crypt($pw, $pw_db = '') {
  807. if ($pw_db) {
  808. return crypt($pw, $pw_db);
  809. }
  810. // Throws E_NOTICE as salt is not specified.
  811. return crypt($pw);
  812. }
  813. /**
  814. * Crypt with MySQL's ENCRYPT function
  815. *
  816. * @param string $pw
  817. * @param string $pw_db (hashed password)
  818. * @return string if $pw_db and the return value match then $pw matches the original password.
  819. */
  820. function _pacrypt_mysql_encrypt($pw, $pw_db = '') {
  821. // See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583
  822. // this is apparently useful for pam_mysql etc.
  823. if ( $pw_db ) {
  824. $res = db_query_one("SELECT ENCRYPT(:pw,:pw_db) as result", ['pw' => $pw, 'pw_db' => $pw_db]);
  825. } else {
  826. // see https://security.stackexchange.com/questions/150687/is-it-safe-to-use-the-encrypt-function-in-mysql-to-hash-passwords
  827. // if no existing password, use a random SHA512 salt.
  828. $salt = _php_crypt_generate_crypt_salt();
  829. $res= db_query_one("SELECT ENCRYPT(:pw, CONCAT('$6$', '$salt')) as result", ['pw' => $pw]);
  830. }
  831. return $res['result'];
  832. }
  833. /**
  834. * Create/Validate courier authlib style crypt'ed passwords. (md5, md5raw, crypt, sha1)
  835. *
  836. * @param string $pw
  837. * @param string $pw_db (optional)
  838. * @return string crypted password - contains {xxx} prefix to identify mechanism.
  839. */
  840. function _pacrypt_authlib($pw, $pw_db) {
  841. global $CONF;
  842. $flavor = $CONF['authlib_default_flavor'];
  843. $salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts
  844. if (preg_match('/^{.*}/', $pw_db)) {
  845. // we have a flavor in the db -> use it instead of default flavor
  846. $result = preg_split('/[{}]/', $pw_db, 3); # split at { and/or }
  847. $flavor = $result[1];
  848. $salt = substr($result[2], 0, 2);
  849. }
  850. if (stripos($flavor, 'md5raw') === 0) {
  851. $password = '{' . $flavor . '}' . md5($pw);
  852. } elseif (stripos($flavor, 'md5') === 0) {
  853. $password = '{' . $flavor . '}' . base64_encode(md5($pw, true));
  854. } elseif (stripos($flavor, 'crypt') === 0) {
  855. $password = '{' . $flavor . '}' . crypt($pw, $salt);
  856. } elseif (stripos($flavor, 'SHA') === 0) {
  857. $password = '{' . $flavor . '}' . base64_encode(sha1($pw, true));
  858. } else {
  859. throw new Exception("authlib_default_flavor '" . $flavor . "' unknown. Valid flavors are 'md5raw', 'md5', 'SHA' and 'crypt'");
  860. }
  861. return $password;
  862. }
  863. /**
  864. * Uses the doveadm pw command, crypted passwords have a {...} prefix to identify type.
  865. *
  866. * @param string $pw - plain text password
  867. * @param string $pw_db - encrypted password, or '' for generation.
  868. * @return string crypted password
  869. */
  870. function _pacrypt_dovecot($pw, $pw_db = '') {
  871. global $CONF;
  872. $split_method = preg_split('/:/', $CONF['encrypt']);
  873. $method = strtoupper($split_method[1]);
  874. # If $pw_db starts with {method}, change $method accordingly
  875. if (!empty($pw_db) && preg_match('/^\{([A-Z0-9.-]+)\}.+/', $pw_db, $method_matches)) {
  876. $method = $method_matches[1];
  877. }
  878. if (! preg_match("/^[A-Z0-9.-]+$/", $method)) {
  879. throw new Exception("invalid dovecot encryption method");
  880. }
  881. # digest-md5 hashes include the username - until someone implements it, let's declare it as unsupported
  882. if (strtolower($method) == 'digest-md5') {
  883. throw new Exception("Sorry, \$CONF['encrypt'] = 'dovecot:digest-md5' is not supported by PostfixAdmin.");
  884. }
  885. # TODO: add -u option for those hashes, or for everything that is salted (-u was available before dovecot 2.1 -> no problem with backward compatibility )
  886. $dovecotpw = "doveadm pw";
  887. if (!empty($CONF['dovecotpw'])) {
  888. $dovecotpw = $CONF['dovecotpw'];
  889. }
  890. # Use proc_open call to avoid safe_mode problems and to prevent showing plain password in process table
  891. $spec = array(
  892. 0 => array("pipe", "r"), // stdin
  893. 1 => array("pipe", "w"), // stdout
  894. 2 => array("pipe", "w"), // stderr
  895. );
  896. $nonsaltedtypes = "SHA|SHA1|SHA256|SHA512|CLEAR|CLEARTEXT|PLAIN|PLAIN-TRUNC|CRAM-MD5|HMAC-MD5|PLAIN-MD4|PLAIN-MD5|LDAP-MD5|LANMAN|NTLM|RPA";
  897. $salted = ! preg_match("/^($nonsaltedtypes)(\.B64|\.BASE64|\.HEX)?$/", strtoupper($method));
  898. $dovepasstest = '';
  899. if ($salted && (!empty($pw_db))) {
  900. # only use -t for salted passwords to be backward compatible with dovecot < 2.1
  901. $dovepasstest = " -t " . escapeshellarg($pw_db);
  902. }
  903. $pipes = [];
  904. $pipe = proc_open("$dovecotpw '-s' $method$dovepasstest", $spec, $pipes);
  905. if (!$pipe) {
  906. throw new Exception("can't proc_open $dovecotpw");
  907. }
  908. // use dovecot's stdin, it uses getpass() twice (except when using -t)
  909. // Write pass in pipe stdin
  910. if (empty($dovepasstest)) {
  911. fwrite($pipes[0], $pw . "\n", 1+strlen($pw));
  912. usleep(1000);
  913. }
  914. fwrite($pipes[0], $pw . "\n", 1+strlen($pw));
  915. fclose($pipes[0]);
  916. $stderr_output = stream_get_contents($pipes[2]);
  917. // Read hash from pipe stdout
  918. $password = fread($pipes[1], 200);
  919. if (!empty($stderr_output) || empty($password)) {
  920. error_log("Failed to read password from $dovecotpw ... stderr: $stderr_output, password: $password ");
  921. throw new Exception("$dovecotpw failed, see error log for details");
  922. }
  923. if (empty($dovepasstest)) {
  924. if (!preg_match('/^\{' . $method . '\}/', $password)) {
  925. error_log("dovecotpw password encryption failed (method: $method) . stderr: $stderr_output");
  926. throw new Exception("can't encrypt password with dovecotpw, see error log for details");
  927. }
  928. } else {
  929. if (!preg_match('(verified)', $password)) {
  930. $password="Thepasswordcannotbeverified";
  931. } else {
  932. $password = rtrim(str_replace('(verified)', '', $password));
  933. }
  934. }
  935. fclose($pipes[1]);
  936. fclose($pipes[2]);
  937. proc_close($pipe);
  938. if ((!empty($pw_db)) && (substr($pw_db, 0, 1) != '{')) {
  939. # for backward compability with "old" dovecot passwords that don't have the {method} prefix
  940. $password = str_replace('{' . $method . '}', '', $password);
  941. }
  942. return rtrim($password);
  943. }
  944. /**
  945. * Supports DES, MD5, BLOWFISH, SHA256, SHA512 methods.
  946. *
  947. * Via config we support an optional prefix (e.g. if you need hashes to start with {SHA256-CRYPT} and optional rounds (hardness) setting.
  948. *
  949. * @param string $pw
  950. * @param string $pw_db (can be empty if setting a new password)
  951. * @return string crypt'ed password; if it matches $pw_db then $pw is the original password.
  952. */
  953. function _pacrypt_php_crypt($pw, $pw_db) {
  954. $configEncrypt = Config::read_string('encrypt');
  955. // use PHPs crypt(), which uses the system's crypt()
  956. // same algorithms as used in /etc/shadow
  957. // you can have mixed hash types in the database for authentication, changed passwords get specified hash type
  958. // the algorithm for a new hash is chosen by feeding a salt with correct magic to crypt()
  959. // set $CONF['encrypt'] to 'php_crypt' to use the default SHA512 crypt method
  960. // set $CONF['encrypt'] to 'php_crypt:METHOD' to use another method; methods supported: DES, MD5, BLOWFISH, SHA256, SHA512
  961. // set $CONF['encrypt'] to 'php_crypt:METHOD:difficulty' where difficulty is between 1000-999999999
  962. // set $CONF['encrypt'] to 'php_crypt:METHOD:difficulty:PREFIX' to prefix the hash with the {PREFIX} etc.
  963. // tested on linux
  964. $prefix = '';
  965. if (strlen($pw_db) > 0) {
  966. // existing pw provided. send entire password hash as salt for crypt() to figure out
  967. $salt = $pw_db;
  968. // if there was a prefix in the password, use this (override anything given in the config).
  969. if (preg_match('/^\{([-A-Z0-9]+)\}(.+)$/', $pw_db, $method_matches)) {
  970. $salt = $method_matches[2];
  971. $prefix = "{" . $method_matches[1] . "}";
  972. }
  973. } else {
  974. $salt_method = 'SHA512'; // hopefully a reasonable default (better than MD5)
  975. $hash_difficulty = '';
  976. // no pw provided. create new password hash
  977. if (strpos($configEncrypt, ':') !== false) {
  978. // use specified hash method
  979. $spec = explode(':', $configEncrypt);
  980. $salt_method = $spec[1];
  981. if (isset($spec[2])) {
  982. $hash_difficulty = $spec[2];
  983. }
  984. if (isset($spec[3])) {
  985. $prefix = $spec[3]; // hopefully something like {SHA256-CRYPT}
  986. }
  987. }
  988. // create appropriate salt for selected hash method
  989. $salt = _php_crypt_generate_crypt_salt($salt_method, $hash_difficulty);
  990. }
  991. $password = crypt($pw, $salt);
  992. return "{$prefix}{$password}";
  993. }
  994. /**
  995. * @param string $hash_type must be one of: MD5, DES, BLOWFISH, SHA256 or SHA512 (default)
  996. * @param int hash difficulty
  997. * @return string
  998. */
  999. function _php_crypt_generate_crypt_salt($hash_type='SHA512', $hash_difficulty=null) {
  1000. // generate a salt (with magic matching chosen hash algorithm) for the PHP crypt() function
  1001. // most commonly used alphabet
  1002. $alphabet = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  1003. switch ($hash_type) {
  1004. case 'DES':
  1005. $alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  1006. $length = 2;
  1007. $salt = _php_crypt_random_string($alphabet, $length);
  1008. return $salt;
  1009. case 'MD5':
  1010. $length = 12;
  1011. $algorithm = '1';
  1012. $salt = _php_crypt_random_string($alphabet, $length);
  1013. return sprintf('$%s$%s', $algorithm, $salt);
  1014. case 'BLOWFISH':
  1015. $length = 22;
  1016. if (empty($hash_difficulty)) {
  1017. $cost = 10;
  1018. } else {
  1019. $cost = (int)$hash_difficulty;
  1020. if ($cost < 4 || $cost > 31) {
  1021. throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 4-31');
  1022. }
  1023. }
  1024. if (version_compare(PHP_VERSION, '5.3.7') >= 0) {
  1025. $algorithm = '2y'; // bcrypt, with fixed unicode problem
  1026. } else {
  1027. $algorithm = '2a'; // bcrypt
  1028. }
  1029. $salt = _php_crypt_random_string($alphabet, $length);
  1030. return sprintf('$%s$%02d$%s', $algorithm, $cost, $salt);
  1031. case 'SHA256':
  1032. $length = 16;
  1033. $algorithm = '5';
  1034. if (empty($hash_difficulty)) {
  1035. $rounds = '';
  1036. } else {
  1037. $rounds = (int)$hash_difficulty;
  1038. if ($rounds < 1000 || $rounds > 999999999) {
  1039. throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 1000-999999999');
  1040. }
  1041. }
  1042. $salt = _php_crypt_random_string($alphabet, $length);
  1043. if (!empty($rounds)) {
  1044. $rounds = sprintf('rounds=%d$', $rounds);
  1045. }
  1046. return sprintf('$%s$%s%s', $algorithm, $rounds, $salt);
  1047. case 'SHA512':
  1048. $length = 16;
  1049. $algorithm = '6';
  1050. if (empty($hash_difficulty)) {
  1051. $rounds = '';
  1052. } else {
  1053. $rounds = (int)$hash_difficulty;
  1054. if ($rounds < 1000 || $rounds > 999999999) {
  1055. throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 1000-999999999');
  1056. }
  1057. }
  1058. $salt = _php_crypt_random_string($alphabet, $length);
  1059. if (!empty($rounds)) {
  1060. $rounds = sprintf('rounds=%d$', $rounds);
  1061. }
  1062. return sprintf('$%s$%s%s', $algorithm, $rounds, $salt);
  1063. default:
  1064. throw new Exception("unknown hash type: '$hash_type'");
  1065. }
  1066. }
  1067. /**
  1068. * Generates a random string of specified $length from $characters.
  1069. * @param string $characters
  1070. * @param int $length
  1071. * @return string of given $length
  1072. */
  1073. function _php_crypt_random_string($characters, $length) {
  1074. $string = '';
  1075. for ($p = 0; $p < $length; $p++) {
  1076. $string .= $characters[random_int(0, strlen($characters) -1)];
  1077. }
  1078. return $string;
  1079. }
  1080. /**
  1081. * Encrypt a password, using the apparopriate hashing mechanism as defined in
  1082. * config.inc.php ($CONF['encrypt']).
  1083. *
  1084. * When wanting to compare one pw to another, it's necessary to provide the salt used - hence
  1085. * the second parameter ($pw_db), which is the existing hash from the DB.
  1086. *
  1087. * @param string $pw
  1088. * @param string $pw_db optional encrypted password
  1089. * @return string encrypted password - if this matches $pw_db then the original password is $pw.
  1090. */
  1091. function pacrypt($pw, $pw_db="") {
  1092. global $CONF;
  1093. switch ($CONF['encrypt']) {
  1094. case 'md5crypt':
  1095. return _pacrypt_md5crypt($pw, $pw_db);
  1096. case 'md5':
  1097. return md5($pw);
  1098. case 'system':
  1099. return _pacrypt_crypt($pw, $pw_db);
  1100. case 'cleartext':
  1101. return $pw;
  1102. case 'mysql_encrypt':
  1103. return _pacrypt_mysql_encrypt($pw, $pw_db);
  1104. case 'authlib':
  1105. return _pacrypt_authlib($pw, $pw_db);
  1106. case 'sha512.b64':
  1107. return _pacrypt_sha512_b64($pw, $pw_db);
  1108. }
  1109. if (preg_match("/^dovecot:/", $CONF['encrypt'])) {
  1110. return _pacrypt_dovecot($pw, $pw_db);
  1111. }
  1112. if (substr($CONF['encrypt'], 0, 9) === 'php_crypt') {
  1113. return _pacrypt_php_crypt($pw, $pw_db);
  1114. }
  1115. throw new Exception('unknown/invalid $CONF["encrypt"] setting: ' . $CONF['encrypt']);
  1116. }
  1117. /**
  1118. * @see https://github.com/postfixadmin/postfixadmin/issues/58
  1119. */
  1120. function _pacrypt_sha512_b64($pw, $pw_db="") {
  1121. if (!function_exists('random_bytes') || !function_exists('crypt') || !defined('CRYPT_SHA512') || !function_exists('mb_substr')) {
  1122. throw new Exception("sha512.b64 not supported!");
  1123. }
  1124. if (!$pw_db) {
  1125. $salt = mb_substr(rtrim(base64_encode(random_bytes(16)),'='),0,16,'8bit');
  1126. return '{SHA512-CRYPT.B64}'.base64_encode(crypt($pw,'$6$'.$salt));
  1127. }
  1128. $password="#Thepasswordcannotbeverified";
  1129. if (strncmp($pw_db,'{SHA512-CRYPT.B64}',18)==0) {
  1130. $dcpwd = base64_decode(mb_substr($pw_db,18,null,'8bit'),true);
  1131. if ($dcpwd !== false && !empty($dcpwd) && strncmp($dcpwd,'$6$',3)==0) {
  1132. $password = '{SHA512-CRYPT.B64}'.base64_encode(crypt($pw,$dcpwd));
  1133. }
  1134. } elseif (strncmp($pw_db,'{MD5-CRYPT}',11)==0) {
  1135. $dcpwd = mb_substr($pw_db,11,null,'8bit');
  1136. if (!empty($dcpwd) && strncmp($dcpwd,'$1$',3)==0) {
  1137. $password = '{MD5-CRYPT}'.crypt($pw,$dcpwd);
  1138. }
  1139. }
  1140. return $password;
  1141. }
  1142. /**
  1143. * Creates MD5 based crypt formatted password.
  1144. * If salt is not provided we generate one.
  1145. *
  1146. * @param string $pw plain text password
  1147. * @param string $salt (optional)
  1148. * @param string $magic (optional)
  1149. * @return string hashed password in crypt format.
  1150. */
  1151. function md5crypt($pw, $salt="", $magic="") {
  1152. $MAGIC = "$1$";
  1153. if ($magic == "") {
  1154. $magic = $MAGIC;
  1155. }
  1156. if ($salt == "") {
  1157. $salt = create_salt();
  1158. }
  1159. $slist = explode("$", $salt);
  1160. if ($slist[0] == "1") {
  1161. $salt = $slist[1];
  1162. }
  1163. $salt = substr($salt, 0, 8);
  1164. $ctx = $pw . $magic . $salt;
  1165. $final = hex2bin(md5($pw . $salt . $pw));
  1166. for ($i=strlen($pw); $i>0; $i-=16) {
  1167. if ($i > 16) {
  1168. $ctx .= substr($final, 0, 16);
  1169. } else {
  1170. $ctx .= substr($final, 0, $i);
  1171. }
  1172. }
  1173. $i = strlen($pw);
  1174. while ($i > 0) {
  1175. if ($i & 1) {
  1176. $ctx .= chr(0);
  1177. } else {
  1178. $ctx .= $pw[0];
  1179. }
  1180. $i = $i >> 1;
  1181. }
  1182. $final = hex2bin(md5($ctx));
  1183. for ($i=0;$i<1000;$i++) {
  1184. $ctx1 = "";
  1185. if ($i & 1) {
  1186. $ctx1 .= $pw;
  1187. } else {
  1188. $ctx1 .= substr($final, 0, 16);
  1189. }
  1190. if ($i % 3) {
  1191. $ctx1 .= $salt;
  1192. }
  1193. if ($i % 7) {
  1194. $ctx1 .= $pw;
  1195. }
  1196. if ($i & 1) {
  1197. $ctx1 .= substr($final, 0, 16);
  1198. } else {
  1199. $ctx1 .= $pw;
  1200. }
  1201. $final = hex2bin(md5($ctx1));
  1202. }
  1203. $passwd = "";
  1204. $passwd .= to64(((ord($final[0]) << 16) | (ord($final[6]) << 8) | (ord($final[12]))), 4);
  1205. $passwd .= to64(((ord($final[1]) << 16) | (ord($final[7]) << 8) | (ord($final[13]))), 4);
  1206. $passwd .= to64(((ord($final[2]) << 16) | (ord($final[8]) << 8) | (ord($final[14]))), 4);
  1207. $passwd .= to64(((ord($final[3]) << 16) | (ord($final[9]) << 8) | (ord($final[15]))), 4);
  1208. $passwd .= to64(((ord($final[4]) << 16) | (ord($final[10]) << 8) | (ord($final[5]))), 4);
  1209. $passwd .= to64(ord($final[11]), 2);
  1210. return "$magic$salt\$$passwd";
  1211. }
  1212. /**
  1213. * @return string - should be random, 8 chars long
  1214. */
  1215. function create_salt() {
  1216. srand((int) microtime()*1000000);
  1217. $salt = substr(md5("" . rand(0, 9999999)), 0, 8);
  1218. return $salt;
  1219. }
  1220. /*
  1221. * remove item $item from array $array
  1222. */
  1223. function remove_from_array($array, $item) {
  1224. # array_diff might be faster, but doesn't provide an easy way to know if the value was found or not
  1225. # return array_diff($array, array($item));
  1226. $ret = array_search($item, $array);
  1227. if ($ret === false) {
  1228. $found = 0;
  1229. } else {
  1230. $found = 1;
  1231. unset($array[$ret]);
  1232. }
  1233. return array($found, $array);
  1234. }
  1235. function to64($v, $n) {
  1236. $ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1237. $ret = "";
  1238. while (($n - 1) >= 0) {
  1239. $n--;
  1240. $ret .= $ITOA64[$v & 0x3f];
  1241. $v = $v >> 6;
  1242. }
  1243. return $ret;
  1244. }
  1245. /**
  1246. * smtp_mail
  1247. * Action: Send email
  1248. * Call: smtp_mail (string to, string from, string subject, string body]) - or -
  1249. * Call: smtp_mail (string to, string from, string data) - DEPRECATED
  1250. * @param String - To:
  1251. * @param String - From:
  1252. * @param String - Subject: (if called with 4 parameters) or full mail body (if called with 3 parameters)
  1253. * @param String (optional) - Password
  1254. * @param String (optional, but recommended) - mail body
  1255. * @return bool - true on success, otherwise false
  1256. * TODO: Replace this with something decent like PEAR::Mail or Zend_Mail.
  1257. */
  1258. function smtp_mail($to, $from, $data, $password = "", $body = "") {
  1259. global $CONF;
  1260. $smtpd_server = $CONF['smtp_server'];
  1261. $smtpd_port = $CONF['smtp_port'];
  1262. //$smtp_server = $_SERVER["SERVER_NAME"];
  1263. $smtp_server = php_uname('n');
  1264. if (!empty($CONF['smtp_client'])) {
  1265. $smtp_server = $CONF['smtp_client'];
  1266. }
  1267. $errno = 0;
  1268. $errstr = "0";
  1269. $timeout = 30;
  1270. if ($body != "") {
  1271. $maildata =
  1272. "To: " . $to . "\n"
  1273. . "From: " . $from . "\n"
  1274. . "Subject: " . encode_header($data) . "\n"
  1275. . "MIME-Version: 1.0\n"
  1276. . "Date: " . date('r') . "\n"
  1277. . "Content-Type: text/plain; charset=utf-8\n"
  1278. . "Content-Transfer-Encoding: 8bit\n"
  1279. . "\n"
  1280. . $body
  1281. ;
  1282. } else {
  1283. $maildata = $data;
  1284. }
  1285. $fh = @fsockopen($smtpd_server, $smtpd_port, $errno, $errstr, $timeout);
  1286. if (!$fh) {
  1287. error_log("fsockopen failed - errno: $errno - errstr: $errstr");
  1288. return false;
  1289. } else {
  1290. smtp_get_response($fh);
  1291. if (Config::bool('smtp_sendmail_tls')) {
  1292. fputs($fh, "STARTTLS\r\n");
  1293. smtp_get_response($fh);
  1294. stream_set_blocking($fh, true);
  1295. stream_socket_enable_crypto($fh, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT);
  1296. stream_set_blocking($fh, true);
  1297. }
  1298. fputs($fh, "EHLO $smtp_server\r\n");
  1299. smtp_get_response($fh);
  1300. if (!empty($password)) {
  1301. fputs($fh,"AUTH LOGIN\r\n");
  1302. smtp_get_response($fh);
  1303. fputs($fh, base64_encode($from) . "\r\n");
  1304. smtp_get_response($fh);
  1305. fputs($fh, base64_encode($password) . "\r\n");
  1306. smtp_get_response($fh);
  1307. }
  1308. fputs($fh, "MAIL FROM:<$from>\r\n");
  1309. smtp_get_response($fh);
  1310. fputs($fh, "RCPT TO:<$to>\r\n");
  1311. smtp_get_response($fh);
  1312. fputs($fh, "DATA\r\n");
  1313. smtp_get_response($fh);
  1314. fputs($fh, "$maildata\r\n.\r\n");
  1315. smtp_get_response($fh);
  1316. fputs($fh, "QUIT\r\n");
  1317. smtp_get_response($fh);
  1318. fclose($fh);
  1319. }
  1320. return true;
  1321. }
  1322. /**
  1323. * smtp_get_admin_email
  1324. * Action: Get configured email address or current user if nothing configured
  1325. * Call: smtp_get_admin_email
  1326. * @return string - username/mail address
  1327. */
  1328. function smtp_get_admin_email() {
  1329. $admin_email = Config::read_string('admin_email');
  1330. if (!empty($admin_email)) {
  1331. return $admin_email;
  1332. } else {
  1333. return authentication_get_username();
  1334. }
  1335. }
  1336. /**
  1337. * smtp_get_admin_password
  1338. * Action: Get smtp password for admin email
  1339. * Call: smtp_get_admin_password
  1340. * @return string - admin smtp password
  1341. */
  1342. function smtp_get_admin_password() {
  1343. return Config::read_string('admin_smtp_password');
  1344. }
  1345. //
  1346. // smtp_get_response
  1347. // Action: Get response from mail server
  1348. // Call: smtp_get_response (string FileHandle)
  1349. //
  1350. function smtp_get_response($fh) {
  1351. $res ='';
  1352. do {
  1353. $line = fgets($fh, 256);
  1354. $res .= $line;
  1355. } while (preg_match("/^\d\d\d\-/", $line));
  1356. return $res;
  1357. }
  1358. $DEBUG_TEXT = <<<EOF
  1359. <p>Please check the documentation and website for more information.</p>
  1360. <ul>
  1361. <li><a href="http://postfixadmin.sf.net">PostfixAdmin - Project website</a></li>
  1362. <li><a href='https://sourceforge.net/p/postfixadmin/discussion/676076'>Forums</a></li>
  1363. </ul>
  1364. EOF;
  1365. /**
  1366. * db_connect
  1367. * Action: Makes a connection to the database if it doesn't exist
  1368. * Call: db_connect ()
  1369. *
  1370. * Return value:
  1371. *
  1372. * @return \PDO
  1373. */
  1374. function db_connect() {
  1375. global $CONF;
  1376. /* some attempt at not reopening an existing connection */
  1377. static $link;
  1378. if (isset($link) && $link) {
  1379. return $link;
  1380. }
  1381. $link = false;
  1382. $options = array(
  1383. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  1384. );
  1385. $username_password = true;
  1386. $queries = array();
  1387. $dsn = null;
  1388. if (db_mysql()) {
  1389. $socket = false;
  1390. if (Config::has('database_socket')) {
  1391. $socket = Config::read_string('database_socket');
  1392. }
  1393. $database_name = Config::read_string('database_name');
  1394. if ($socket) {
  1395. $dsn = "mysql:unix_socket={$socket};dbname={$database_name};charset=UTF8";
  1396. } else {
  1397. $dsn = "mysql:host={$CONF['database_host']};dbname={$database_name};charset=UTF8";
  1398. }
  1399. if (Config::bool('database_use_ssl')) {
  1400. $options[PDO::MYSQL_ATTR_SSL_KEY] = Config::read_string('database_ssl_key');
  1401. $options[PDO::MYSQL_ATTR_SSL_CA] = Config::read_string('database_ssl_ca');
  1402. $options[PDO::MYSQL_ATTR_SSL_CAPATH] = Config::read_string('database_ssl_ca_path');
  1403. $options[PDO::MYSQL_ATTR_SSL_CERT] = Config::read_string('database_ssl_cert');
  1404. $options[PDO::MYSQL_ATTR_SSL_CIPHER] = Config::read_string('database_ssl_cipher');
  1405. $options = array_filter($options); // remove empty settings.
  1406. $verify = Config::read('database_ssl_verify_server_cert');
  1407. if ($verify === null) { // undefined
  1408. $verify = true;
  1409. }
  1410. $options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = (bool)$verify;
  1411. }
  1412. $queries[] = 'SET CHARACTER SET utf8';
  1413. $queries[] = "SET COLLATION_CONNECTION='utf8_general_ci'";
  1414. } elseif (db_sqlite()) {
  1415. $db = $CONF['database_name'];
  1416. if (!file_exists($db)) {
  1417. $error_text = 'SQLite database missing: '. $db;
  1418. throw new Exception($error_text);
  1419. }
  1420. if (!is_writeable($db)) {
  1421. $error_text = 'SQLite database not writeable: '. $db;
  1422. throw new Exception($error_text);
  1423. }
  1424. if (!is_writeable(dirname($db))) {
  1425. $error_text = 'The directory the SQLite database is in is not writeable: '. dirname($db);
  1426. throw new Exception($error_text);
  1427. }
  1428. $dsn = "sqlite:{$db}";
  1429. $username_password = false;
  1430. } elseif (db_pgsql()) {
  1431. $dsn = "pgsql:dbname={$CONF['database_name']}";
  1432. if (isset($CONF['database_host'])) {
  1433. $dsn .= ";host={$CONF['database_host']}";
  1434. }
  1435. if (isset($CONF['database_port'])) {
  1436. $dsn .= ";port={$CONF['database_port']}";
  1437. }
  1438. $dsn .= ";options='-c client_encoding=utf8'";
  1439. } else {
  1440. throw new Exception("<p style='color: red'>FATAL Error:<br />Invalid \$CONF['database_type']! Please fix your config.inc.php!</p>");
  1441. }
  1442. if ($username_password) {
  1443. $link = new PDO($dsn, Config::read_string('database_user'), Config::read_string('database_password'), $options);
  1444. } else {
  1445. $link = new PDO($dsn, null, null, $options);
  1446. }
  1447. if (!empty($queries)) {
  1448. foreach ($queries as $q) {
  1449. $link->exec($q);
  1450. }
  1451. }
  1452. return $link;
  1453. }
  1454. /**
  1455. * Returns the appropriate boolean value for the database.
  1456. *
  1457. * @param bool|string $bool
  1458. * @return string|int as appropriate for underlying db platform
  1459. */
  1460. function db_get_boolean($bool) {
  1461. if (! (is_bool($bool) || $bool == '0' || $bool == '1')) {
  1462. error_log("Invalid usage of 'db_get_boolean($bool)'");
  1463. throw new Exception("Invalid usage of 'db_get_boolean($bool)'");
  1464. }
  1465. if (db_pgsql()) {
  1466. // return either true or false (unquoted strings)
  1467. if ($bool) {
  1468. return 't';
  1469. }
  1470. return 'f';
  1471. } elseif (db_mysql() || db_sqlite()) {
  1472. if ($bool) {
  1473. return 1;
  1474. }
  1475. return 0;
  1476. } else {
  1477. throw new Exception('Unknown value in $CONF[database_type]');
  1478. }
  1479. }
  1480. /**
  1481. * Returns a query that reports the used quota ("x / y")
  1482. * @param string column containing used quota
  1483. * @param string column containing allowed quota
  1484. * @param string column that will contain "x / y"
  1485. * @return string
  1486. */
  1487. function db_quota_text($count, $quota, $fieldname) {
  1488. if (db_pgsql() || db_sqlite()) {
  1489. // SQLite and PostgreSQL use || to concatenate strings
  1490. return " CASE $quota
  1491. WHEN '-1' THEN (coalesce($count,0) || ' / -')
  1492. WHEN '0' THEN (coalesce($count,0) || ' / " . escape_string(html_entity_decode('&infin;')) . "')
  1493. ELSE (coalesce($count,0) || ' / ' || $quota)
  1494. END AS $fieldname";
  1495. } else {
  1496. return " CASE $quota
  1497. WHEN '-1' THEN CONCAT(coalesce($count,0), ' / -')
  1498. WHEN '0' THEN CONCAT(coalesce($count,0), ' / ', '" . escape_string(html_entity_decode('&infin;')) . "')
  1499. ELSE CONCAT(coalesce($count,0), ' / ', $quota)
  1500. END AS $fieldname";
  1501. }
  1502. }
  1503. /**
  1504. * Returns a query that reports the used quota ("x / y")
  1505. * @param string column containing used quota
  1506. * @param string column containing allowed quota
  1507. * @param string column that will contain "x / y"
  1508. * @return string
  1509. */
  1510. function db_quota_percent($count, $quota, $fieldname) {
  1511. return " CASE $quota
  1512. WHEN '-1' THEN -1
  1513. WHEN '0' THEN -1
  1514. ELSE round(100 * coalesce($count,0) / $quota)
  1515. END AS $fieldname";
  1516. }
  1517. /**
  1518. * @return boolean true if it's a MySQL database variant.
  1519. */
  1520. function db_mysql() {
  1521. $type = Config::Read('database_type');
  1522. if ($type == 'mysql' || $type == 'mysqli') {
  1523. return true;
  1524. }
  1525. return false;
  1526. }
  1527. /**
  1528. * @return bool true if PostgreSQL is used, false otherwise
  1529. */
  1530. function db_pgsql() {
  1531. return Config::read_string('database_type') == 'pgsql';
  1532. }
  1533. /**
  1534. * returns true if SQLite is used, false otherwise
  1535. */
  1536. function db_sqlite() {
  1537. if (Config::Read('database_type')=='sqlite') {
  1538. return true;
  1539. } else {
  1540. return false;
  1541. }
  1542. }
  1543. /**
  1544. * @param string $sql
  1545. * @param array $values
  1546. * @return array
  1547. */
  1548. function db_query_all($sql, array $values = []) {
  1549. $r = db_query($sql, $values);
  1550. return $r['result']->fetchAll(PDO::FETCH_ASSOC);
  1551. }
  1552. /**
  1553. * @param string $sql
  1554. * @param array $values
  1555. * @return array
  1556. */
  1557. function db_query_one($sql, array $values = []) {
  1558. $r = db_query($sql, $values);
  1559. return $r['result']->fetch(PDO::FETCH_ASSOC);
  1560. }
  1561. /**
  1562. * @param string $sql e.g. UPDATE foo SET bar = :baz
  1563. * @param array $values - parameters for the prepared statement e.g. ['baz' => 1234]
  1564. * @param bool $throw_exceptions
  1565. * @return int number of rows affected by the query
  1566. */
  1567. function db_execute($sql, array $values = [], $throw_exceptions = false) {
  1568. $link = db_connect();
  1569. try {
  1570. $stmt = $link->prepare($sql);
  1571. $stmt->execute($values);
  1572. } catch (PDOException $e) {
  1573. $error_text = "Invalid query: " . $e->getMessage() . " caused by " . $sql ;
  1574. error_log($error_text);
  1575. if ($throw_exceptions) {
  1576. throw $e;
  1577. }
  1578. return 0;
  1579. }
  1580. return $stmt->rowCount();
  1581. }
  1582. /**
  1583. * @param string $sql
  1584. * @param array $values
  1585. * @param bool $ignore_errors - set to true to ignore errors.
  1586. * @return array e.g. ['result' => PDOStatement, 'error' => string ]
  1587. */
  1588. function db_query($sql, array $values = array(), $ignore_errors = false) {
  1589. $link = db_connect();
  1590. $error_text = '';
  1591. $stmt = null;
  1592. try {
  1593. $stmt = $link->prepare($sql);
  1594. $stmt->execute($values);
  1595. } catch (PDOException $e) {
  1596. $error_text = "Invalid query: " . $e->getMessage() . " caused by " . $sql ;
  1597. error_log($error_text);
  1598. if (defined('PHPUNIT_TEST')) {
  1599. throw new Exception("SQL query failed: {{{$sql}}} with " . json_encode($values) . ". Error message: " . $e->getMessage());
  1600. }
  1601. if (!$ignore_errors) {
  1602. throw new Exception("DEBUG INFORMATION: " . $e->getMessage() . "<br/> Check your error_log for the failed query");
  1603. }
  1604. }
  1605. return array(
  1606. "result" => $stmt,
  1607. "error" => $error_text,
  1608. );
  1609. }
  1610. /**
  1611. * Delete a row from the specified table.
  1612. *
  1613. * DELETE FROM $table WHERE $where = $delete $aditionalWhere
  1614. *
  1615. * @param string $table
  1616. * @param string $where - should never be a user supplied value
  1617. * @param string $delete
  1618. * @param string $additionalwhere (default '').
  1619. * @return int|mixed rows deleted.
  1620. */
  1621. function db_delete($table, $where, $delete, $additionalwhere='') {
  1622. $table = table_by_key($table);
  1623. $query = "DELETE FROM $table WHERE $where = ? $additionalwhere";
  1624. return db_execute($query, array($delete));
  1625. }
  1626. /**
  1627. * db_insert
  1628. * Action: Inserts a row from a specified table
  1629. * Call: db_insert (string table, array values [, array timestamp])
  1630. *
  1631. * @param string - table name
  1632. * @param array $values - key/value map of data to insert into the table.
  1633. * @param array $timestamp (optional) - array of fields to set to now() - default: array('created', 'modified')
  1634. * @param boolean $throw_exceptions
  1635. * @return int - number of inserted rows
  1636. */
  1637. function db_insert($table, array $values, $timestamp = array('created', 'modified'), $throw_exceptions = false) {
  1638. $table = table_by_key($table);
  1639. foreach ($timestamp as $key) {
  1640. if (db_sqlite()) {
  1641. $values[$key] = "datetime('now')";
  1642. } else {
  1643. $values[$key] = "now()";
  1644. }
  1645. }
  1646. $value_string = '';
  1647. $comma = '';
  1648. $prepared_statment_values = $values;
  1649. foreach ($values as $field => $value) {
  1650. if (in_array($field, $timestamp)) {
  1651. $value_string .= $comma . $value; // see above.
  1652. unset($prepared_statment_values[$field]);
  1653. } else {
  1654. $value_string .= $comma . ":{$field}";
  1655. }
  1656. $comma = ',';
  1657. }
  1658. return db_execute(
  1659. "INSERT INTO $table (" . implode(",", array_keys($values)) .") VALUES ($value_string)",
  1660. $prepared_statment_values,
  1661. $throw_exceptions);
  1662. }
  1663. /**
  1664. * db_update
  1665. * Action: Updates a specified table
  1666. * Call: db_update (string table, string where_col, string where_value, array values [, array timestamp])
  1667. * @param string $table - table name
  1668. * @param string $where_col - column of WHERE condition
  1669. * @param string $where_value - value of WHERE condition
  1670. * @param array $values - key/value map of data to insert into the table.
  1671. * @param array $timestamp (optional) - array of fields to set to now() - default: array('modified')
  1672. * @return int - number of updated rows
  1673. */
  1674. function db_update($table, $where_col, $where_value, $values, $timestamp = array('modified'), $throw_exceptions = false) {
  1675. $table_key = table_by_key($table);
  1676. $sql = "UPDATE $table_key SET ";
  1677. $pvalues = array();
  1678. $set = array();
  1679. foreach ($values as $key => $value) {
  1680. if (in_array($key, $timestamp)) {
  1681. if (db_sqlite()) {
  1682. $set[] = " $key = datetime('now') ";
  1683. } else {
  1684. $set[] = " $key = now() ";
  1685. }
  1686. } else {
  1687. $set[] = " $key = :$key ";
  1688. $pvalues[$key] = $value;
  1689. }
  1690. }
  1691. $pvalues['where'] = $where_value;
  1692. $sql="UPDATE $table_key SET " . implode(",", $set) . " WHERE $where_col = :where";
  1693. return db_execute($sql, $pvalues, $throw_exceptions);
  1694. }
  1695. /**
  1696. * db_log
  1697. * Action: Logs actions from admin
  1698. * Call: db_log (string domain, string action, string data)
  1699. * Possible actions are defined in $LANG["pViewlog_action_$action"]
  1700. */
  1701. function db_log($domain, $action, $data) {
  1702. if (!Config::bool('logging')) {
  1703. return true;
  1704. }
  1705. $REMOTE_ADDR = getRemoteAddr();
  1706. $username = authentication_get_username();
  1707. if (Config::Lang("pViewlog_action_$action") == '') {
  1708. throw new Exception("Invalid log action : $action"); // could do with something better?
  1709. }
  1710. $logdata = array(
  1711. 'username' => "$username ($REMOTE_ADDR)",
  1712. 'domain' => $domain,
  1713. 'action' => $action,
  1714. 'data' => $data,
  1715. );
  1716. $result = db_insert('log', $logdata, array('timestamp'));
  1717. if ($result != 1) {
  1718. return false;
  1719. } else {
  1720. return true;
  1721. }
  1722. }
  1723. /**
  1724. * db_in_clause
  1725. * Action: builds and returns the "field in(x, y)" clause for database queries
  1726. * Call: db_in_clause (string field, array values)
  1727. * @param string $field
  1728. * @param array $values
  1729. * @return string
  1730. */
  1731. function db_in_clause($field, array $values) {
  1732. $v = array_map('escape_string', array_values($values));
  1733. return " $field IN ('" . implode("','", $v) . "') ";
  1734. }
  1735. /**
  1736. * db_where_clause
  1737. * Action: builds and returns a WHERE clause for database queries. All given conditions will be AND'ed.
  1738. * Call: db_where_clause (array $conditions, array $struct)
  1739. * @param array $condition - array('field' => 'value', 'field2' => 'value2, ...)
  1740. * @param array $struct - field structure, used for automatic bool conversion
  1741. * @param string $additional_raw_where - raw sniplet to include in the WHERE part - typically needs to start with AND
  1742. * @param array $searchmode - operators to use (=, <, > etc.) - defaults to = if not specified for a field (see
  1743. * $allowed_operators for available operators)
  1744. * Note: the $searchmode operator will only be used if a $condition for that field is set.
  1745. * This also means you'll need to set a (dummy) condition for NULL and NOTNULL.
  1746. */
  1747. function db_where_clause(array $condition, array $struct, $additional_raw_where = '', array $searchmode = array()) {
  1748. if (count($condition) == 0 && trim($additional_raw_where) == '') {
  1749. throw new Exception("db_where_cond: parameter is an empty array!");
  1750. }
  1751. $allowed_operators = array('<', '>', '>=', '<=', '=', '!=', '<>', 'CONT', 'LIKE', 'NULL', 'NOTNULL');
  1752. $where_parts = array();
  1753. $having_parts = array();
  1754. foreach ($condition as $field => $value) {
  1755. if (isset($struct[$field]) && $struct[$field]['type'] == 'bool') {
  1756. $value = db_get_boolean($value);
  1757. }
  1758. $operator = '=';
  1759. if (isset($searchmode[$field])) {
  1760. if (in_array($searchmode[$field], $allowed_operators)) {
  1761. $operator = $searchmode[$field];
  1762. if ($operator == 'CONT') { # CONT - as in "contains"
  1763. $operator = ' LIKE '; # add spaces
  1764. $value = '%' . $value . '%';
  1765. } elseif ($operator == 'LIKE') { # LIKE -without adding % wildcards (the search value can contain %)
  1766. $operator = ' LIKE '; # add spaces
  1767. }
  1768. } else {
  1769. throw new Exception('db_where_clause: Invalid searchmode for ' . $field);
  1770. }
  1771. }
  1772. if ($operator == "NULL") {
  1773. $querypart = $field . ' IS NULL';
  1774. } elseif ($operator == "NOTNULL") {
  1775. $querypart = $field . ' IS NOT NULL';
  1776. } else {
  1777. $querypart = $field . $operator . "'" . escape_string($value) . "'";
  1778. // might need other types adding here.
  1779. if (db_pgsql() && isset($struct[$field]) && in_array($struct[$field]['type'], array('ts', 'num')) && $value === '') {
  1780. $querypart = $field . $operator . " NULL";
  1781. }
  1782. }
  1783. if (!empty($struct[$field]['select'])) {
  1784. $having_parts[$field] = $querypart;
  1785. } else {
  1786. $where_parts[$field] = $querypart;
  1787. }
  1788. }
  1789. $query = ' WHERE 1=1 ';
  1790. $query .= " $additional_raw_where ";
  1791. if (count($where_parts) > 0) {
  1792. $query .= " AND ( " . join(" AND ", $where_parts) . " ) ";
  1793. }
  1794. if (count($having_parts) > 0) {
  1795. $query .= " HAVING ( " . join(" AND ", $having_parts) . " ) ";
  1796. }
  1797. return $query;
  1798. }
  1799. /**
  1800. * Convert a programmatic db table name into what may be the actual name.
  1801. *
  1802. * Takes into consideration any CONF database_prefix or database_tables map
  1803. *
  1804. * If it's a MySQL database, then we return the name with backticks around it (`).
  1805. *
  1806. * @param string database table name.
  1807. * @return string - database table name with appropriate prefix (and quoting if MySQL)
  1808. */
  1809. function table_by_key($table_key) {
  1810. global $CONF;
  1811. $table = $table_key;
  1812. if (!empty($CONF['database_tables'][$table_key])) {
  1813. $table = $CONF['database_tables'][$table_key];
  1814. }
  1815. $table = $CONF['database_prefix'] . $table;
  1816. if (db_mysql()) {
  1817. return "`" . $table . "`";
  1818. }
  1819. return $table;
  1820. }
  1821. /**
  1822. * check if the database layout is up to date
  1823. * returns the current 'version' value from the config table
  1824. * if $error_out is True (default), exit(1) with a message that recommends to run setup.php.
  1825. * @param bool $error_out
  1826. * @return int
  1827. */
  1828. function check_db_version($error_out = true) {
  1829. global $min_db_version;
  1830. $table = table_by_key('config');
  1831. $sql = "SELECT value FROM $table WHERE name = 'version'";
  1832. $row = db_query_one($sql);
  1833. if (isset($row['value'])) {
  1834. $dbversion = (int) $row['value'];
  1835. } else {
  1836. db_execute("INSERT INTO $table (name, value) VALUES ('version', '0')");
  1837. $dbversion = 0;
  1838. }
  1839. if (($dbversion < $min_db_version) && $error_out == true) {
  1840. echo "ERROR: The PostfixAdmin database layout is outdated (you have r$dbversion, but r$min_db_version is expected).\nPlease run setup.php to upgrade the database.\n";
  1841. exit(1);
  1842. }
  1843. return $dbversion;
  1844. }
  1845. /**
  1846. *
  1847. * Action: Return a string of colored &nbsp;'s that indicate
  1848. * the if an alias goto has an error or is sent to
  1849. * addresses list in show_custom_domains
  1850. *
  1851. * @param string $show_alias
  1852. * @return string
  1853. */
  1854. function gen_show_status($show_alias) {
  1855. global $CONF;
  1856. $table_alias = table_by_key('alias');
  1857. $stat_string = "";
  1858. $stat_goto = "";
  1859. $stat_result = db_query_one("SELECT goto FROM $table_alias WHERE address=?", array($show_alias));
  1860. if ($stat_result) {
  1861. $stat_goto = $stat_result['goto'];
  1862. }
  1863. $delimiter_regex = null;
  1864. if (!empty($CONF['recipient_delimiter'])) {
  1865. $delimiter = preg_quote($CONF['recipient_delimiter'], "/");
  1866. $delimiter_regex = '/' .$delimiter. '[^' .$delimiter. '@]*@/';
  1867. }
  1868. // UNDELIVERABLE CHECK
  1869. if ($CONF['show_undeliverable'] == 'YES') {
  1870. $gotos=array();
  1871. $gotos=explode(',', $stat_goto);
  1872. $undel_string="";
  1873. //make sure this alias goes somewhere known
  1874. $stat_ok = 1;
  1875. foreach ($gotos as $g) {
  1876. if (!$stat_ok) {
  1877. break;
  1878. }
  1879. if (strpos($g, '@') === false) {
  1880. continue;
  1881. }
  1882. list($local_part, $stat_domain) = explode('@', $g);
  1883. $v = array();
  1884. $stat_delimiter = "";
  1885. $sql = "SELECT address FROM $table_alias WHERE address = ? OR address = ?";
  1886. $v[] = $g;
  1887. $v[] = '@' . $stat_domain;
  1888. if (!empty($CONF['recipient_delimiter']) && isset($delimiter_regex)) {
  1889. $v[] = preg_replace($delimiter_regex, "@", $g);
  1890. $sql .= " OR address = ? ";
  1891. }
  1892. $stat_result = db_query_one($sql, $v);
  1893. if (empty($stat_result)) {
  1894. $stat_ok = 0;
  1895. }
  1896. if ($stat_ok == 0) {
  1897. if ($stat_domain == $CONF['vacation_domain'] || in_array($stat_domain, $CONF['show_undeliverable_exceptions'])) {
  1898. $stat_ok = 1;
  1899. }
  1900. }
  1901. } // while
  1902. if ($stat_ok == 0) {
  1903. $stat_string .= "<span style='background-color:" . $CONF['show_undeliverable_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1904. } else {
  1905. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1906. }
  1907. }
  1908. // Vacation CHECK
  1909. if ( array_key_exists('show_vacation', $CONF) && $CONF['show_vacation'] == 'YES' ) {
  1910. $stat_result = db_query_one("SELECT * FROM ". table_by_key('vacation') ." WHERE email = ? AND active = ? ", array($show_alias, db_get_boolean(true) )) ;
  1911. if (!empty($stat_result)) {
  1912. $stat_string .= "<span style='background-color:" . $CONF['show_vacation_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1913. } else {
  1914. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1915. }
  1916. }
  1917. // Disabled CHECK
  1918. if ( array_key_exists('show_disabled', $CONF) && $CONF['show_disabled'] == 'YES' ) {
  1919. $stat_result = db_query_one(
  1920. "SELECT * FROM ". table_by_key('mailbox') ." WHERE username = ? AND active = ?",
  1921. array($show_alias, db_get_boolean(false))
  1922. );
  1923. if (!empty($stat_result)) {
  1924. $stat_string .= "<span style='background-color:" . $CONF['show_disabled_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1925. } else {
  1926. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1927. }
  1928. }
  1929. // Expired CHECK
  1930. if (Config::has('password_expiration') && Config::bool('password_expiration') && Config::bool('show_expired')) {
  1931. $now = 'now()';
  1932. if (db_sqlite()) {
  1933. $now = "datetime('now')";
  1934. }
  1935. $stat_result = db_query_one("SELECT * FROM " . table_by_key('mailbox') . " WHERE username = ? AND password_expiry <= $now AND active = ?", array($show_alias, db_get_boolean(true)));
  1936. if (!empty($stat_result)) {
  1937. $stat_string .= "<span style='background-color:" . $CONF['show_expired_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1938. } else {
  1939. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1940. }
  1941. }
  1942. // POP/IMAP CHECK
  1943. if ($CONF['show_popimap'] == 'YES') {
  1944. $stat_delimiter = "";
  1945. if (!empty($CONF['recipient_delimiter']) && isset($delimiter_regex)) {
  1946. $stat_delimiter = ',' . preg_replace($delimiter_regex, "@", $stat_goto);
  1947. }
  1948. //if the address passed in appears in its own goto field, its POP/IMAP
  1949. # TODO: or not (might also be an alias loop) -> check mailbox table!
  1950. if (preg_match('/,' . $show_alias . ',/', ',' . $stat_goto . $stat_delimiter . ',')) {
  1951. $stat_string .= "<span style='background-color:" . $CONF['show_popimap_color'] .
  1952. "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1953. } else {
  1954. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1955. }
  1956. }
  1957. // CUSTOM DESTINATION CHECK
  1958. if (count($CONF['show_custom_domains']) > 0) {
  1959. for ($i = 0; $i < sizeof($CONF['show_custom_domains']); $i++) {
  1960. if (preg_match('/^.*' . $CONF['show_custom_domains'][$i] . '.*$/', $stat_goto)) {
  1961. $stat_string .= "<span style='background-color:" . $CONF['show_custom_colors'][$i] .
  1962. "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1963. } else {
  1964. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1965. }
  1966. }
  1967. } else {
  1968. $stat_string .= ";&nbsp;";
  1969. }
  1970. // $stat_string .= "<span style='background-color:green'> &nbsp; </span> &nbsp;" .
  1971. // "<span style='background-color:blue'> &nbsp; </span> &nbsp;";
  1972. return $stat_string;
  1973. }
  1974. /**
  1975. * @return string
  1976. */
  1977. function getRemoteAddr() {
  1978. $REMOTE_ADDR = 'localhost';
  1979. if (isset($_SERVER['REMOTE_ADDR'])) {
  1980. $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
  1981. }
  1982. return $REMOTE_ADDR;
  1983. }
  1984. /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */