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 63KB

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