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.

2214 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 r $querypart
  486. ) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $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 r
  495. FROM idx t2
  496. WHERE (r % $page_size) IN (0,$page_size_zerobase) OR r = $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. if (!is_array($val_conf)) {
  769. $val_conf = [];
  770. }
  771. $minlen = (int) Config::read('min_password_length'); # used up to 2.3.x - check it for backward compatibility
  772. if ($minlen > 0) {
  773. $val_conf['/.{' . $minlen . '}/'] = "password_too_short $minlen";
  774. }
  775. foreach ($val_conf as $regex => $message) {
  776. if (!preg_match($regex, $password)) {
  777. $msgparts = preg_split("/ /", $message, 2);
  778. if (count($msgparts) == 1) {
  779. $result[] = Config::lang($msgparts[0]);
  780. } else {
  781. $result[] = sprintf(Config::lang($msgparts[0]), $msgparts[1]);
  782. }
  783. }
  784. }
  785. return $result;
  786. }
  787. function _pacrypt_md5crypt($pw, $pw_db) {
  788. $split_salt = preg_split('/\$/', $pw_db);
  789. if (isset($split_salt[2])) {
  790. $salt = $split_salt[2];
  791. return md5crypt($pw, $salt);
  792. }
  793. return md5crypt($pw);
  794. }
  795. function _pacrypt_crypt($pw, $pw_db) {
  796. if ($pw_db) {
  797. return crypt($pw, $pw_db);
  798. }
  799. return crypt($pw);
  800. }
  801. function _pacrypt_mysql_encrypt($pw, $pw_db) {
  802. // See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583
  803. // this is apparently useful for pam_mysql etc.
  804. $pw = escape_string($pw);
  805. if ($pw_db!="") {
  806. $salt=escape_string(substr($pw_db, 0, 2));
  807. $res=db_query("SELECT ENCRYPT('".$pw."','".$salt."');");
  808. } else {
  809. $res=db_query("SELECT ENCRYPT('".$pw."');");
  810. }
  811. $l = db_row($res["result"]);
  812. $password = $l[0];
  813. return $password;
  814. }
  815. function _pacrypt_authlib($pw, $pw_db) {
  816. global $CONF;
  817. $flavor = $CONF['authlib_default_flavor'];
  818. $salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts
  819. if (preg_match('/^{.*}/', $pw_db)) {
  820. // we have a flavor in the db -> use it instead of default flavor
  821. $result = preg_split('/[{}]/', $pw_db, 3); # split at { and/or }
  822. $flavor = $result[1];
  823. $salt = substr($result[2], 0, 2);
  824. }
  825. if (stripos($flavor, 'md5raw') === 0) {
  826. $password = '{' . $flavor . '}' . md5($pw);
  827. } elseif (stripos($flavor, 'md5') === 0) {
  828. $password = '{' . $flavor . '}' . base64_encode(md5($pw, true));
  829. } elseif (stripos($flavor, 'crypt') === 0) {
  830. $password = '{' . $flavor . '}' . crypt($pw, $salt);
  831. } elseif (stripos($flavor, 'SHA') === 0) {
  832. $password = '{' . $flavor . '}' . base64_encode(sha1($pw, true));
  833. } else {
  834. die("authlib_default_flavor '" . $flavor . "' unknown. Valid flavors are 'md5raw', 'md5', 'SHA' and 'crypt'");
  835. }
  836. return $password;
  837. }
  838. /**
  839. * @param string $pw - plain text password
  840. * @param string $pw_db - encrypted password, or '' for generation.
  841. * @return string
  842. */
  843. function _pacrypt_dovecot($pw, $pw_db) {
  844. global $CONF;
  845. $split_method = preg_split('/:/', $CONF['encrypt']);
  846. $method = strtoupper($split_method[1]);
  847. # If $pw_db starts with {method}, change $method accordingly
  848. if (!empty($pw_db) && preg_match('/^\{([A-Z0-9.-]+)\}.+/', $pw_db, $method_matches)) {
  849. $method = $method_matches[1];
  850. }
  851. if (! preg_match("/^[A-Z0-9.-]+$/", $method)) {
  852. die("invalid dovecot encryption method");
  853. }
  854. # TODO: check against a fixed list?
  855. # 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.");
  856. # $crypt_method = preg_match ("/.*-CRYPT$/", $method);
  857. # digest-md5 and SCRAM-SHA-1 hashes include the username - until someone implements it, let's declare it as unsupported
  858. if (strtolower($method) == 'digest-md5') {
  859. die("Sorry, \$CONF['encrypt'] = 'dovecot:digest-md5' is not supported by PostfixAdmin.");
  860. }
  861. if (strtoupper($method) == 'SCRAM-SHA-1') {
  862. die("Sorry, \$CONF['encrypt'] = 'dovecot:scram-sha-1' is not supported by PostfixAdmin.");
  863. }
  864. # 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)
  865. $dovecotpw = "doveadm pw";
  866. if (!empty($CONF['dovecotpw'])) {
  867. $dovecotpw = $CONF['dovecotpw'];
  868. }
  869. # Use proc_open call to avoid safe_mode problems and to prevent showing plain password in process table
  870. $spec = array(
  871. 0 => array("pipe", "r"), // stdin
  872. 1 => array("pipe", "w"), // stdout
  873. 2 => array("pipe", "w"), // stderr
  874. );
  875. $nonsaltedtypes = "SHA|SHA1|SHA256|SHA512|CLEAR|CLEARTEXT|PLAIN|PLAIN-TRUNC|CRAM-MD5|HMAC-MD5|PLAIN-MD4|PLAIN-MD5|LDAP-MD5|LANMAN|NTLM|RPA";
  876. $salted = ! preg_match("/^($nonsaltedtypes)(\.B64|\.BASE64|\.HEX)?$/", strtoupper($method));
  877. $dovepasstest = '';
  878. if ($salted && (!empty($pw_db))) {
  879. # only use -t for salted passwords to be backward compatible with dovecot < 2.1
  880. $dovepasstest = " -t " . escapeshellarg($pw_db);
  881. }
  882. $pipe = proc_open("$dovecotpw '-s' $method$dovepasstest", $spec, $pipes);
  883. if (!$pipe) {
  884. die("can't proc_open $dovecotpw");
  885. }
  886. // use dovecot's stdin, it uses getpass() twice (except when using -t)
  887. // Write pass in pipe stdin
  888. if (empty($dovepasstest)) {
  889. fwrite($pipes[0], $pw . "\n", 1+strlen($pw));
  890. usleep(1000);
  891. }
  892. fwrite($pipes[0], $pw . "\n", 1+strlen($pw));
  893. fclose($pipes[0]);
  894. // Read hash from pipe stdout
  895. $password = fread($pipes[1], "200");
  896. if (empty($dovepasstest)) {
  897. if (!preg_match('/^\{' . $method . '\}/', $password)) {
  898. $stderr_output = stream_get_contents($pipes[2]);
  899. error_log('dovecotpw password encryption failed. STDERR output: '. $stderr_output);
  900. die("can't encrypt password with dovecotpw, see error log for details");
  901. }
  902. } else {
  903. if (!preg_match('(verified)', $password)) {
  904. $password="Thepasswordcannotbeverified";
  905. } else {
  906. $password = rtrim(str_replace('(verified)', '', $password));
  907. }
  908. }
  909. fclose($pipes[1]);
  910. fclose($pipes[2]);
  911. proc_close($pipe);
  912. if ((!empty($pw_db)) && (substr($pw_db, 0, 1) != '{')) {
  913. # for backward compability with "old" dovecot passwords that don't have the {method} prefix
  914. $password = str_replace('{' . $method . '}', '', $password);
  915. }
  916. return rtrim($password);
  917. }
  918. /**
  919. * @param string $pw
  920. * @param string $pw_db (can be empty if setting a new password)
  921. * @return string
  922. */
  923. function _pacrypt_php_crypt($pw, $pw_db) {
  924. global $CONF;
  925. // use PHPs crypt(), which uses the system's crypt()
  926. // same algorithms as used in /etc/shadow
  927. // you can have mixed hash types in the database for authentication, changed passwords get specified hash type
  928. // the algorithm for a new hash is chosen by feeding a salt with correct magic to crypt()
  929. // set $CONF['encrypt'] to 'php_crypt' to use the default SHA512 crypt method
  930. // set $CONF['encrypt'] to 'php_crypt:METHOD' to use another method; methods supported: DES, MD5, BLOWFISH, SHA256, SHA512
  931. // tested on linux
  932. if (strlen($pw_db) > 0) {
  933. // existing pw provided. send entire password hash as salt for crypt() to figure out
  934. $salt = $pw_db;
  935. } else {
  936. $salt_method = 'SHA512'; // hopefully a reasonable default (better than MD5)
  937. // no pw provided. create new password hash
  938. if (strpos($CONF['encrypt'], ':') !== false) {
  939. // use specified hash method
  940. $split_method = explode(':', $CONF['encrypt']);
  941. $salt_method = $split_method[1];
  942. }
  943. // create appropriate salt for selected hash method
  944. $salt = _php_crypt_generate_crypt_salt($salt_method);
  945. }
  946. // send it to PHPs crypt()
  947. $password = crypt($pw, $salt);
  948. return $password;
  949. }
  950. /**
  951. * @param string $hash_type must be one of: MD5, DES, BLOWFISH, SHA256 or SHA512 (default)
  952. * @return string
  953. */
  954. function _php_crypt_generate_crypt_salt($hash_type='SHA512') {
  955. // generate a salt (with magic matching chosen hash algorithm) for the PHP crypt() function
  956. // most commonly used alphabet
  957. $alphabet = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  958. switch ($hash_type) {
  959. case 'DES':
  960. $alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  961. $length = 2;
  962. $salt = _php_crypt_random_string($alphabet, $length);
  963. return $salt;
  964. case 'MD5':
  965. $length = 12;
  966. $algorithm = '1';
  967. $salt = _php_crypt_random_string($alphabet, $length);
  968. return sprintf('$%s$%s', $algorithm, $salt);
  969. case 'BLOWFISH':
  970. $length = 22;
  971. $cost = 10;
  972. if (version_compare(PHP_VERSION, '5.3.7') >= 0) {
  973. $algorithm = '2y'; // bcrypt, with fixed unicode problem
  974. } else {
  975. $algorithm = '2a'; // bcrypt
  976. }
  977. $salt = _php_crypt_random_string($alphabet, $length);
  978. return sprintf('$%s$%02d$%s', $algorithm, $cost, $salt);
  979. case 'SHA256':
  980. $length = 16;
  981. $algorithm = '5';
  982. $salt = _php_crypt_random_string($alphabet, $length);
  983. return sprintf('$%s$%s', $algorithm, $salt);
  984. case 'SHA512':
  985. $length = 16;
  986. $algorithm = '6';
  987. $salt = _php_crypt_random_string($alphabet, $length);
  988. return sprintf('$%s$%s', $algorithm, $salt);
  989. default:
  990. die("unknown hash type: '$hash_type'");
  991. }
  992. }
  993. /**
  994. * Generates a random string of specified $length from $characters.
  995. * @param string $characters
  996. * @param int $length
  997. * @return string of given $length
  998. */
  999. function _php_crypt_random_string($characters, $length) {
  1000. $string = '';
  1001. for ($p = 0; $p < $length; $p++) {
  1002. $string .= $characters[random_int(0, strlen($characters) -1)];
  1003. }
  1004. return $string;
  1005. }
  1006. /**
  1007. * Encrypt a password, using the apparopriate hashing mechanism as defined in
  1008. * config.inc.php ($CONF['encrypt']).
  1009. * When wanting to compare one pw to another, it's necessary to provide the salt used - hence
  1010. * the second parameter ($pw_db), which is the existing hash from the DB.
  1011. *
  1012. * @param string $pw
  1013. * @param string $pw_db optional encrypted password
  1014. * @return string encrypted password.
  1015. */
  1016. function pacrypt($pw, $pw_db="") {
  1017. global $CONF;
  1018. switch ($CONF['encrypt']) {
  1019. case 'md5crypt':
  1020. return _pacrypt_md5crypt($pw, $pw_db);
  1021. case 'md5':
  1022. return md5($pw);
  1023. case 'system':
  1024. return _pacrypt_crypt($pw, $pw_db);
  1025. case 'cleartext':
  1026. return $pw;
  1027. case 'mysql_encrypt':
  1028. return _pacrypt_mysql_encrypt($pw, $pw_db);
  1029. case 'authlib':
  1030. return _pacrypt_authlib($pw, $pw_db);
  1031. }
  1032. if (preg_match("/^dovecot:/", $CONF['encrypt'])) {
  1033. return _pacrypt_dovecot($pw, $pw_db);
  1034. }
  1035. if (substr($CONF['encrypt'], 0, 9) === 'php_crypt') {
  1036. return _pacrypt_php_crypt($pw, $pw_db);
  1037. }
  1038. die('unknown/invalid $CONF["encrypt"] setting: ' . $CONF['encrypt']);
  1039. }
  1040. //
  1041. // md5crypt
  1042. // Action: Creates MD5 encrypted password
  1043. // Call: md5crypt (string cleartextpassword)
  1044. //
  1045. function md5crypt($pw, $salt="", $magic="") {
  1046. $MAGIC = "$1$";
  1047. if ($magic == "") {
  1048. $magic = $MAGIC;
  1049. }
  1050. if ($salt == "") {
  1051. $salt = create_salt();
  1052. }
  1053. $slist = explode("$", $salt);
  1054. if ($slist[0] == "1") {
  1055. $salt = $slist[1];
  1056. }
  1057. $salt = substr($salt, 0, 8);
  1058. $ctx = $pw . $magic . $salt;
  1059. $final = hex2bin(md5($pw . $salt . $pw));
  1060. for ($i=strlen($pw); $i>0; $i-=16) {
  1061. if ($i > 16) {
  1062. $ctx .= substr($final, 0, 16);
  1063. } else {
  1064. $ctx .= substr($final, 0, $i);
  1065. }
  1066. }
  1067. $i = strlen($pw);
  1068. while ($i > 0) {
  1069. if ($i & 1) {
  1070. $ctx .= chr(0);
  1071. } else {
  1072. $ctx .= $pw[0];
  1073. }
  1074. $i = $i >> 1;
  1075. }
  1076. $final = hex2bin(md5($ctx));
  1077. for ($i=0;$i<1000;$i++) {
  1078. $ctx1 = "";
  1079. if ($i & 1) {
  1080. $ctx1 .= $pw;
  1081. } else {
  1082. $ctx1 .= substr($final, 0, 16);
  1083. }
  1084. if ($i % 3) {
  1085. $ctx1 .= $salt;
  1086. }
  1087. if ($i % 7) {
  1088. $ctx1 .= $pw;
  1089. }
  1090. if ($i & 1) {
  1091. $ctx1 .= substr($final, 0, 16);
  1092. } else {
  1093. $ctx1 .= $pw;
  1094. }
  1095. $final = hex2bin(md5($ctx1));
  1096. }
  1097. $passwd = "";
  1098. $passwd .= to64(((ord($final[0]) << 16) | (ord($final[6]) << 8) | (ord($final[12]))), 4);
  1099. $passwd .= to64(((ord($final[1]) << 16) | (ord($final[7]) << 8) | (ord($final[13]))), 4);
  1100. $passwd .= to64(((ord($final[2]) << 16) | (ord($final[8]) << 8) | (ord($final[14]))), 4);
  1101. $passwd .= to64(((ord($final[3]) << 16) | (ord($final[9]) << 8) | (ord($final[15]))), 4);
  1102. $passwd .= to64(((ord($final[4]) << 16) | (ord($final[10]) << 8) | (ord($final[5]))), 4);
  1103. $passwd .= to64(ord($final[11]), 2);
  1104. return "$magic$salt\$$passwd";
  1105. }
  1106. function create_salt() {
  1107. srand((double) microtime()*1000000);
  1108. $salt = substr(md5(rand(0, 9999999)), 0, 8);
  1109. return $salt;
  1110. }
  1111. /**/ if (!function_exists('hex2bin')) { # PHP around 5.3.8 includes hex2bin as native function - http://php.net/hex2bin
  1112. function hex2bin($str) {
  1113. $len = strlen($str);
  1114. $nstr = "";
  1115. for ($i=0;$i<$len;$i+=2) {
  1116. $num = sscanf(substr($str, $i, 2), "%x");
  1117. $nstr.=chr($num[0]);
  1118. }
  1119. return $nstr;
  1120. }
  1121. /**/
  1122. }
  1123. /*
  1124. * remove item $item from array $array
  1125. */
  1126. function remove_from_array($array, $item) {
  1127. # array_diff might be faster, but doesn't provide an easy way to know if the value was found or not
  1128. # return array_diff($array, array($item));
  1129. $ret = array_search($item, $array);
  1130. if ($ret === false) {
  1131. $found = 0;
  1132. } else {
  1133. $found = 1;
  1134. unset($array[$ret]);
  1135. }
  1136. return array($found, $array);
  1137. }
  1138. function to64($v, $n) {
  1139. $ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1140. $ret = "";
  1141. while (($n - 1) >= 0) {
  1142. $n--;
  1143. $ret .= $ITOA64[$v & 0x3f];
  1144. $v = $v >> 6;
  1145. }
  1146. return $ret;
  1147. }
  1148. /**
  1149. * smtp_mail
  1150. * Action: Send email
  1151. * Call: smtp_mail (string to, string from, string subject, string body]) - or -
  1152. * Call: smtp_mail (string to, string from, string data) - DEPRECATED
  1153. * @param String - To:
  1154. * @param String - From:
  1155. * @param String - Subject: (if called with 4 parameters) or full mail body (if called with 3 parameters)
  1156. * @param String (optional, but recommended) - mail body
  1157. * @return bool - true on success, otherwise false
  1158. * TODO: Replace this with something decent like PEAR::Mail or Zend_Mail.
  1159. */
  1160. function smtp_mail($to, $from, $data, $body = "") {
  1161. global $CONF;
  1162. $smtpd_server = $CONF['smtp_server'];
  1163. $smtpd_port = $CONF['smtp_port'];
  1164. //$smtp_server = $_SERVER["SERVER_NAME"];
  1165. $smtp_server = php_uname('n');
  1166. if (!empty($CONF['smtp_client'])) {
  1167. $smtp_server = $CONF['smtp_client'];
  1168. }
  1169. $errno = "0";
  1170. $errstr = "0";
  1171. $timeout = "30";
  1172. if ($body != "") {
  1173. $maildata =
  1174. "To: " . $to . "\n"
  1175. . "From: " . $from . "\n"
  1176. . "Subject: " . encode_header($data) . "\n"
  1177. . "MIME-Version: 1.0\n"
  1178. . "Date: " . date('r') . "\n"
  1179. . "Content-Type: text/plain; charset=utf-8\n"
  1180. . "Content-Transfer-Encoding: 8bit\n"
  1181. . "\n"
  1182. . $body
  1183. ;
  1184. } else {
  1185. $maildata = $data;
  1186. }
  1187. $fh = @fsockopen($smtpd_server, $smtpd_port, $errno, $errstr, $timeout);
  1188. if (!$fh) {
  1189. error_log("fsockopen failed - errno: $errno - errstr: $errstr");
  1190. return false;
  1191. } else {
  1192. $res = smtp_get_response($fh);
  1193. fputs($fh, "EHLO $smtp_server\r\n");
  1194. $res = smtp_get_response($fh);
  1195. fputs($fh, "MAIL FROM:<$from>\r\n");
  1196. $res = smtp_get_response($fh);
  1197. fputs($fh, "RCPT TO:<$to>\r\n");
  1198. $res = smtp_get_response($fh);
  1199. fputs($fh, "DATA\r\n");
  1200. $res = smtp_get_response($fh);
  1201. fputs($fh, "$maildata\r\n.\r\n");
  1202. $res = smtp_get_response($fh);
  1203. fputs($fh, "QUIT\r\n");
  1204. $res = smtp_get_response($fh);
  1205. fclose($fh);
  1206. }
  1207. return true;
  1208. }
  1209. /**
  1210. * smtp_get_admin_email
  1211. * Action: Get configured email address or current user if nothing configured
  1212. * Call: smtp_get_admin_email
  1213. * @return String - username/mail address
  1214. */
  1215. function smtp_get_admin_email() {
  1216. $admin_email = Config::read('admin_email');
  1217. if (!empty($admin_email)) {
  1218. return $admin_email;
  1219. } else {
  1220. return authentication_get_username();
  1221. }
  1222. }
  1223. //
  1224. // smtp_get_response
  1225. // Action: Get response from mail server
  1226. // Call: smtp_get_response (string FileHandle)
  1227. //
  1228. function smtp_get_response($fh) {
  1229. $res ='';
  1230. do {
  1231. $line = fgets($fh, 256);
  1232. $res .= $line;
  1233. } while (preg_match("/^\d\d\d\-/", $line));
  1234. return $res;
  1235. }
  1236. $DEBUG_TEXT = "\n
  1237. <p />\n
  1238. Please check the documentation and website for more information.\n
  1239. <p />\n
  1240. <a href=\"http://postfixadmin.sf.net/\">Postfix Admin</a><br />\n
  1241. <a href='https://sourceforge.net/p/postfixadmin/discussion/676076'>Forums</a>
  1242. ";
  1243. /**
  1244. * db_connect
  1245. * Action: Makes a connection to the database if it doesn't exist
  1246. * Call: db_connect ()
  1247. * Optional parameter: $ignore_errors = TRUE, used by setup.php
  1248. *
  1249. * Return value:
  1250. * a) without $ignore_errors or $ignore_errors == 0
  1251. * - $link - the database connection -OR-
  1252. * - call die() in case of connection problems
  1253. * b) with $ignore_errors == TRUE
  1254. * array($link, $error_text);
  1255. *
  1256. * @return resource connection to db (normally)
  1257. */
  1258. function db_connect($ignore_errors = false) {
  1259. global $CONF;
  1260. global $DEBUG_TEXT;
  1261. if ($ignore_errors != 0) {
  1262. $DEBUG_TEXT = '';
  1263. }
  1264. $error_text = '';
  1265. static $link;
  1266. if (isset($link) && $link) {
  1267. if ($ignore_errors) {
  1268. return array($link, $error_text);
  1269. }
  1270. return $link;
  1271. }
  1272. $link = 0;
  1273. if ($CONF['database_type'] == "mysql") {
  1274. if (function_exists("mysql_connect")) {
  1275. $link = @mysql_connect($CONF['database_host'], $CONF['database_user'], $CONF['database_password']) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: " . mysql_error() . "$DEBUG_TEXT");
  1276. if ($link) {
  1277. @mysql_query("SET CHARACTER SET utf8", $link);
  1278. @mysql_query("SET COLLATION_CONNECTION='utf8_general_ci'", $link);
  1279. @mysql_select_db($CONF['database_name'], $link) or $error_text .= ("<p />DEBUG INFORMATION:<br />MySQL Select Database: " . mysql_error() . "$DEBUG_TEXT");
  1280. }
  1281. } else {
  1282. $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";
  1283. }
  1284. } elseif ($CONF['database_type'] == "mysqli") {
  1285. $is_connected = false;
  1286. if ($CONF['database_use_ssl']) {
  1287. if (function_exists("mysqli_real_connect")) {
  1288. $link = mysqli_init();
  1289. $link->ssl_set($CONF['database_ssl_key'], $CONF['database_ssl_cert'], $CONF['database_ssl_ca'], $CONF['database_ssl_ca_path'], $CONF['database_ssl_cipher']);
  1290. $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'));
  1291. $is_connected = $connected;
  1292. } else {
  1293. $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";
  1294. }
  1295. } else {
  1296. if (function_exists("mysqli_connect")) {
  1297. $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");
  1298. $is_connected = $link;
  1299. } else {
  1300. $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";
  1301. }
  1302. }
  1303. if ($is_connected) {
  1304. @mysqli_query($link, "SET CHARACTER SET utf8");
  1305. @mysqli_query($link, "SET COLLATION_CONNECTION='utf8_general_ci'");
  1306. }
  1307. } elseif (db_sqlite()) {
  1308. if (class_exists("SQLite3")) {
  1309. if ($CONF['database_name'] == '' || !is_dir(dirname($CONF['database_name'])) || !is_writable(dirname($CONF['database_name']))) {
  1310. $error_text .= ("<p />DEBUG INFORMATION<br />Connect: given database path does not exist, is not writable, or \$CONF['database_name'] is empty.");
  1311. } else {
  1312. $link = new SQLite3($CONF['database_name']) or $error_text .= ("<p />DEBUG INFORMATION<br />Connect: failed to connect to database. $DEBUG_TEXT");
  1313. $link->createFunction('base64_decode', 'base64_decode');
  1314. }
  1315. } else {
  1316. $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";
  1317. }
  1318. } elseif (db_pgsql()) {
  1319. if (function_exists("pg_pconnect")) {
  1320. if (!isset($CONF['database_port'])) {
  1321. $CONF['database_port'] = '5432';
  1322. }
  1323. $connect_string = "host=" . $CONF['database_host'] . " port=" . $CONF['database_port'] . " dbname=" . $CONF['database_name'] . " user=" . $CONF['database_user'] . " password=" . $CONF['database_password'];
  1324. $link = @pg_pconnect($connect_string) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: failed to connect to database. $DEBUG_TEXT");
  1325. if ($link) {
  1326. pg_set_client_encoding($link, 'UNICODE');
  1327. }
  1328. } else {
  1329. $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";
  1330. }
  1331. } else {
  1332. $error_text = "<p />DEBUG INFORMATION:<br />Invalid \$CONF['database_type']! Please fix your config.inc.php! $DEBUG_TEXT";
  1333. }
  1334. if ($ignore_errors) {
  1335. return array($link, $error_text);
  1336. } elseif ($error_text != "") {
  1337. print $error_text;
  1338. die();
  1339. } elseif ($link) {
  1340. return $link;
  1341. } else {
  1342. print "DEBUG INFORMATION:<br />\n";
  1343. print "Connect: Unable to connect to database<br />\n";
  1344. print "<br />\n";
  1345. print "Make sure that you have set the correct database type in the config.inc.php file<br />\n";
  1346. print $DEBUG_TEXT;
  1347. die();
  1348. }
  1349. }
  1350. /**
  1351. * Returns the appropriate boolean value for the database.
  1352. * @param boolean $bool (REQUIRED)
  1353. * @return string|int as appropriate for underlying db platform
  1354. */
  1355. function db_get_boolean($bool) {
  1356. if (! (is_bool($bool) || $bool == '0' || $bool == '1')) {
  1357. error_log("Invalid usage of 'db_get_boolean($bool)'");
  1358. die("Invalid usage of 'db_get_boolean($bool)'");
  1359. }
  1360. if (db_pgsql()) {
  1361. // return either true or false (unquoted strings)
  1362. if ($bool) {
  1363. return 't';
  1364. }
  1365. return 'f';
  1366. } elseif (Config::Read('database_type') == 'mysql' || Config::Read('database_type') == 'mysqli' || db_sqlite()) {
  1367. if ($bool) {
  1368. return 1;
  1369. }
  1370. return 0;
  1371. } else {
  1372. die('Unknown value in $CONF[database_type]');
  1373. }
  1374. }
  1375. /**
  1376. * Returns a query that reports the used quota ("x / y")
  1377. * @param string column containing used quota
  1378. * @param string column containing allowed quota
  1379. * @param string column that will contain "x / y"
  1380. * @return string
  1381. */
  1382. function db_quota_text($count, $quota, $fieldname) {
  1383. if (db_pgsql() || db_sqlite()) {
  1384. // SQLite and PostgreSQL use || to concatenate strings
  1385. return " CASE $quota
  1386. WHEN '-1' THEN (coalesce($count,0) || ' / -')
  1387. WHEN '0' THEN (coalesce($count,0) || ' / " . escape_string(html_entity_decode('&infin;')) . "')
  1388. ELSE (coalesce($count,0) || ' / ' || $quota)
  1389. END AS $fieldname";
  1390. } else {
  1391. return " CASE $quota
  1392. WHEN '-1' THEN CONCAT(coalesce($count,0), ' / -')
  1393. WHEN '0' THEN CONCAT(coalesce($count,0), ' / ', '" . escape_string(html_entity_decode('&infin;')) . "')
  1394. ELSE CONCAT(coalesce($count,0), ' / ', $quota)
  1395. END AS $fieldname";
  1396. }
  1397. }
  1398. /**
  1399. * Returns a query that reports the used quota ("x / y")
  1400. * @param string column containing used quota
  1401. * @param string column containing allowed quota
  1402. * @param string column that will contain "x / y"
  1403. * @return string
  1404. */
  1405. function db_quota_percent($count, $quota, $fieldname) {
  1406. return " CASE $quota
  1407. WHEN '-1' THEN -1
  1408. WHEN '0' THEN -1
  1409. ELSE round(100 * coalesce($count,0) / $quota)
  1410. END AS $fieldname";
  1411. }
  1412. /**
  1413. * @return boolean true if it's a MySQL database variant.
  1414. */
  1415. function db_mysql() {
  1416. $type = Config::Read('database_type');
  1417. if ($type == 'mysql' || $type == 'mysqli') {
  1418. return true;
  1419. }
  1420. return false;
  1421. }
  1422. /**
  1423. * returns true if PostgreSQL is used, false otherwise
  1424. */
  1425. function db_pgsql() {
  1426. if (Config::Read('database_type')=='pgsql') {
  1427. return true;
  1428. }
  1429. return false;
  1430. }
  1431. /**
  1432. * returns true if SQLite is used, false otherwise
  1433. */
  1434. function db_sqlite() {
  1435. if (Config::Read('database_type')=='sqlite') {
  1436. return true;
  1437. } else {
  1438. return false;
  1439. }
  1440. }
  1441. /**
  1442. * @param string $query SQL to execute
  1443. * @param int $ignore_errors (default 0 aka do not ignore errors)
  1444. * @return array ['result' => resource, 'rows' => int ,'error' => string]
  1445. */
  1446. function db_query($query, $ignore_errors = 0) {
  1447. global $CONF;
  1448. global $DEBUG_TEXT;
  1449. $result = "";
  1450. $number_rows = "";
  1451. $link = db_connect();
  1452. $error_text = "";
  1453. if ($ignore_errors) {
  1454. $DEBUG_TEXT = "";
  1455. }
  1456. if ($CONF['database_type'] == "mysql") {
  1457. $result = @mysql_query($query, $link)
  1458. or $error_text = "Invalid query: " . mysql_error($link);
  1459. }
  1460. if ($CONF['database_type'] == "mysqli") {
  1461. $result = @mysqli_query($link, $query)
  1462. or $error_text = "Invalid query: " . mysqli_error($link);
  1463. }
  1464. if (db_sqlite()) {
  1465. $result = @$link->query($query)
  1466. or $error_text = "Invalid query: " . $link->lastErrorMsg();
  1467. }
  1468. if (db_pgsql()) {
  1469. $result = @pg_query($link, $query)
  1470. or $error_text = "Invalid query: " . pg_last_error();
  1471. }
  1472. if ($error_text != "" && $ignore_errors == 0) {
  1473. error_log($error_text);
  1474. error_log("caused by query: $query");
  1475. die("<p />DEBUG INFORMATION:<br />$error_text <p>Check your error_log for the failed query. $DEBUG_TEXT");
  1476. }
  1477. if ($error_text == "") {
  1478. if (db_sqlite()) {
  1479. if ($result->numColumns()) {
  1480. // Query returned something
  1481. $num_rows = 0;
  1482. while (@$result->fetchArray(SQLITE3_ASSOC)) {
  1483. $num_rows++;
  1484. }
  1485. $result->reset();
  1486. $number_rows = $num_rows;
  1487. } else {
  1488. // Query was UPDATE, DELETE or INSERT
  1489. $number_rows = $link->changes();
  1490. }
  1491. } elseif (preg_match("/^SELECT/i", trim($query))) {
  1492. // if $query was a SELECT statement check the number of rows with [database_type]_num_rows ().
  1493. if ($CONF['database_type'] == "mysql") {
  1494. $number_rows = mysql_num_rows($result);
  1495. }
  1496. if ($CONF['database_type'] == "mysqli") {
  1497. $number_rows = mysqli_num_rows($result);
  1498. }
  1499. if (db_pgsql()) {
  1500. $number_rows = pg_num_rows($result);
  1501. }
  1502. } else {
  1503. // if $query was something else, UPDATE, DELETE or INSERT check the number of rows with
  1504. // [database_type]_affected_rows ().
  1505. if ($CONF['database_type'] == "mysql") {
  1506. $number_rows = mysql_affected_rows($link);
  1507. }
  1508. if ($CONF['database_type'] == "mysqli") {
  1509. $number_rows = mysqli_affected_rows($link);
  1510. }
  1511. if (db_pgsql()) {
  1512. $number_rows = pg_affected_rows($result);
  1513. }
  1514. }
  1515. }
  1516. $return = array(
  1517. "result" => $result,
  1518. "rows" => $number_rows,
  1519. "error" => $error_text
  1520. );
  1521. return $return;
  1522. }
  1523. // db_row
  1524. // Action: Returns a row from a table
  1525. // Call: db_row (int result)
  1526. function db_row($result) {
  1527. global $CONF;
  1528. $row = "";
  1529. if ($CONF['database_type'] == "mysql") {
  1530. $row = mysql_fetch_row($result);
  1531. }
  1532. if ($CONF['database_type'] == "mysqli") {
  1533. $row = mysqli_fetch_row($result);
  1534. }
  1535. if (db_sqlite()) {
  1536. $row = $result->fetchArray(SQLITE3_NUM);
  1537. }
  1538. if (db_pgsql()) {
  1539. $row = pg_fetch_row($result);
  1540. }
  1541. return $row;
  1542. }
  1543. /**
  1544. * Return array from a db resource (presumably not associative).
  1545. * @param resource $result
  1546. * @return array|null|string
  1547. */
  1548. function db_array($result) {
  1549. global $CONF;
  1550. $row = "";
  1551. if ($CONF['database_type'] == "mysql") {
  1552. $row = mysql_fetch_array($result);
  1553. }
  1554. if ($CONF['database_type'] == "mysqli") {
  1555. $row = mysqli_fetch_array($result);
  1556. }
  1557. if (db_sqlite()) {
  1558. $row = $result->fetchArray();
  1559. }
  1560. if (db_pgsql()) {
  1561. $row = pg_fetch_array($result);
  1562. }
  1563. return $row;
  1564. }
  1565. /**
  1566. * Get an associative array from a DB query resource.
  1567. *
  1568. * @param resource $result
  1569. * @return array|null|string
  1570. */
  1571. function db_assoc($result) {
  1572. global $CONF;
  1573. $row = "";
  1574. if ($CONF['database_type'] == "mysql") {
  1575. $row = mysql_fetch_assoc($result);
  1576. }
  1577. if ($CONF['database_type'] == "mysqli") {
  1578. $row = mysqli_fetch_assoc($result);
  1579. }
  1580. if (db_sqlite()) {
  1581. $row = $result->fetchArray(SQLITE3_ASSOC);
  1582. }
  1583. if (db_pgsql()) {
  1584. $row = pg_fetch_assoc($result);
  1585. }
  1586. return $row;
  1587. }
  1588. /**
  1589. * Delete a row from the specified table.
  1590. *
  1591. * DELETE FROM $table WHERE $where = $delete $aditionalWhere
  1592. *
  1593. * @param string $table
  1594. * @param string $where - should never be a user supplied value
  1595. * @param string $delete
  1596. * @param string $additionalwhere (default '').
  1597. * @return int|mixed rows deleted.
  1598. */
  1599. function db_delete($table, $where, $delete, $additionalwhere='') {
  1600. $table = table_by_key($table);
  1601. $query = "DELETE FROM $table WHERE $where ='" . escape_string($delete) . "' " . $additionalwhere;
  1602. $result = db_query($query);
  1603. if ($result['rows'] >= 1) {
  1604. return $result['rows'];
  1605. } else {
  1606. return 0;
  1607. }
  1608. }
  1609. /**
  1610. * db_insert
  1611. * Action: Inserts a row from a specified table
  1612. * Call: db_insert (string table, array values [, array timestamp])
  1613. *
  1614. * @param string - table name
  1615. * @param array - key/value map of data to insert into the table.
  1616. * @param array (optional) - array of fields to set to now() - default: array('created', 'modified')
  1617. * @return int - number of inserted rows
  1618. */
  1619. function db_insert($table, $values, $timestamp = array('created', 'modified')) {
  1620. $table = table_by_key($table);
  1621. foreach (array_keys($values) as $key) {
  1622. $values[$key] = "'" . escape_string($values[$key]) . "'";
  1623. }
  1624. foreach ($timestamp as $key) {
  1625. if (db_sqlite()) {
  1626. $values[$key] = "datetime('now')";
  1627. } else {
  1628. $values[$key] = "now()";
  1629. }
  1630. }
  1631. $sql_values = "(" . implode(",", escape_string(array_keys($values))).") VALUES (".implode(",", $values).")";
  1632. $result = db_query("INSERT INTO $table $sql_values");
  1633. return $result['rows'];
  1634. }
  1635. /**
  1636. * db_update
  1637. * Action: Updates a specified table
  1638. * Call: db_update (string table, string where_col, string where_value, array values [, array timestamp])
  1639. * @param string $table - table name
  1640. * @param string $where_col - column of WHERE condition
  1641. * @param string $where_value - value of WHERE condition
  1642. * @param array $values - key/value map of data to insert into the table.
  1643. * @param array $timestamp (optional) - array of fields to set to now() - default: array('modified')
  1644. * @return int - number of updated rows
  1645. */
  1646. function db_update($table, $where_col, $where_value, $values, $timestamp = array('modified')) {
  1647. $where = $where_col . " = '" . escape_string($where_value) . "'";
  1648. return db_update_q($table, $where, $values, $timestamp);
  1649. }
  1650. /**
  1651. * db_update_q
  1652. * Action: Updates a specified table
  1653. * Call: db_update_q (string table, string where, array values [, array timestamp])
  1654. * @param string $table - table name
  1655. * @param string $where - WHERE condition (as SQL)
  1656. * @param array $values - key/value map of data to insert into the table.
  1657. * @param array $timestamp (optional) - array of fields to set to now() - default: array('modified')
  1658. * @return int - number of updated rows
  1659. */
  1660. function db_update_q($table, $where, $values, $timestamp = array('modified')) {
  1661. $table = table_by_key($table);
  1662. foreach ($values as $key => $value) {
  1663. $sql_values[$key] = $key . "='" . escape_string($value) . "'";
  1664. }
  1665. foreach ($timestamp as $key) {
  1666. if (db_sqlite()) {
  1667. $sql_values[$key] = escape_string($key) . "=datetime('now')";
  1668. } else {
  1669. $sql_values[$key] = escape_string($key) . "=now()";
  1670. }
  1671. }
  1672. $sql="UPDATE $table SET " . implode(",", $sql_values) . " WHERE $where";
  1673. $result = db_query($sql);
  1674. return $result['rows'];
  1675. }
  1676. /**
  1677. * db_log
  1678. * Action: Logs actions from admin
  1679. * Call: db_log (string domain, string action, string data)
  1680. * Possible actions are defined in $LANG["pViewlog_action_$action"]
  1681. */
  1682. function db_log($domain, $action, $data) {
  1683. if (!Config::bool('logging')) {
  1684. return true;
  1685. }
  1686. $REMOTE_ADDR = getRemoteAddr();
  1687. $username = authentication_get_username();
  1688. if (Config::Lang("pViewlog_action_$action") == '') {
  1689. die("Invalid log action : $action"); // could do with something better?
  1690. }
  1691. $logdata = array(
  1692. 'username' => "$username ($REMOTE_ADDR)",
  1693. 'domain' => $domain,
  1694. 'action' => $action,
  1695. 'data' => $data,
  1696. );
  1697. $result = db_insert('log', $logdata, array('timestamp'));
  1698. if ($result != 1) {
  1699. return false;
  1700. } else {
  1701. return true;
  1702. }
  1703. }
  1704. /**
  1705. * db_in_clause
  1706. * Action: builds and returns the "field in(x, y)" clause for database queries
  1707. * Call: db_in_clause (string field, array values)
  1708. * @param string $field
  1709. * @param array $values
  1710. */
  1711. function db_in_clause($field, $values) {
  1712. return " $field IN ('"
  1713. . implode("','", escape_string(array_values($values)))
  1714. . "') ";
  1715. }
  1716. /**
  1717. * db_where_clause
  1718. * Action: builds and returns a WHERE clause for database queries. All given conditions will be AND'ed.
  1719. * Call: db_where_clause (array $conditions, array $struct)
  1720. * @param array $condition - array('field' => 'value', 'field2' => 'value2, ...)
  1721. * @param array $struct - field structure, used for automatic bool conversion
  1722. * @param string $additional_raw_where - raw sniplet to include in the WHERE part - typically needs to start with AND
  1723. * @param array $searchmode - operators to use (=, <, > etc.) - defaults to = if not specified for a field (see
  1724. * $allowed_operators for available operators)
  1725. * Note: the $searchmode operator will only be used if a $condition for that field is set.
  1726. * This also means you'll need to set a (dummy) condition for NULL and NOTNULL.
  1727. */
  1728. function db_where_clause($condition, $struct, $additional_raw_where = '', $searchmode = array()) {
  1729. if (!is_array($condition)) {
  1730. die('db_where_cond: parameter $cond is not an array!');
  1731. } elseif (!is_array($searchmode)) {
  1732. die('db_where_cond: parameter $searchmode is not an array!');
  1733. } elseif (count($condition) == 0 && trim($additional_raw_where) == '') {
  1734. die("db_where_cond: parameter is an empty array!"); # die() might sound harsh, but can prevent information leaks
  1735. } elseif (!is_array($struct)) {
  1736. die('db_where_cond: parameter $struct is not an array!');
  1737. }
  1738. $allowed_operators = array('<', '>', '>=', '<=', '=', '!=', '<>', 'CONT', 'LIKE', 'NULL', 'NOTNULL');
  1739. $where_parts = array();
  1740. $having_parts = array();
  1741. foreach ($condition as $field => $value) {
  1742. if (isset($struct[$field]) && $struct[$field]['type'] == 'bool') {
  1743. $value = db_get_boolean($value);
  1744. }
  1745. $operator = '=';
  1746. if (isset($searchmode[$field])) {
  1747. if (in_array($searchmode[$field], $allowed_operators)) {
  1748. $operator = $searchmode[$field];
  1749. if ($operator == 'CONT') { # CONT - as in "contains"
  1750. $operator = ' LIKE '; # add spaces
  1751. $value = '%' . $value . '%';
  1752. } elseif ($operator == 'LIKE') { # LIKE -without adding % wildcards (the search value can contain %)
  1753. $operator = ' LIKE '; # add spaces
  1754. }
  1755. } else {
  1756. die('db_where_clause: Invalid searchmode for ' . $field);
  1757. }
  1758. }
  1759. if ($operator == "NULL") {
  1760. $querypart = $field . ' IS NULL';
  1761. } elseif ($operator == "NOTNULL") {
  1762. $querypart = $field . ' IS NOT NULL';
  1763. } else {
  1764. $querypart = $field . $operator . "'" . escape_string($value) . "'";
  1765. // might need other types adding here.
  1766. if (db_pgsql() && isset($struct[$field]) && in_array($struct[$field]['type'], array('ts', 'num')) && $value === '') {
  1767. $querypart = $field . $operator . " NULL";
  1768. }
  1769. }
  1770. if (!empty($struct[$field]['select'])) {
  1771. $having_parts[$field] = $querypart;
  1772. } else {
  1773. $where_parts[$field] = $querypart;
  1774. }
  1775. }
  1776. $query = ' WHERE 1=1 ';
  1777. $query .= " $additional_raw_where ";
  1778. if (count($where_parts) > 0) {
  1779. $query .= " AND ( " . join(" AND ", $where_parts) . " ) ";
  1780. }
  1781. if (count($having_parts) > 0) {
  1782. $query .= " HAVING ( " . join(" AND ", $having_parts) . " ) ";
  1783. }
  1784. return $query;
  1785. }
  1786. /**
  1787. * Convert a programmatic db table name into what may be the actual name.
  1788. *
  1789. * Takes into consideration any CONF database_prefix or database_tables map
  1790. *
  1791. * If it's a MySQL database, then we return the name with backticks around it (`).
  1792. *
  1793. * @param string database table name.
  1794. * @return string - database table name with appropriate prefix (and quoting if MySQL)
  1795. */
  1796. function table_by_key($table_key) {
  1797. global $CONF;
  1798. $table = $table_key;
  1799. if (!empty($CONF['database_tables'][$table_key])) {
  1800. $table = $CONF['database_tables'][$table_key];
  1801. }
  1802. $table = $CONF['database_prefix'] . $table;
  1803. if (db_mysql()) {
  1804. return "`" . $table . "`";
  1805. }
  1806. return $table;
  1807. }
  1808. /*
  1809. * check if the database layout is up to date
  1810. * returns the current 'version' value from the config table
  1811. * if $error_out is True (default), die() with a message that recommends to run setup.php.
  1812. */
  1813. function check_db_version($error_out = true) {
  1814. global $min_db_version;
  1815. $table = table_by_key('config');
  1816. $sql = "SELECT value FROM $table WHERE name = 'version'";
  1817. $r = db_query($sql);
  1818. if ($r['rows'] == 1) {
  1819. $row = db_assoc($r['result']);
  1820. $dbversion = $row['value'];
  1821. } else {
  1822. $dbversion = 0;
  1823. db_query("INSERT INTO $table (name, value) VALUES ('version', '0')", 0, '');
  1824. }
  1825. if (($dbversion < $min_db_version) && $error_out == true) {
  1826. 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";
  1827. exit(1);
  1828. }
  1829. return $dbversion;
  1830. }
  1831. //
  1832. // gen_show_status
  1833. // Action: Return a string of colored &nbsp;'s that indicate
  1834. // the if an alias goto has an error or is sent to
  1835. // addresses list in show_custom_domains
  1836. // Call: gen_show_status (string alias_address)
  1837. //
  1838. function gen_show_status($show_alias) {
  1839. global $CONF;
  1840. $table_alias = table_by_key('alias');
  1841. $stat_string = "";
  1842. $show_alias = escape_string($show_alias);
  1843. $stat_goto = "";
  1844. $stat_result = db_query("SELECT goto FROM $table_alias WHERE address='$show_alias'");
  1845. if ($stat_result['rows'] > 0) {
  1846. $row = db_row($stat_result['result']);
  1847. $stat_goto = $row[0];
  1848. }
  1849. if (!empty($CONF['recipient_delimiter'])) {
  1850. $delimiter = preg_quote($CONF['recipient_delimiter'], "/");
  1851. $delimiter_regex = '/' .$delimiter. '[^' .$delimiter. '@]*@/';
  1852. }
  1853. // UNDELIVERABLE CHECK
  1854. if ($CONF['show_undeliverable'] == 'YES') {
  1855. $gotos=array();
  1856. $gotos=explode(',', $stat_goto);
  1857. $undel_string="";
  1858. //make sure this alias goes somewhere known
  1859. $stat_ok = 1;
  1860. foreach ($gotos as $g) {
  1861. if (!$stat_ok) {
  1862. break;
  1863. }
  1864. if (strpos($g, '@') === false) {
  1865. continue;
  1866. }
  1867. list($local_part, $stat_domain) = explode('@', $g);
  1868. $stat_delimiter = "";
  1869. if (!empty($CONF['recipient_delimiter'])) {
  1870. $stat_delimiter = "OR address = '" . escape_string(preg_replace($delimiter_regex, "@", $g)) . "'";
  1871. }
  1872. $stat_result = db_query("SELECT address FROM $table_alias WHERE address = '" . escape_string($g) . "' OR address = '@" . escape_string($stat_domain) . "' $stat_delimiter");
  1873. if ($stat_result['rows'] == 0) {
  1874. $stat_ok = 0;
  1875. }
  1876. if ($stat_ok == 0) {
  1877. if ($stat_domain == $CONF['vacation_domain'] || in_array($stat_domain, $CONF['show_undeliverable_exceptions'])) {
  1878. $stat_ok = 1;
  1879. }
  1880. }
  1881. } // while
  1882. if ($stat_ok == 0) {
  1883. $stat_string .= "<span style='background-color:" . $CONF['show_undeliverable_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1884. } else {
  1885. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1886. }
  1887. }
  1888. // Vacation CHECK
  1889. if ( isset($CONF['show_vacation']) && $CONF['show_vacation'] == 'YES' ) {
  1890. $stat_result = db_query("SELECT * FROM ". $CONF['database_tables']['vacation'] ." WHERE email = '" . $show_alias . "' AND active = '" . db_get_boolean(true) . "'") ;
  1891. if ($stat_result['rows'] == 1) {
  1892. $stat_string .= "<span style='background-color:" . $CONF['show_vacation_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1893. } else {
  1894. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1895. }
  1896. }
  1897. // Disabled CHECK
  1898. if ( isset($CONF['show_disabled']) && $CONF['show_disabled'] == 'YES' ) {
  1899. $stat_result = db_query("SELECT * FROM ". $CONF['database_tables']['mailbox'] ." WHERE username = '" . $show_alias . "' AND active = '" . db_get_boolean(false) . "'");
  1900. if ($stat_result['rows'] == 1) {
  1901. $stat_string .= "<span style='background-color:" . $CONF['show_disabled_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1902. } else {
  1903. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1904. }
  1905. }
  1906. // POP/IMAP CHECK
  1907. if ($CONF['show_popimap'] == 'YES') {
  1908. $stat_delimiter = "";
  1909. if (!empty($CONF['recipient_delimiter'])) {
  1910. $stat_delimiter = ',' . preg_replace($delimiter_regex, "@", $stat_goto);
  1911. }
  1912. //if the address passed in appears in its own goto field, its POP/IMAP
  1913. # TODO: or not (might also be an alias loop) -> check mailbox table!
  1914. if (preg_match('/,' . $show_alias . ',/', ',' . $stat_goto . $stat_delimiter . ',')) {
  1915. $stat_string .= "<span style='background-color:" . $CONF['show_popimap_color'] .
  1916. "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1917. } else {
  1918. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1919. }
  1920. }
  1921. // CUSTOM DESTINATION CHECK
  1922. if (count($CONF['show_custom_domains']) > 0) {
  1923. for ($i = 0; $i < sizeof($CONF['show_custom_domains']); $i++) {
  1924. if (preg_match('/^.*' . $CONF['show_custom_domains'][$i] . '.*$/', $stat_goto)) {
  1925. $stat_string .= "<span style='background-color:" . $CONF['show_custom_colors'][$i] .
  1926. "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
  1927. } else {
  1928. $stat_string .= $CONF['show_status_text'] . "&nbsp;";
  1929. }
  1930. }
  1931. } else {
  1932. $stat_string .= ";&nbsp;";
  1933. }
  1934. // $stat_string .= "<span style='background-color:green'> &nbsp; </span> &nbsp;" .
  1935. // "<span style='background-color:blue'> &nbsp; </span> &nbsp;";
  1936. return $stat_string;
  1937. }
  1938. /**
  1939. * @return string
  1940. */
  1941. function getRemoteAddr() {
  1942. $REMOTE_ADDR = 'localhost';
  1943. if (isset($_SERVER['REMOTE_ADDR'])) {
  1944. $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
  1945. }
  1946. return $REMOTE_ADDR;
  1947. }
  1948. /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */