您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

PFAHandler.php 36KB

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