Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

PFAHandler.php 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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() - but will NOT be decoded automatically)
  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. } elseif (db_sqlite()) {
  483. $formatted_date = "strftime(###KEY###, '" . escape_string(Config::Lang('dateformat_mysql')) . "')";
  484. # $base64_decode = "base64_decode(###KEY###)";
  485. } else {
  486. $formatted_date = "DATE_FORMAT(###KEY###, '" . escape_string(Config::Lang('dateformat_mysql')) . "')";
  487. # $base64_decode = "FROM_BASE64(###KEY###)"; # requires MySQL >= 5.6
  488. }
  489. $colformat = array(
  490. # 'ts' fields are always returned as $formatted_date, and the raw value as _$field
  491. 'ts' => "$formatted_date AS ###KEY###, ###KEY### AS _###KEY###",
  492. # 'bool' fields are always returned as 0/1, additonally _$field contains yes/no (already translated)
  493. 'bool' => "CASE ###KEY### WHEN '" . db_get_boolean(true) . "' THEN '1' WHEN '" . db_get_boolean(false) . "' THEN '0' END as ###KEY###," .
  494. "CASE ###KEY### WHEN '" . db_get_boolean(true) . "' THEN '$yes' WHEN '" . db_get_boolean(false) . "' THEN '$no' END as _###KEY###",
  495. # 'b64p' => "$base64_decode AS ###KEY###", # not available in MySQL < 5.6, therefore not decoding for any database
  496. );
  497. # get list of fields to display
  498. $extrafrom = "";
  499. foreach($this->struct as $key=>$row) {
  500. if ( ($row['display_in_list'] != 0 || $row['display_in_form'] != 0) && $row['not_in_db'] == 0 ) {
  501. if ($row['select'] != '') $key = $row['select'];
  502. if ($row['extrafrom'] != '') $extrafrom = $extrafrom . " " . $row['extrafrom'] . "\n";
  503. if (isset($colformat[$row['type']])) {
  504. $select_cols[] = str_replace('###KEY###', $key, $colformat[$row['type']] );
  505. } else {
  506. $select_cols[] = $key;
  507. }
  508. }
  509. }
  510. $cols = join(',', $select_cols);
  511. $table = table_by_key($this->db_table);
  512. $additional_where = '';
  513. if ($this->domain_field != "") {
  514. $additional_where .= " AND " . db_in_clause($this->domain_field, $this->allowed_domains);
  515. }
  516. # if logged in as user, restrict to the items the user is allowed to see
  517. if ( (!$this->is_admin) && $this->user_field != '') {
  518. $additional_where .= " AND " . $this->user_field . " = '" . escape_string($this->username) . "' ";
  519. }
  520. if (is_array($condition)) {
  521. if (isset($condition['_']) && count($this->searchfields) > 0) {
  522. $simple_search = array();
  523. foreach ($this->searchfields as $field) {
  524. $simple_search[] = "$field LIKE '%" . escape_string($condition['_']) . "%'";
  525. }
  526. $additional_where .= " AND ( " . join(" OR ", $simple_search) . " ) ";
  527. unset($condition['_']);
  528. }
  529. $where = db_where_clause($condition, $this->struct, $additional_where, $searchmode);
  530. } else {
  531. if ($condition == "") $condition = '1=1';
  532. $where = " WHERE ( $condition ) $additional_where";
  533. }
  534. return array(
  535. 'select_cols' => " SELECT $cols ",
  536. 'from_where_order' => " FROM $table $extrafrom $where ORDER BY " . $this->order_by,
  537. );
  538. }
  539. /**
  540. * getPagebrowser
  541. *
  542. * @param array or string condition (see build_select_query() for details)
  543. * @param array searchmode - (see build_select_query() for details)
  544. * @return array - pagebrowser keys ("aa-cz", "de-pf", ...)
  545. */
  546. public function getPagebrowser($condition, $searchmode) {
  547. $queryparts = $this->build_select_query($condition, $searchmode);
  548. return create_page_browser($this->label_field, $queryparts['from_where_order']);
  549. }
  550. /**
  551. * read_from_db
  552. *
  553. * reads all fields specified in $this->struct from the database
  554. * and auto-converts them to database-independent values based on the field type (see $colformat)
  555. *
  556. * calls $this->read_from_db_postprocess() to postprocess the result
  557. *
  558. * @param array or string condition -see build_select_query() for details
  559. * @param array searchmode - see build_select_query() for details
  560. * @param integer limit - maximum number of rows to return
  561. * @param integer offset - number of first row to return
  562. * @return array - rows (as associative array, with the ID as key)
  563. */
  564. protected function read_from_db($condition, $searchmode = array(), $limit=-1, $offset=-1) {
  565. $queryparts = $this->build_select_query($condition, $searchmode);
  566. $query = $queryparts['select_cols'] . $queryparts['from_where_order'];
  567. $limit = (int) $limit; # make sure $limit and $offset are really integers
  568. $offset = (int) $offset;
  569. if ($limit > -1 && $offset > -1) {
  570. $query .= " LIMIT $limit OFFSET $offset ";
  571. }
  572. $result = db_query($query);
  573. $db_result = array();
  574. if ($result['rows'] != 0) {
  575. while ($row = db_assoc ($result['result'])) {
  576. $db_result[$row[$this->id_field]] = $row;
  577. }
  578. }
  579. $db_result = $this->read_from_db_postprocess($db_result);
  580. return $db_result;
  581. }
  582. /**
  583. * allows to postprocess the database result
  584. * called by read_from_db()
  585. */
  586. protected function read_from_db_postprocess($db_result) {
  587. return $db_result;
  588. }
  589. /**
  590. * get the values of an item
  591. * @param boolean (optional) - if false, $this->errormsg[] will not be filled in case of errors
  592. * @return bool - true if item was found
  593. * The data is stored in $this->result (as associative array of column => value)
  594. * error messages (if any) are stored in $this->errormsg
  595. */
  596. public function view($errors=true) {
  597. $result = $this->read_from_db(array($this->id_field => $this->id) );
  598. if (count($result) == 1) {
  599. $this->result = $result[$this->id];
  600. return true;
  601. }
  602. if ($errors) $this->errormsg[] = Config::lang($this->msg['error_does_not_exist']);
  603. # $this->errormsg[] = $result['error'];
  604. return false;
  605. }
  606. /**
  607. * get a list of one or more items with all values
  608. * @param array or string $condition - see read_from_db for details
  609. * WARNING: will be changed to array only in the future, with an option to include a raw string inside the array
  610. * @param array - modes to use if $condition is an array - see read_from_db for details
  611. * @param integer limit - maximum number of rows to return
  612. * @param integer offset - number of first row to return
  613. * @return bool - always true, no need to check ;-) (if $result is not an array, getList die()s)
  614. * The data is stored in $this->result (as array of rows, each row is an associative array of column => value)
  615. */
  616. public function getList($condition, $searchmode = array(), $limit=-1, $offset=-1) {
  617. if (is_array($condition)) {
  618. $real_condition = array();
  619. foreach ($condition as $key => $value) {
  620. # allow only access to fields the user can access to avoid information leaks via search parameters
  621. if (isset($this->struct[$key]) && ($this->struct[$key]['display_in_list'] || $this->struct[$key]['display_in_form']) ) {
  622. $real_condition[$key] = $value;
  623. } elseif (($key == '_') && count($this->searchfields)) {
  624. $real_condition[$key] = $value;
  625. } else {
  626. $this->errormsg[] = "Ignoring unknown search field $key";
  627. }
  628. }
  629. } else {
  630. # warning: no sanity checks are applied if $condition is not an array!
  631. $real_condition = $condition;
  632. }
  633. $result = $this->read_from_db($real_condition, $searchmode, $limit, $offset);
  634. if (!is_array($result)) {
  635. error_log('getList: read_from_db didn\'t return an array. table: ' . $this->db_table . ' - condition: $condition - limit: $limit - offset: $offset');
  636. error_log('getList: This is most probably caused by read_from_db_postprocess()');
  637. die('Unexpected error while reading from database! (Please check the error log for details, and open a bugreport)');
  638. }
  639. $this->result = $result;
  640. return true;
  641. }
  642. /**
  643. * Attempt to log a user in.
  644. * @param string $username
  645. * @param string $password
  646. * @return boolean true on successful login (i.e. password matches etc)
  647. */
  648. public function login($username, $password) {
  649. $username = escape_string($username);
  650. $table = table_by_key($this->db_table);
  651. $active = db_get_boolean(True);
  652. $query = "SELECT password FROM $table WHERE " . $this->id_field . "='$username' AND active='$active'";
  653. $result = db_query ($query);
  654. if ($result['rows'] == 1) {
  655. $row = db_array ($result['result']);
  656. $crypt_password = pacrypt ($password, $row['password']);
  657. if($row['password'] == $crypt_password) {
  658. return true;
  659. }
  660. }
  661. return false;
  662. }
  663. /**************************************************************************
  664. * functions to read protected variables
  665. */
  666. public function getStruct() {
  667. return $this->struct;
  668. }
  669. public function getMsg() {
  670. return $this->msg;
  671. }
  672. public function getId_field() {
  673. return $this->id_field;
  674. }
  675. /**
  676. * @return return value of previously called method
  677. */
  678. public function result() {
  679. return $this->result;
  680. }
  681. /**
  682. * compare two password fields
  683. * typically called from _validate_password2()
  684. * @param string $field1 - "password" field
  685. * @param string $field2 - "repeat password" field
  686. */
  687. protected function compare_password_fields($field1, $field2) {
  688. if ($this->RAWvalues[$field1] == $this->RAWvalues[$field2]) {
  689. unset ($this->errormsg[$field2]); # no need to warn about too short etc. passwords - it's enough to display this message at the 'password' field
  690. return true;
  691. }
  692. $this->errormsg[$field2] = Config::lang('pEdit_mailbox_password_text_error');
  693. return false;
  694. }
  695. /**
  696. * set field to default value
  697. * @param string $field - fieldname
  698. */
  699. protected function set_default_value($field) {
  700. if (isset($this->struct[$field]['default'])) {
  701. $this->RAWvalues[$field] = $this->struct[$field]['default'];
  702. }
  703. }
  704. /**************************************************************************
  705. * _inp_*()
  706. * functions for basic input validation
  707. * @return boolean - true if the value is valid, otherwise false
  708. * also set $this->errormsg[$field] if a value is invalid
  709. */
  710. /**
  711. * check if value is numeric and >= -1 (= minimum value for quota)
  712. */
  713. protected function _inp_num($field, $val) {
  714. $valid = is_numeric($val);
  715. if ($val < -1) $valid = false;
  716. if (!$valid) $this->errormsg[$field] = Config::Lang_f('must_be_numeric', $field);
  717. return $valid;
  718. # return (int)($val);
  719. }
  720. /**
  721. * check if value is (numeric) boolean - in other words: 0 or 1
  722. */
  723. protected function _inp_bool($field, $val) {
  724. if ($val == "0" || $val == "1") return true;
  725. $this->errormsg[$field] = Config::Lang_f('must_be_boolean', $field);
  726. return false;
  727. # return $val ? db_get_boolean(true): db_get_boolean(false);
  728. }
  729. /**
  730. * check if value of an enum field is in the list of allowed values
  731. */
  732. protected function _inp_enum($field, $val) {
  733. if(in_array($val, $this->struct[$field]['options'])) return true;
  734. $this->errormsg[$field] = Config::Lang_f('invalid_value_given', $field);
  735. return false;
  736. }
  737. /**
  738. * check if value of an enum field is in the list of allowed values
  739. */
  740. protected function _inp_enma($field, $val) {
  741. if(array_key_exists($val, $this->struct[$field]['options'])) return true;
  742. $this->errormsg[$field] = Config::Lang_f('invalid_value_given', $field);
  743. return false;
  744. }
  745. /**
  746. * check if a password is secure enough
  747. */
  748. protected function _inp_pass($field, $val){
  749. $validpass = validate_password($val); # returns array of error messages, or empty array on success
  750. if(count($validpass) == 0) return true;
  751. $this->errormsg[$field] = $validpass[0]; # TODO: honor all error messages, not only the first one?
  752. return false;
  753. }
  754. }
  755. /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */