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.

2210 lines
71 KiB

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