3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
10 * Copyright © 2007-2014 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
29 * @author Johan Cwiklinski <johan@x-tnd.be>
30 * @copyright 2007-2014 The Galette Team
31 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
32 * @link http://galette.tuxfamily.org
33 * @since Available since 0.7dev - 2007-10-14
36 namespace Galette\Core
;
39 use Galette\Entity\Adherent
;
40 use Galette\Entity\Status
;
42 use Galette\IO\PdfMembersCards
;
43 use Galette\Repository\Members
;
46 * Preferences for galette
51 * @author Johan Cwiklinski <johan@x-tnd.be>
52 * @copyright 2007-2014 The Galette Team
53 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
54 * @link http://galette.tuxfamily.org
55 * @since Available since 0.7dev - 2007-10-14
57 * @property string $pref_theme Prefered theme
58 * @property-read string $vpref_email_newadh Comma separated list of mail senders
66 public const TABLE
= 'preferences';
67 public const PK
= 'nom_pref';
69 /** Postal address will be the one given in the preferences */
70 public const POSTAL_ADDRESS_FROM_PREFS
= 0;
71 /** Postal address will be the one of the selected staff member */
72 public const POSTAL_ADDRESS_FROM_STAFF
= 1;
74 /** Public pages stuff */
75 /** Public pages are publically visibles */
76 public const PUBLIC_PAGES_VISIBILITY_PUBLIC
= 0;
77 /** Public pages are visibles for up to date members only */
78 public const PUBLIC_PAGES_VISIBILITY_RESTRICTED
= 1;
79 /** Public pages are visibles for admin and staff members only */
80 public const PUBLIC_PAGES_VISIBILITY_PRIVATE
= 2;
82 public const LOG_DISABLED
= 0;
83 public const LOG_ENABLED
= 1;
85 /** No password strength */
86 public const PWD_NONE
= 0;
87 /** Weak password strength */
88 public const PWD_WEAK
= 1;
89 /** Medium password strength */
90 public const PWD_MEDIUM
= 2;
91 /** Strong password strength */
92 public const PWD_STRONG
= 3;
93 /** Very strong password strength */
94 public const PWD_VERY_STRONG
= 4;
96 private static $fields = array(
101 private static $defaults = array(
102 'pref_admin_login' => 'admin',
103 'pref_admin_pass' => 'admin',
104 'pref_nom' => 'Galette',
106 'pref_adresse' => '-',
107 'pref_adresse2' => '',
111 'pref_postal_adress' => self
::POSTAL_ADDRESS_FROM_PREFS
,
112 'pref_postal_staff_member' => '',
113 'pref_lang' => I18n
::DEFAULT_LANG
,
114 'pref_numrows' => 30,
115 'pref_log' => self
::LOG_ENABLED
,
116 'pref_statut' => Status
::DEFAULT_STATUS
,
117 /* Preferences for emails */
118 'pref_email_nom' => 'Galette',
119 'pref_email' => 'mail@domain.com',
120 'pref_email_newadh' => 'mail@domain.com',
121 'pref_bool_mailadh' => false,
122 'pref_editor_enabled' => false,
123 'pref_mail_method' => GaletteMail
::METHOD_DISABLED
,
124 'pref_mail_smtp' => '',
125 'pref_mail_smtp_host' => '',
126 'pref_mail_smtp_auth' => false,
127 'pref_mail_smtp_secure' => false,
128 'pref_mail_smtp_port' => '',
129 'pref_mail_smtp_user' => '',
130 'pref_mail_smtp_password' => '',
131 'pref_membership_ext' => 12,
132 'pref_beg_membership' => '',
133 'pref_membership_offermonths' => 0,
134 'pref_email_reply_to' => '',
135 'pref_website' => '',
136 /* Preferences for labels */
137 'pref_etiq_marges_v' => 10,
138 'pref_etiq_marges_h' => 10,
139 'pref_etiq_hspace' => 10,
140 'pref_etiq_vspace' => 5,
141 'pref_etiq_hsize' => 90,
142 'pref_etiq_vsize' => 35,
143 'pref_etiq_cols' => 2,
144 'pref_etiq_rows' => 7,
145 'pref_etiq_corps' => 12,
146 /* Preferences for members cards */
147 'pref_card_abrev' => 'GALETTE',
148 'pref_card_strip' => 'Gestion d\'Adherents en Ligne Extrêmement Tarabiscotée',
149 'pref_card_tcol' => 'FFFFFF',
150 'pref_card_scol' => '8C2453',
151 'pref_card_bcol' => '53248C',
152 'pref_card_hcol' => '248C53',
153 'pref_bool_display_title' => false,
154 'pref_card_address' => 1,
155 'pref_card_year' => '',
156 'pref_card_marges_v' => 15,
157 'pref_card_marges_h' => 20,
158 'pref_card_vspace' => 5,
159 'pref_card_hspace' => 10,
160 'pref_card_self' => 1,
161 'pref_theme' => 'default',
162 'pref_bool_publicpages' => true,
163 'pref_publicpages_visibility' => self
::PUBLIC_PAGES_VISIBILITY_RESTRICTED
,
164 'pref_bool_selfsubscribe' => true,
165 'pref_googleplus' => '',
166 'pref_facebook' => '',
167 'pref_twitter' => '',
169 'pref_linkedin' => '',
170 'pref_mail_sign' => "{NAME}\r\n\r\n{WEBSITE}\r\n{GOOGLEPLUS}\r\n{FACEBOOK}\r\n{TWITTER}\r\n{LINKEDIN}\r\n{VIADEO}",
171 /* New contribution script */
172 'pref_new_contrib_script' => '',
173 'pref_bool_wrap_mails' => true,
174 'pref_rss_url' => 'http://galette.eu/dc/index.php/feed/atom',
175 'pref_show_id' => false,
176 'pref_adhesion_form' => '\Galette\IO\PdfAdhesionForm',
177 'pref_mail_allow_unsecure' => false,
178 'pref_instance_uuid' => '',
179 'pref_registration_uuid' => '',
180 'pref_telemetry_date' => '',
181 'pref_registration_date' => '',
183 'pref_filter_account' => Members
::ALL_ACCOUNTS
,
184 'pref_galette_url' => '',
185 'pref_redirect_on_create' => Adherent
::AFTER_ADD_DEFAULT
,
186 /* Security related */
187 'pref_password_length' => 6,
188 'pref_password_blacklist' => false,
189 'pref_password_strength' => self
::PWD_NONE
192 // flagging required fields
193 private $required = array(
198 'pref_etiq_marges_v',
199 'pref_etiq_marges_h',
209 'pref_card_marges_v',
210 'pref_card_marges_h',
216 * Default constructor
218 * @param Db $zdb Db instance
219 * @param boolean $load Automatically load preferences on load
223 public function __construct(Db
$zdb, $load = true)
228 $this->checkUpdate();
233 * Check if all fields referenced in the default array does exists,
238 private function checkUpdate()
242 foreach (self
::$defaults as $k => $v) {
243 if (!isset($this->prefs
[$k])) {
244 $this->prefs
[$k] = $v;
246 'The field `' . $k . '` does not exists, Galette will attempt to create it.',
256 if ($proceed !== false) {
258 $insert = $this->zdb
->insert(self
::TABLE
);
261 'nom_pref' => ':nom_pref',
262 'val_pref' => ':val_pref'
265 $stmt = $this->zdb
->sql
->prepareStatementForSqlObject($insert);
267 foreach ($params as $p) {
270 'nom_pref' => $p['nom_pref'],
271 'val_pref' => $p['val_pref']
275 } catch (\Exception
$e) {
277 'Unable to add missing preferences.' . $e->getMessage(),
284 'Missing preferences were successfully stored into database.',
291 * Load current preferences from database.
295 public function load()
297 $this->prefs
= array();
300 $result = $this->zdb
->selectAll(self
::TABLE
);
301 foreach ($result as $pref) {
302 $this->prefs
[$pref->nom_pref
] = $pref->val_pref
;
305 } catch (\Exception
$e) {
307 'Preferences cannot be loaded. Galette should not work without ' .
308 'preferences. Exiting.',
316 * Set default preferences at install time
318 * @param string $lang language selected at install screen
319 * @param string $adm_login admin login entered at install time
320 * @param string $adm_pass admin password entered at install time
322 * @return boolean|\Exception
324 public function installInit($lang, $adm_login, $adm_pass)
327 //first, we drop all values
328 $delete = $this->zdb
->delete(self
::TABLE
);
329 $this->zdb
->execute($delete);
331 //we then replace default values with the ones user has selected
332 $values = self
::$defaults;
333 $values['pref_lang'] = $lang;
334 $values['pref_admin_login'] = $adm_login;
335 $values['pref_admin_pass'] = $adm_pass;
336 $values['pref_card_year'] = date('Y');
338 $insert = $this->zdb
->insert(self
::TABLE
);
341 'nom_pref' => ':nom_pref',
342 'val_pref' => ':val_pref'
345 $stmt = $this->zdb
->sql
->prepareStatementForSqlObject($insert);
347 foreach ($values as $k => $v) {
357 'Default preferences were successfully stored into database.',
361 } catch (\Exception
$e) {
363 'Unable to initialize default preferences.' . $e->getMessage(),
371 * Returns all preferences keys
375 public function getFieldsNames()
377 return array_keys($this->prefs
);
383 * @param array $values Values
384 * @param Login $login Logged in user
388 public function check(array $values, Login
$login)
390 $insert_values = array();
391 if ($login->isSuperAdmin() && GALETTE_MODE
!== 'DEMO') {
392 $this->required
[] = 'pref_admin_login';
396 foreach ($this->getFieldsNames() as $fieldname) {
397 if (isset($values[$fieldname])) {
398 $value = trim($values[$fieldname]);
403 // now, check validity
405 switch ($fieldname) {
406 case 'pref_admin_login':
407 if (GALETTE_MODE
=== 'DEMO') {
409 'Trying to set superadmin login while in DEMO.',
413 if (strlen($value) < 4) {
414 $this->errors
[] = _T("- The username must be composed of at least 4 characters!");
416 //check if login is already taken
417 if ($login->loginExists($value)) {
418 $this->errors
[] = _T("- This username is already used by another member !");
424 if (!is_numeric($value) ||
$value < 0) {
425 $this->errors
[] = _T("- The numbers and measures have to be integers!");
428 case 'pref_etiq_marges_h':
429 case 'pref_etiq_marges_v':
430 case 'pref_etiq_hspace':
431 case 'pref_etiq_vspace':
432 case 'pref_etiq_hsize':
433 case 'pref_etiq_vsize':
434 case 'pref_etiq_cols':
435 case 'pref_etiq_rows':
436 case 'pref_etiq_corps':
437 case 'pref_card_marges_v':
438 case 'pref_card_marges_h':
439 case 'pref_card_hspace':
440 case 'pref_card_vspace':
441 // prevent division by zero
442 if ($fieldname == 'pref_numrows' && $value == '0') {
445 if (!is_numeric($value) ||
$value < 0) {
446 $this->errors
[] = _T("- The numbers and measures have to be integers!");
449 case 'pref_card_tcol':
450 // Set strip text color to white
451 if (!preg_match("/#([0-9A-F]{6})/i", $value)) {
455 case 'pref_card_scol':
456 case 'pref_card_bcol':
457 case 'pref_card_hcol':
458 // Set strip background colors to black
459 if (!preg_match("/#([0-9A-F]{6})/i", $value)) {
463 case 'pref_admin_pass':
464 if (GALETTE_MODE
== 'DEMO') {
466 'Trying to set superadmin pass while in DEMO.',
470 $pwcheck = new \Galette\Util\
Password($this);
471 $pwcheck->addPersonalInformation(['pref_admin_login' => $this->pref_admin_login
]);
472 if (!$pwcheck->isValid($value)) {
473 $this->errors
= array_merge(
475 $pwcheck->getErrors()
480 case 'pref_membership_ext':
481 if (!is_numeric($value) ||
$value < 0) {
482 $this->errors
[] = _T("- Invalid number of months of membership extension.");
485 case 'pref_beg_membership':
486 $beg_membership = explode("/", $value);
487 if (count($beg_membership) != 2) {
488 $this->errors
[] = _T("- Invalid format of beginning of membership.");
491 if (!checkdate($beg_membership[1], $beg_membership[0], $now['year'])) {
492 $this->errors
[] = _T("- Invalid date for beginning of membership.");
496 case 'pref_membership_offermonths':
497 if (!is_numeric($value) ||
$value < 0) {
498 $this->errors
[] = _T("- Invalid number of offered months.");
501 case 'pref_card_year':
502 if ($value !== 'DEADLINE' && !preg_match('/^(?:\d{4}|\d{2})(\D?)(?:\d{4}|\d{2})$/', $value)) {
503 $this->errors
[] = _T("- Invalid year for cards.");
509 $insert_values[$fieldname] = $value;
514 GALETTE_MODE
!== 'DEMO'
515 && isset($insert_values['pref_mail_method'])
517 if ($insert_values['pref_mail_method'] > GaletteMail
::METHOD_DISABLED
) {
519 !isset($insert_values['pref_email_nom'])
520 ||
$insert_values['pref_email_nom'] == ''
522 $this->errors
[] = _T("- You must indicate a sender name for emails!");
525 !isset($insert_values['pref_email'])
526 ||
$insert_values['pref_email'] == ''
528 $this->errors
[] = _T("- You must indicate an email address Galette should use to send emails!");
530 if ($insert_values['pref_mail_method'] == GaletteMail
::METHOD_SMTP
) {
532 !isset($insert_values['pref_mail_smtp_host'])
533 ||
$insert_values['pref_mail_smtp_host'] == ''
535 $this->errors
[] = _T("- You must indicate the SMTP server you want to use!");
539 $insert_values['pref_mail_method'] == GaletteMail
::METHOD_GMAIL
540 ||
($insert_values['pref_mail_method'] == GaletteMail
::METHOD_SMTP
541 && $insert_values['pref_mail_smtp_auth'])
544 !isset($insert_values['pref_mail_smtp_user'])
545 ||
trim($insert_values['pref_mail_smtp_user']) == ''
547 $this->errors
[] = _T("- You must provide a login for SMTP authentication.");
550 !isset($insert_values['pref_mail_smtp_password'])
551 ||
($insert_values['pref_mail_smtp_password']) == ''
553 $this->errors
[] = _T("- You must provide a password for SMTP authentication.");
560 isset($insert_values['pref_beg_membership'])
561 && $insert_values['pref_beg_membership'] != ''
562 && isset($insert_values['pref_membership_ext'])
563 && $insert_values['pref_membership_ext'] != ''
565 $this->errors
[] = _T("- Default membership extention and beginning of membership are mutually exclusive.");
569 isset($insert_values['pref_membership_offermonths'])
570 && (int)$insert_values['pref_membership_offermonths'] > 0
571 && isset($insert_values['pref_membership_ext'])
572 && $insert_values['pref_membership_ext'] != ''
574 $this->errors
[] = _T("- Offering months is only compatible with beginning of membership.");
577 // missing required fields?
578 foreach ($this->required
as $val) {
579 if (!isset($values[$val]) ||
isset($values[$val]) && trim($values[$val]) == '') {
580 $this->errors
[] = str_replace(
583 _T("- Mandatory field %field empty.")
588 if (GALETTE_MODE
!== 'DEMO' && isset($values['pref_admin_pass_check'])) {
589 // Check passwords. Hash will be done into the Preferences class
590 if (strcmp($insert_values['pref_admin_pass'], $values['pref_admin_pass_check']) != 0) {
591 $this->errors
[] = _T("Passwords mismatch");
596 if (isset($insert_values['pref_postal_adress'])) {
597 $value = $insert_values['pref_postal_adress'];
598 if ($value == Preferences
::POSTAL_ADDRESS_FROM_PREFS
) {
599 if (isset($insert_values['pref_postal_staff_member'])) {
600 unset($insert_values['pref_postal_staff_member']);
602 } elseif ($value == Preferences
::POSTAL_ADDRESS_FROM_STAFF
) {
603 if (!isset($value) ||
$value < 1) {
604 $this->errors
[] = _T("You have to select a staff member");
609 // update preferences
610 foreach ($insert_values as $champ => $valeur) {
612 $login->isSuperAdmin()
613 ||
(!$login->isSuperAdmin()
614 && ($champ != 'pref_admin_pass' && $champ != 'pref_admin_login'))
617 ($champ == "pref_admin_pass" && $_POST['pref_admin_pass'] != '')
618 ||
($champ != "pref_admin_pass")
620 $this->$champ = $valeur;
625 return 0 === count($this->errors
);
629 * Will store all preferences in the database
633 public function store()
636 $this->zdb
->connection
->beginTransaction();
637 $update = $this->zdb
->update(self
::TABLE
);
640 'val_pref' => ':val_pref'
642 )->where
->equalTo('nom_pref', ':nom_pref');
644 $stmt = $this->zdb
->sql
->prepareStatementForSqlObject($update);
646 foreach (self
::$defaults as $k => $v) {
648 GALETTE_MODE
== 'DEMO'
649 && in_array($k, ['pref_admin_pass', 'pref_admin_login', 'pref_mail_method'])
653 Analog
::log('Storing ' . $k, Analog
::DEBUG
);
655 $value = $this->prefs
[$k];
656 //do not store pdf_adhesion_form, it's designed to be overriden by plugin
657 if ($k === 'pref_adhesion_form') {
658 if (trim($v) == '') {
659 //Reset to default, should not be empty
660 $v = self
::$defaults['pref_adhesion_form'];
667 'val_pref' => $value,
672 $this->zdb
->connection
->commit();
674 'Preferences were successfully stored into database.',
678 } catch (\Exception
$e) {
679 $this->zdb
->connection
->rollBack();
683 $messages[] = $e->getMessage();
684 } while ($e = $e->getPrevious());
687 'Unable to store preferences | ' . print_r($messages, true),
695 * Returns postal address
697 * @return string postal address
699 public function getPostalAddress()
710 $replacements = null;
712 if ($this->prefs
['pref_postal_adress'] == self
::POSTAL_ADDRESS_FROM_PREFS
) {
713 $_address = $this->prefs
['pref_adresse'];
714 if ($this->prefs
['pref_adresse2'] && $this->prefs
['pref_adresse2'] != '') {
715 $_address .= "\n" . $this->prefs
['pref_adresse2'];
717 $replacements = array(
718 $this->prefs
['pref_nom'],
721 $this->prefs
['pref_cp'],
722 $this->prefs
['pref_ville'],
723 $this->prefs
['pref_pays']
726 //get selected staff member address
727 $adh = new Adherent($this->zdb
, (int)$this->prefs
['pref_postal_staff_member']);
728 $_complement = preg_replace(
729 array('/%name/', '/%status/'),
730 array($this->prefs
['pref_nom'], $adh->sstatus
),
731 _T("%name association's %status")
733 $_address = $adh->address
;
734 if ($adh->address_continuation
&& $adh->address_continuation
!= '') {
735 $_address .= "\n" . $adh->address_continuation
;
737 $replacements = array(
738 $adh->sfullname
. "\n",
747 /*FIXME: i18n fails :/ */
751 _T("%name\n%complement\n%address\n%zip %town - %country")
756 "%name%complement%address\n%zip %town - %country"
762 * Are public pages visibles?
764 * @param Authentication $login Authenticaqtion instance
768 public function showPublicPages(Authentication
$login)
770 if ($this->prefs
['pref_bool_publicpages']) {
771 //if public pages are actives, let's check if we
772 //display them for curent call
773 switch ($this->prefs
['pref_publicpages_visibility']) {
774 case self
::PUBLIC_PAGES_VISIBILITY_PUBLIC
:
775 //pages are publically visibles
778 case self
::PUBLIC_PAGES_VISIBILITY_RESTRICTED
:
779 //pages should be displayed only for up to date members
790 case self
::PUBLIC_PAGES_VISIBILITY_PRIVATE
:
791 //pages should be displayed only for staff and admins
792 if ($login->isAdmin() ||
$login->isStaff()) {
799 //should never be there
809 * Global getter method
811 * @param string $name name of the property we want to retrive
813 * @return false|object the called property
815 public function __get($name)
817 $forbidden = array('defaults');
818 $virtuals = array('vpref_email_newadh');
820 if (!in_array($name, $forbidden) && isset($this->prefs
[$name])) {
822 GALETTE_MODE
=== 'DEMO'
823 && $name == 'pref_mail_method'
825 return GaletteMail
::METHOD_DISABLED
;
827 if ($name == 'pref_adhesion_form' && $this->prefs
[$name] == '') {
828 $this->prefs
[$name] = self
::$defaults['pref_adhesion_form'];
830 $value = $this->prefs
[$name];
831 if (TYPE_DB
=== \Galette\Core\Db
::PGSQL
) {
832 if ($value === 'f') {
837 if (in_array($name, ['pref_email_newadh'])) {
838 $values = explode(',', $value);
839 $value = $values[0]; //take first as default
844 } elseif (in_array($name, $virtuals)) {
845 $virtual = str_replace('vpref_', 'pref_', $name);
846 return explode(',', $this->prefs
[$virtual]);
849 'Preference `' . $name . '` is not set or is forbidden',
857 * Get default preferences
861 public function getDefaults()
863 return self
::$defaults;
867 * Global setter method
869 * @param string $name name of the property we want to assign a value to
870 * @param object $value a relevant value for the property
874 public function __set($name, $value)
876 //does this pref exists ?
877 if (!array_key_exists($name, self
::$defaults)) {
879 'Trying to set a preference value which does not seem to exist ('
887 $name == 'pref_email'
888 ||
$name == 'pref_email_newadh'
889 ||
$name == 'pref_email_reply_to'
891 if (GALETTE_MODE
=== 'DEMO') {
893 'Trying to set pref_email while in DEMO.',
899 //check emails validity
900 //may be a comma separated list of valid emails identifiers:
901 //"The Name <mail@domain.com>,The Other <other@mail.com>" expect for reply_to.
903 if (trim($value) != '') {
904 if ($name == 'pref_email_newadh') {
905 $addresses = explode(',', $value);
907 $addresses = [$value];
910 foreach ($addresses as $address) {
911 if (!GaletteMail
::isValidEmail($address)) {
912 $msg = str_replace('%s', $address, _T("Invalid E-Mail address: %s"));
913 Analog
::log($msg, Analog
::WARNING
);
914 $this->errors
[] = $msg;
919 //some values need to be changed (eg. passwords)
920 if ($name == 'pref_admin_pass') {
921 $value = password_hash($value, PASSWORD_BCRYPT
);
924 //okay, let's update value
925 $this->prefs
[$name] = $value;
929 * Get instance URL from configuration (if set) or guessed if not
933 public function getURL()
936 if (isset($this->prefs
['pref_galette_url']) && !empty($this->prefs
['pref_galette_url'])) {
937 $url = $this->prefs
['pref_galette_url'];
939 $url = $this->getDefaultURL();
945 * Get default URL (when not setted by user in preferences)
949 public function getDefaultURL()
951 $scheme = (isset($_SERVER['HTTPS']) ?
'https' : 'http');
952 $uri = $scheme . '://' . $_SERVER['HTTP_HOST'];
957 * Check member cards sizes
958 * Always a A4/portrait
962 public function checkCardsSizes()
964 $warning_detected = [];
968 $size = $this->pref_card_marges_h
* 2;
970 $size +
= PdfMembersCards
::getWidth() * PdfMembersCards
::getCols();
972 $size +
= $this->pref_card_hspace
* (PdfMembersCards
::getCols() - 1);
974 $warning_detected[] = _T('Current cards configuration may exceed page width!');
979 $size = $this->pref_card_marges_v
* 2;
981 $size +
= PdfMembersCards
::getHeight() * PdfMembersCards
::getRows();
983 $size +
= $this->pref_card_vspace
* (PdfMembersCards
::getRows() - 1);
985 $warning_detected[] = _T('Current cards configuration may exceed page height!');
988 return $warning_detected;
996 public function getErrors()
998 return $this->errors
;