PFAHandler.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. <?php
  2. abstract class PFAHandler {
  3. /**
  4. * public variables
  5. */
  6. # array of error messages - if a method returns false, you'll find the error message(s) here
  7. public $errormsg = array();
  8. # array of info messages (for example success messages)
  9. public $infomsg = array();
  10. # array of tasks available in CLI
  11. public $taskNames = array('Help', 'Add', 'Update', 'Delete', 'View', 'Scheme');
  12. /**
  13. * variables that must be defined in all *Handler classes
  14. */
  15. # (default) name of the database table
  16. # (can be overridden by $CONF[database_prefix] and $CONF[database_tables][*] via table_by_key())
  17. protected $db_table = null;
  18. # field containing the ID
  19. protected $id_field = null;
  20. # field containing the label
  21. # defaults to $id_field if not set
  22. protected $label_field = null;
  23. # field(s) to use in the ORDER BY clause
  24. # can contain multiple comma-separated fields
  25. # defaults to $id_field if not set
  26. protected $order_by = null;
  27. # column containing the domain
  28. # if a table does not contain a domain column, leave empty and override no_domain_field())
  29. protected $domain_field = "";
  30. # column containing the username (if logged in as non-admin)
  31. protected $user_field = '';
  32. # skip empty password fields in edit mode
  33. # enabled by default to allow changing an admin, mailbox etc. without changing the password
  34. # disable for "edit password" forms
  35. protected $skip_empty_pass = true;
  36. # fields to search when using simple search ("?search[_]=...")
  37. # array with one or more fields to search (all fields will be OR'ed in the query)
  38. # searchmode is always 'contains' (using LIKE "%searchterm%")
  39. protected $searchfields = array();
  40. /**
  41. * internal variables - filled by methods of *Handler
  42. */
  43. # if $domain_field is set, this is an array with the domain list
  44. # set in __construct()
  45. protected $allowed_domains = false;
  46. # if set, restrict $allowed_domains to this admin
  47. # set in __construct()
  48. protected $admin_username = "";
  49. # will be set to 0 if $admin_username is set and is not a superadmin
  50. protected $is_superadmin = 1;
  51. # if set, switch to user (non-admin) mode
  52. protected $username = '';
  53. # will be set to 0 if a user (non-admin) is logged in
  54. protected $is_admin = 1;
  55. # the ID of the current item (where item can be an admin, domain, mailbox, alias etc.)
  56. # filled in init()
  57. protected $id = null;
  58. # the domain of the current item (used for logging)
  59. # filled in domain_from_id() via init()
  60. protected $domain = null;
  61. # the label of the current item (for usage in error/info messages)
  62. # filled in init() (only contains the "real" label in edit mode - in new mode, it will be the same as $id)
  63. protected $label = null;
  64. # can this item be edited?
  65. # filled in init() (only in edit mode)
  66. protected $can_edit = 1;
  67. # can this item be deleted?
  68. # filled in init() (only in edit mode)
  69. protected $can_delete = 1;
  70. # TODO: needs to be implemented in delete()
  71. # structure of the database table, list, edit form etc.
  72. # filled in initStruct()
  73. protected $struct = array();
  74. # new item or edit existing one?
  75. # set in __construct()
  76. protected $new = 0; # 1 on create, otherwise 0
  77. # validated values
  78. # filled in set()
  79. protected $values = array();
  80. # unchecked (!) input given to set() - use it carefully!
  81. # filled in set(), can be modified by _missing_$field()
  82. protected $RAWvalues = array();
  83. # are the values given to set() valid?
  84. # set by set(), checked by store()
  85. protected $values_valid = false;
  86. # messages used in various functions
  87. # (stored separately to make the functions reuseable)
  88. # filled by initMsg()
  89. protected $msg = array(
  90. 'can_create' => True,
  91. 'confirm_delete' => 'confirm',
  92. 'list_header' => '', # headline used in list view
  93. );
  94. # called via another *Handler class? (use calledBy() to set this information)
  95. protected $called_by = '';
  96. /**
  97. * Constructor: fill $struct etc.
  98. * @param integer - 0 is edit mode, set to 1 to switch to create mode
  99. * @param string - if an admin_username is specified, permissions will be restricted to the domains this admin may manage
  100. * @param integer - 0 if logged in as user, 1 if logged in as admin or superadmin
  101. */
  102. public function __construct($new = 0, $username = "", $is_admin = 1) {
  103. # set label_field if not explicitely set
  104. if (empty($this->label_field)) {
  105. $this->label_field = $this->id_field;
  106. }
  107. # set order_by if not explicitely set
  108. if (empty($this->order_by)) {
  109. $this->order_by = $this->id_field;
  110. }
  111. if ($new) $this->new = 1;
  112. if ($is_admin) {
  113. $this->admin_username = $username;
  114. } else {
  115. $this->username = $username;
  116. $this->is_admin = 0;
  117. $this->is_superadmin = 0;
  118. }
  119. if ($username != "" && (! authentication_has_role('global-admin') ) ) {
  120. $this->is_superadmin = 0;
  121. }
  122. if ($this->domain_field == "") {
  123. $this->no_domain_field();
  124. } else {
  125. if ($this->admin_username != "") {
  126. $this->allowed_domains = list_domains_for_admin($username);
  127. } else {
  128. $this->allowed_domains = list_domains();
  129. }
  130. }
  131. if ($this->user_field == '') {
  132. $this->no_user_field();
  133. }
  134. $this->initStruct();
  135. if (!isset($this->struct['_can_edit'])) {
  136. $this->struct['_can_edit'] = pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
  137. /*not_in_db*/ 0,
  138. /*dont_write_to_db*/ 1,
  139. /*select*/ '1 as _can_edit'
  140. );
  141. }
  142. if (!isset($this->struct['_can_delete'])) {
  143. $this->struct['_can_delete'] = pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
  144. /*not_in_db*/ 0,
  145. /*dont_write_to_db*/ 1,
  146. /*select*/ '1 as _can_delete'
  147. );
  148. }
  149. $struct_hook = Config::read($this->db_table . '_struct_hook');
  150. if ( $struct_hook != 'NO' && function_exists($struct_hook) ) {
  151. $this->struct = $struct_hook($this->struct);
  152. }
  153. $this->initMsg();
  154. $this->msg['id_field'] = $this->id_field;
  155. $this->msg['show_simple_search'] = count($this->searchfields) > 0;
  156. }
  157. /**
  158. * ensure a lazy programmer can't give access to all items accidently
  159. *
  160. * to intentionally disable the check if $this->domain_field is empty, override this function
  161. */
  162. protected function no_domain_field() {
  163. if ($this->admin_username != "") die('Attemp to restrict domains without setting $this->domain_field!');
  164. }
  165. /**
  166. * ensure a lazy programmer can't give access to all items accidently
  167. *
  168. * to intentionally disable the check if $this->user_field is empty, override this function
  169. */
  170. protected function no_user_field() {
  171. if ($this->username != '') die('Attemp to restrict users without setting $this->user_field!');
  172. }
  173. /**
  174. * init $this->struct (an array of pacol() results)
  175. * see pacol() in functions.inc.php for all available parameters
  176. *
  177. * available values for the "type" column:
  178. * text one line of text
  179. * *vtxt "virtual" line of text, coming from JOINs etc.
  180. * html raw html (use carefully, won't get auto-escaped by smarty! Don't use with user input!)
  181. * pass password (will be encrypted with pacrypt())
  182. * b64p password (will be stored with base64_encode())
  183. * num number
  184. * txtl text "list" - array of one line texts
  185. * *vnum "virtual" number, coming from JOINs etc.
  186. * bool boolean (converted to 0/1, additional column _$field with yes/no)
  187. * ts timestamp (created/modified)
  188. * enum list of options, must be given in column "options" as array
  189. * enma list of options, must be given in column "options" as associative array
  190. * list like enum, but allow multiple selections
  191. * *quot used / total quota ("5 / 10") - for field "quotausage", there must also be a "_quotausage_percent" (type vnum)
  192. * You can use custom types, but you'll have to add handling for them in *Handler and the smarty templates
  193. *
  194. * Field types marked with * will automatically be skipped in store().
  195. *
  196. * All database tables should have a 'created' and a 'modified' column.
  197. *
  198. * Do not use one of the following field names:
  199. * edit, delete, prefill, webroot, help
  200. * because those are used as parameter names in the web and/or commandline interface
  201. */
  202. abstract protected function initStruct();
  203. /**
  204. * init $this->msg[] with messages used in various functions.
  205. *
  206. * always list the key to hand over to Config::lang
  207. * the only exception is 'logname' which uses the key for db_log
  208. *
  209. * The values can depend on $this->new
  210. * TODO: use separate keys edit_* and new_* and choose the needed message at runtime
  211. */
  212. abstract protected function initMsg();
  213. /**
  214. * returns an array with some labels and settings for the web interface
  215. * can also change $this->struct to something that makes the web interface better
  216. * (for example, it can make local_part and domain editable as separate fields
  217. * so that users can choose the domain from a dropdown)
  218. *
  219. * @return array
  220. */
  221. abstract public function webformConfig();
  222. /**
  223. * if you call one *Handler class from another one, tell the "child" *Handler as early as possible (before init())
  224. * The flag can be used to avoid logging, avoid loops etc. The exact handling is up to the implementation in *Handler
  225. *
  226. * @param string calling class
  227. */
  228. public function calledBy($calling_class) {
  229. $this->called_by = $calling_class;
  230. }
  231. /**
  232. * initialize with $id and check if it is valid
  233. * @param string $id
  234. */
  235. public function init($id) {
  236. $this->id = strtolower($id);
  237. $this->label = $this->id;
  238. $exists = $this->view(false);
  239. if ($this->new) {
  240. if ($exists) {
  241. $this->errormsg[$this->id_field] = Config::lang($this->msg['error_already_exists']);
  242. return false;
  243. } elseif (!$this->validate_new_id() ) {
  244. # errormsg filled by validate_new_id()
  245. return false;
  246. # } else {
  247. # return true;
  248. }
  249. } else { # view or edit mode
  250. if (!$exists) {
  251. $this->errormsg[$this->id_field] = Config::lang($this->msg['error_does_not_exist']);
  252. return false;
  253. } else {
  254. $this->can_edit = $this->result['_can_edit'];
  255. $this->can_delete = $this->result['_can_delete'];
  256. $this->label = $this->result[$this->label_field];
  257. # return true;
  258. }
  259. }
  260. $this->domain = $this->domain_from_id();
  261. return true;
  262. }
  263. /**
  264. * on $new, check if the ID is valid (for example, check if it is a valid mail address syntax-wise)
  265. * called by init()
  266. * @return boolean true/false
  267. * must also set $this->errormsg[$this->id_field] if ID is invalid
  268. */
  269. abstract protected function validate_new_id();
  270. /**
  271. * called by init() if $this->id != $this->domain_field
  272. * must be overridden if $id_field != $domain_field
  273. * @return string the domain to use for logging
  274. */
  275. protected function domain_from_id() {
  276. if ($this->id_field == $this->domain_field) {
  277. return $this->id;
  278. } elseif ($this->domain_field == "") {
  279. return "";
  280. } else {
  281. die('You must override domain_from_id()!');
  282. }
  283. }
  284. /**
  285. * web interface can prefill some fields
  286. * if a _prefill_$field method exists, call it (it can for example modify $struct)
  287. * @param string - field
  288. * @param string - prefill value
  289. */
  290. public function prefill($field, $val) {
  291. $func="_prefill_".$field;
  292. if (method_exists($this, $func) ) {
  293. $this->{$func}($field, $val); # call _missing_$fieldname()
  294. } else {
  295. $this->struct[$field]['default'] = $val;
  296. }
  297. }
  298. /**
  299. * set and verify values
  300. * @param array values - associative array with ($field1 => $value1, $field2 => $value2, ...)
  301. * @return bool - true if all values are valid, otherwise false
  302. * error messages (if any) are stored in $this->errormsg
  303. */
  304. public function set($values) {
  305. if ( !$this->can_edit ) {
  306. $this->errormsg[] = Config::Lang_f('edit_not_allowed', $this->label);
  307. return false;
  308. }
  309. if ($this->new == 1) {
  310. $values[$this->id_field] = $this->id;
  311. }
  312. $this->RAWvalues = $values; # allows comparison of two fields before the second field is checked
  313. # Warning: $this->RAWvalues contains unchecked input data - use it carefully!
  314. if ($this->new) {
  315. foreach($this->struct as $key=>$row) {
  316. if ($row['editable'] && !isset($values[$key]) ) {
  317. /**
  318. * when creating a new item:
  319. * if a field is editable and not set,
  320. * - if $this->_missing_$fieldname() exists, call it
  321. * (it can set $this->RAWvalues[$fieldname] - or do nothing if it can't set a useful value)
  322. * - otherwise use the default value from $this->struct
  323. * (if you don't want this, create an empty _missing_$fieldname() function)
  324. */
  325. $func="_missing_".$key;
  326. if (method_exists($this, $func) ) {
  327. $this->{$func}($key); # call _missing_$fieldname()
  328. } else {
  329. $this->set_default_value($key); # take default value from $this->struct
  330. }
  331. }
  332. }
  333. $values = $this->RAWvalues;
  334. }
  335. # base validation
  336. $this->values = array();
  337. $this->values_valid = false;
  338. foreach($this->struct as $key=>$row) {
  339. if ($row['editable'] == 0) { # not editable
  340. if ($this->new == 1) {
  341. # on $new, always set non-editable field to default value on $new (even if input data contains another value)
  342. $this->values[$key] = $row['default'];
  343. }
  344. } else { # field is editable
  345. if (isset($values[$key])) {
  346. if (
  347. ($row['type'] != "pass" && $row['type'] != 'b64p') || # field type is NOT 'pass' or 'b64p' - or -
  348. strlen($values[$key]) > 0 || # new value is not empty - or -
  349. $this->new == 1 || # create mode - or -
  350. $this->skip_empty_pass != true # skip on empty (aka unchanged) password on edit
  351. ) {
  352. # TODO: do not skip "password2" if "password" is filled, but "password2" is empty
  353. $valid = true; # trust input unless validator objects
  354. # validate based on field type ($this->_inp_$type)
  355. $func="_inp_".$row['type'];
  356. if (method_exists($this, $func) ) {
  357. if (!$this->{$func}($key, $values[$key])) $valid = false;
  358. } else {
  359. # TODO: warning if no validation function exists?
  360. }
  361. # validate based on field name (_validate_$fieldname)
  362. $func="_validate_".$key;
  363. if (method_exists($this, $func) ) {
  364. if (!$this->{$func}($key, $values[$key])) $valid = false;
  365. }
  366. if (isset($this->errormsg[$key]) && $this->errormsg[$key] != '') $valid = false;
  367. if ($valid) {
  368. $this->values[$key] = $values[$key];
  369. }
  370. }
  371. } elseif ($this->new) { # new, field not set in input data
  372. $this->errormsg[$key] = Config::lang_f('missing_field', $key);
  373. } else { # edit, field unchanged
  374. # echo "skipped / not set: $key\n";
  375. }
  376. }
  377. }
  378. $this->setmore($values);
  379. if (count($this->errormsg) == 0) {
  380. $this->values_valid = true;
  381. }
  382. return $this->values_valid;
  383. }
  384. /**
  385. * set more values
  386. * can be used to update additional columns etc.
  387. * hint: modify $this->values and $this->errormsg directly as needed
  388. */
  389. protected function setmore($values) {
  390. # do nothing
  391. }
  392. /**
  393. * store $this->values in the database
  394. *
  395. * converts values based on $this->struct[*][type] (boolean, password encryption)
  396. *
  397. * calls $this->storemore() where additional things can be done
  398. * @return bool - true if all values were stored in the database, otherwise false
  399. * error messages (if any) are stored in $this->errormsg
  400. */
  401. public function store() {
  402. if ($this->values_valid == false) {
  403. $this->errormsg[] = "one or more values are invalid!";
  404. return false;
  405. }
  406. if ( !$this->beforestore() ) {
  407. return false;
  408. }
  409. $db_values = $this->values;
  410. foreach(array_keys($db_values) as $key) {
  411. switch ($this->struct[$key]['type']) { # modify field content for some types
  412. case 'bool':
  413. $db_values[$key] = db_get_boolean($db_values[$key]);
  414. break;
  415. case 'pass':
  416. $db_values[$key] = pacrypt($db_values[$key]);
  417. break;
  418. case 'b64p':
  419. $db_values[$key] = base64_encode($db_values[$key]);
  420. break;
  421. case 'quot':
  422. case 'vnum':
  423. case 'vtxt':
  424. unset ($db_values[$key]); # virtual field, never write it
  425. break;
  426. }
  427. if ($this->struct[$key]['not_in_db'] == 1) unset ($db_values[$key]); # remove 'not in db' columns
  428. if ($this->struct[$key]['dont_write_to_db'] == 1) unset ($db_values[$key]); # remove 'dont_write_to_db' columns
  429. }
  430. if ($this->new) {
  431. $result = db_insert($this->db_table, $db_values);
  432. } else {
  433. $result = db_update($this->db_table, $this->id_field, $this->id, $db_values);
  434. }
  435. if ($result != 1) {
  436. $this->errormsg[] = Config::lang_f($this->msg['store_error'], $this->label);
  437. return false;
  438. }
  439. $result = $this->storemore();
  440. # db_log() even if storemore() failed
  441. db_log ($this->domain, $this->msg['logname'], $this->id);
  442. if ($result) {
  443. # return success message
  444. # TODO: add option to override the success message (for example to include autogenerated passwords)
  445. $this->infomsg['success'] = Config::lang_f($this->msg['successmessage'], $this->label);
  446. }
  447. return $result;
  448. }
  449. /**
  450. * called by $this->store() before storing the values in the database
  451. * @return bool - if false, store() will abort
  452. */
  453. protected function beforestore() {
  454. return true; # do nothing, successfully ;-)
  455. }
  456. /**
  457. * called by $this->store() after storing $this->values in the database
  458. * can be used to update additional tables, call scripts etc.
  459. */
  460. protected function storemore() {
  461. return true; # do nothing, successfully ;-)
  462. }
  463. /**
  464. * build_select_query
  465. *
  466. * helper function to build the inner part of the select query
  467. * can be used by read_from_db() and for generating the pagebrowser
  468. *
  469. * @param array or string - condition (an array will be AND'ed using db_where_clause, a string will be directly used)
  470. * (if you use a string, make sure it is correctly escaped!)
  471. * - WARNING: will be changed to array only in the future, with an option to include a raw string inside the array
  472. * @param array searchmode - operators to use (=, <, >) if $condition is an array. Defaults to = if not specified for a field.
  473. * @return array - contains query parts
  474. */
  475. protected function build_select_query($condition, $searchmode) {
  476. $select_cols = array();
  477. $yes = escape_string(Config::lang('YES'));
  478. $no = escape_string(Config::lang('NO'));
  479. if (db_pgsql()) {
  480. $formatted_date = "TO_DATE(text(###KEY###), '" . escape_string(Config::Lang('dateformat_pgsql')) . "')";
  481. $base64_decode = "DECODE(###KEY###, 'base64')";
  482. } else {
  483. $formatted_date = "DATE_FORMAT(###KEY###, '" . escape_string(Config::Lang('dateformat_mysql')) . "')";
  484. $base64_decode = "FROM_BASE64(###KEY###)";
  485. }
  486. $colformat = array(
  487. # 'ts' fields are always returned as $formatted_date, and the raw value as _$field
  488. 'ts' => "$formatted_date AS ###KEY###, ###KEY### AS _###KEY###",
  489. # 'bool' fields are always returned as 0/1, additonally _$field contains yes/no (already translated)
  490. 'bool' => "CASE ###KEY### WHEN '" . db_get_boolean(true) . "' THEN '1' WHEN '" . db_get_boolean(false) . "' THEN '0' END as ###KEY###," .
  491. "CASE ###KEY### WHEN '" . db_get_boolean(true) . "' THEN '$yes' WHEN '" . db_get_boolean(false) . "' THEN '$no' END as _###KEY###",
  492. 'b64p' => "$base64_decode AS ###KEY###",
  493. );
  494. # get list of fields to display
  495. $extrafrom = "";
  496. foreach($this->struct as $key=>$row) {
  497. if ( ($row['display_in_list'] != 0 || $row['display_in_form'] != 0) && $row['not_in_db'] == 0 ) {
  498. if ($row['select'] != '') $key = $row['select'];
  499. if ($row['extrafrom'] != '') $extrafrom = $extrafrom . " " . $row['extrafrom'] . "\n";
  500. if (isset($colformat[$row['type']])) {
  501. $select_cols[] = str_replace('###KEY###', $key, $colformat[$row['type']] );
  502. } else {
  503. $select_cols[] = $key;
  504. }
  505. }
  506. }
  507. $cols = join(',', $select_cols);
  508. $table = table_by_key($this->db_table);
  509. $additional_where = '';
  510. if ($this->domain_field != "") {
  511. $additional_where .= " AND " . db_in_clause($this->domain_field, $this->allowed_domains);
  512. }
  513. # if logged in as user, restrict to the items the user is allowed to see
  514. if ( (!$this->is_admin) && $this->user_field != '') {
  515. $additional_where .= " AND " . $this->user_field . " = '" . escape_string($this->username) . "' ";
  516. }
  517. if (is_array($condition)) {
  518. if (isset($condition['_']) && count($this->searchfields) > 0) {
  519. $simple_search = array();
  520. foreach ($this->searchfields as $field) {
  521. $simple_search[] = "$field LIKE '%" . escape_string($condition['_']) . "%'";
  522. }
  523. $additional_where .= " AND ( " . join(" OR ", $simple_search) . " ) ";
  524. unset($condition['_']);
  525. }
  526. $where = db_where_clause($condition, $this->struct, $additional_where, $searchmode);
  527. } else {
  528. if ($condition == "") $condition = '1=1';
  529. $where = " WHERE ( $condition ) $additional_where";
  530. }
  531. return array(
  532. 'select_cols' => " SELECT $cols ",
  533. 'from_where_order' => " FROM $table $extrafrom $where ORDER BY " . $this->order_by,
  534. );
  535. }
  536. /**
  537. * getPagebrowser
  538. *
  539. * @param array or string condition (see build_select_query() for details)
  540. * @param array searchmode - (see build_select_query() for details)
  541. * @return array - pagebrowser keys ("aa-cz", "de-pf", ...)
  542. */
  543. public function getPagebrowser($condition, $searchmode) {
  544. $queryparts = $this->build_select_query($condition, $searchmode);
  545. return create_page_browser($this->label_field, $queryparts['from_where_order']);
  546. }
  547. /**
  548. * read_from_db
  549. *
  550. * reads all fields specified in $this->struct from the database
  551. * and auto-converts them to database-independent values based on the field type (see $colformat)
  552. *
  553. * calls $this->read_from_db_postprocess() to postprocess the result
  554. *
  555. * @param array or string condition -see build_select_query() for details
  556. * @param array searchmode - see build_select_query() for details
  557. * @param integer limit - maximum number of rows to return
  558. * @param integer offset - number of first row to return
  559. * @return array - rows (as associative array, with the ID as key)
  560. */
  561. protected function read_from_db($condition, $searchmode = array(), $limit=-1, $offset=-1) {
  562. $queryparts = $this->build_select_query($condition, $searchmode);
  563. $query = $queryparts['select_cols'] . $queryparts['from_where_order'];
  564. $limit = (int) $limit; # make sure $limit and $offset are really integers
  565. $offset = (int) $offset;
  566. if ($limit > -1 && $offset > -1) {
  567. $query .= " LIMIT $limit OFFSET $offset ";
  568. }
  569. $result = db_query($query);
  570. $db_result = array();
  571. if ($result['rows'] != 0) {
  572. while ($row = db_assoc ($result['result'])) {
  573. $db_result[$row[$this->id_field]] = $row;
  574. }
  575. }
  576. $db_result = $this->read_from_db_postprocess($db_result);
  577. return $db_result;
  578. }
  579. /**
  580. * allows to postprocess the database result
  581. * called by read_from_db()
  582. */
  583. protected function read_from_db_postprocess($db_result) {
  584. return $db_result;
  585. }
  586. /**
  587. * get the values of an item
  588. * @param boolean (optional) - if false, $this->errormsg[] will not be filled in case of errors
  589. * @return bool - true if item was found
  590. * The data is stored in $this->result (as associative array of column => value)
  591. * error messages (if any) are stored in $this->errormsg
  592. */
  593. public function view($errors=true) {
  594. $result = $this->read_from_db(array($this->id_field => $this->id) );
  595. if (count($result) == 1) {
  596. $this->result = $result[$this->id];
  597. return true;
  598. }
  599. if ($errors) $this->errormsg[] = Config::lang($this->msg['error_does_not_exist']);
  600. # $this->errormsg[] = $result['error'];
  601. return false;
  602. }
  603. /**
  604. * get a list of one or more items with all values
  605. * @param array or string $condition - see read_from_db for details
  606. * WARNING: will be changed to array only in the future, with an option to include a raw string inside the array
  607. * @param array - modes to use if $condition is an array - see read_from_db for details
  608. * @param integer limit - maximum number of rows to return
  609. * @param integer offset - number of first row to return
  610. * @return bool - always true, no need to check ;-) (if $result is not an array, getList die()s)
  611. * The data is stored in $this->result (as array of rows, each row is an associative array of column => value)
  612. */
  613. public function getList($condition, $searchmode = array(), $limit=-1, $offset=-1) {
  614. if (is_array($condition)) {
  615. $real_condition = array();
  616. foreach ($condition as $key => $value) {
  617. # allow only access to fields the user can access to avoid information leaks via search parameters
  618. if (isset($this->struct[$key]) && ($this->struct[$key]['display_in_list'] || $this->struct[$key]['display_in_form']) ) {
  619. $real_condition[$key] = $value;
  620. } elseif (($key == '_') && count($this->searchfields)) {
  621. $real_condition[$key] = $value;
  622. } else {
  623. $this->errormsg[] = "Ignoring unknown search field $key";
  624. }
  625. }
  626. } else {
  627. # warning: no sanity checks are applied if $condition is not an array!
  628. $real_condition = $condition;
  629. }
  630. $result = $this->read_from_db($real_condition, $searchmode, $limit, $offset);
  631. if (!is_array($result)) {
  632. error_log('getList: read_from_db didn\'t return an array. table: ' . $this->db_table . ' - condition: $condition - limit: $limit - offset: $offset');
  633. error_log('getList: This is most probably caused by read_from_db_postprocess()');
  634. die('Unexpected error while reading from database! (Please check the error log for details, and open a bugreport)');
  635. }
  636. $this->result = $result;
  637. return true;
  638. }
  639. /**
  640. * Attempt to log a user in.
  641. * @param string $username
  642. * @param string $password
  643. * @return boolean true on successful login (i.e. password matches etc)
  644. */
  645. public function login($username, $password) {
  646. $username = escape_string($username);
  647. $table = table_by_key($this->db_table);
  648. $active = db_get_boolean(True);
  649. $query = "SELECT password FROM $table WHERE " . $this->id_field . "='$username' AND active='$active'";
  650. $result = db_query ($query);
  651. if ($result['rows'] == 1) {
  652. $row = db_array ($result['result']);
  653. $crypt_password = pacrypt ($password, $row['password']);
  654. if($row['password'] == $crypt_password) {
  655. return true;
  656. }
  657. }
  658. return false;
  659. }
  660. /**************************************************************************
  661. * functions to read protected variables
  662. */
  663. public function getStruct() {
  664. return $this->struct;
  665. }
  666. public function getMsg() {
  667. return $this->msg;
  668. }
  669. public function getId_field() {
  670. return $this->id_field;
  671. }
  672. /**
  673. * @return return value of previously called method
  674. */
  675. public function result() {
  676. return $this->result;
  677. }
  678. /**
  679. * compare two password fields
  680. * typically called from _validate_password2()
  681. * @param string $field1 - "password" field
  682. * @param string $field2 - "repeat password" field
  683. */
  684. protected function compare_password_fields($field1, $field2) {
  685. if ($this->RAWvalues[$field1] == $this->RAWvalues[$field2]) {
  686. unset ($this->errormsg[$field2]); # no need to warn about too short etc. passwords - it's enough to display this message at the 'password' field
  687. return true;
  688. }
  689. $this->errormsg[$field2] = Config::lang('pEdit_mailbox_password_text_error');
  690. return false;
  691. }
  692. /**
  693. * set field to default value
  694. * @param string $field - fieldname
  695. */
  696. protected function set_default_value($field) {
  697. if (isset($this->struct[$field]['default'])) {
  698. $this->RAWvalues[$field] = $this->struct[$field]['default'];
  699. }
  700. }
  701. /**************************************************************************
  702. * _inp_*()
  703. * functions for basic input validation
  704. * @return boolean - true if the value is valid, otherwise false
  705. * also set $this->errormsg[$field] if a value is invalid
  706. */
  707. /**
  708. * check if value is numeric and >= -1 (= minimum value for quota)
  709. */
  710. protected function _inp_num($field, $val) {
  711. $valid = is_numeric($val);
  712. if ($val < -1) $valid = false;
  713. if (!$valid) $this->errormsg[$field] = Config::Lang_f('must_be_numeric', $field);
  714. return $valid;
  715. # return (int)($val);
  716. }
  717. /**
  718. * check if value is (numeric) boolean - in other words: 0 or 1
  719. */
  720. protected function _inp_bool($field, $val) {
  721. if ($val == "0" || $val == "1") return true;
  722. $this->errormsg[$field] = Config::Lang_f('must_be_boolean', $field);
  723. return false;
  724. # return $val ? db_get_boolean(true): db_get_boolean(false);
  725. }
  726. /**
  727. * check if value of an enum field is in the list of allowed values
  728. */
  729. protected function _inp_enum($field, $val) {
  730. if(in_array($val, $this->struct[$field]['options'])) return true;
  731. $this->errormsg[$field] = Config::Lang_f('invalid_value_given', $field);
  732. return false;
  733. }
  734. /**
  735. * check if value of an enum field is in the list of allowed values
  736. */
  737. protected function _inp_enma($field, $val) {
  738. if(array_key_exists($val, $this->struct[$field]['options'])) return true;
  739. $this->errormsg[$field] = Config::Lang_f('invalid_value_given', $field);
  740. return false;
  741. }
  742. /**
  743. * check if a password is secure enough
  744. */
  745. protected function _inp_pass($field, $val){
  746. $validpass = validate_password($val); # returns array of error messages, or empty array on success
  747. if(count($validpass) == 0) return true;
  748. $this->errormsg[$field] = $validpass[0]; # TODO: honor all error messages, not only the first one?
  749. return false;
  750. }
  751. }
  752. /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */