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.

functions.inc.php 71KB

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