functions.inc.php 73 KB

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