PFAHandler.php 37 KB

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