forked from klaftertief/members-legacy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
extension.driver.php
1167 lines (1006 loc) · 38.2 KB
/
extension.driver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
include_once(TOOLKIT . '/class.entrymanager.php');
include_once(TOOLKIT . '/class.sectionmanager.php');
include_once(EXTENSIONS . '/members/lib/class.role.php');
include_once(EXTENSIONS . '/members/lib/class.members.php');
Class extension_Members extends Extension {
/**
* @var boolean $initialised
*/
private static $initialised = false;
/**
* @var integer $members_section
*/
private static $members_section = null;
/**
* @var array $member_fields
*/
private static $member_fields = array(
'memberusername', 'memberemail'
);
/**
* @var array $member_events
*/
private static $member_events = array(
'members_regenerate_activation_code',
'members_activate_account',
'members_generate_recovery_code',
'members_reset_password'
);
/**
* Holds the current Member class that is in place, for this release
* this will always the SymphonyMember, which extends Member and implements
* the Member interface.
*
* @see getMemberDriver()
* @var Member $Member
*/
protected $Member = null;
/**
* Accessible via `getField()`
*
* @see getField()
* @var array $fields
*/
protected static $fields = array();
/**
* Accessible via `getFieldHandle()`
*
* @see getFieldHandle()
* @var array $handles
*/
protected static $handles = array();
/**
* Returns an associative array of errors that have occurred while
* logging in or preforming a Members custom event. The key is the
* field's `element_name` and the value is the error message.
*
* @var array $_errors
*/
public static $_errors = array();
/**
* By default this is set to `false`. If a Member attempts to login
* but is unsuccessful, this will be `true`. Useful in the
* `appendLoginStatusToEventXML` function to determine whether to display
* `extension_Members::$_errors` or not.
*
* @var boolean $failed_login_attempt
*/
public static $_failed_login_attempt = false;
/**
* An instance of the EntryManager class. Keep in mind that the Field Manager
* and Section Manager are accessible via `$entryManager->fieldManager` and
* `$entryManager->sectionManager` respectively.
*
* @var EntryManager $entryManager
*/
public static $entryManager = null;
/**
* Only create a Member object on the Frontend of the site.
* There is no need to create this in the Administration context
* as authenticated users are Authors and are handled by Symphony,
* not this extension.
*/
public function __construct() {
if(class_exists('Symphony') && Symphony::Engine() instanceof Frontend) {
$this->Member = new SymphonyMember($this);
}
extension_Members::$entryManager = new EntryManager(Symphony::Engine());
if(!extension_Members::$initialised) {
extension_Members::initialise();
}
}
/**
* Loops over the configuration to detect the capabilities of this
* Members setup. Populates two array's, one for Field objects, and
* one for Field handles.
*/
public static function initialise() {
extension_Members::$initialised = true;
$sectionManager = extension_Members::$entryManager->sectionManager;
$membersSectionSchema = array();
if(
!is_null(extension_Members::getMembersSection()) &&
is_numeric(extension_Members::getMembersSection())
) {
$memberSection = $sectionManager->fetch(
extension_Members::getMembersSection()
);
if($memberSection instanceof Section) {
$membersSectionSchema = $memberSection->fetchFieldsSchema();
}
else {
Symphony::$Log->pushToLog(
__("The Member's section, %d, saved in the configuration could not be found.", array(extension_Members::getMembersSection())),
E_ERROR, true
);
}
}
foreach($membersSectionSchema as $field) {
if($field['type'] == 'membertimezone') {
extension_Members::initialiseField($field, 'timezone');
continue;
}
if($field['type'] == 'memberrole') {
extension_Members::initialiseField($field, 'role');
continue;
}
if($field['type'] == 'memberactivation') {
extension_Members::initialiseField($field, 'activation');
continue;
}
if($field['type'] == 'memberusername') {
extension_Members::initialiseField($field, 'identity');
continue;
}
if($field['type'] == 'memberemail') {
extension_Members::initialiseField($field, 'email');
continue;
}
if($field['type'] == 'memberpassword') {
extension_Members::initialiseField($field, 'authentication');
continue;
}
}
}
private static function initialiseField($field, $name) {
extension_Members::$fields[$name] = extension_Members::$entryManager->fieldManager->fetch($field['id']);
if(extension_Members::$fields[$name] instanceof Field) {
extension_Members::$handles[$name] = $field['element_name'];
}
}
public function about(){
return array(
'name' => 'Members',
'version' => '1.1.1',
'release-date' => '2011-08-13',
'author' => array(
'name' => 'Symphony Team',
'website' => 'http://www.symphony-cms.com',
'email' => '[email protected]'
),
'description' => 'Frontend Membership extension for Symphony CMS'
);
}
public function fetchNavigation(){
return array(
array(
'location' => __('System'),
'name' => __('Member Roles'),
'link' => '/roles/'
)
);
}
public function getSubscribedDelegates(){
return array(
/*
FRONTEND
*/
array(
'page' => '/frontend/',
'delegate' => 'FrontendPageResolved',
'callback' => 'checkFrontendPagePermissions'
),
array(
'page' => '/frontend/',
'delegate' => 'FrontendParamsResolve',
'callback' => 'addMemberDetailsToPageParams'
),
array(
'page' => '/frontend/',
'delegate' => 'FrontendProcessEvents',
'callback' => 'appendLoginStatusToEventXML'
),
array(
'page' => '/frontend/',
'delegate' => 'EventPreSaveFilter',
'callback' => 'checkEventPermissions'
),
array(
'page' => '/frontend/',
'delegate' => 'EventPostSaveFilter',
'callback' => 'processPostSaveFilter'
),
/*
BACKEND
*/
array(
'page' => '/backend/',
'delegate' => 'AdminPagePreGenerate',
'callback' => 'appendAssets'
),
array(
'page' => '/system/preferences/',
'delegate' => 'AddCustomPreferenceFieldsets',
'callback' => 'appendPreferences'
),
array(
'page' => '/system/preferences/',
'delegate' => 'Save',
'callback' => 'savePreferences'
),
array(
'page' => '/blueprints/events/new/',
'delegate' => 'AppendEventFilter',
'callback' => 'appendFilter'
),
array(
'page' => '/blueprints/events/edit/',
'delegate' => 'AppendEventFilter',
'callback' => 'appendFilter'
),
);
}
/*-------------------------------------------------------------------------
Versioning:
-------------------------------------------------------------------------*/
/**
* Sets the `cookie-prefix` of `sym-members` in the Configuration
* and creates all of the field's tables in the database
*
* @return boolean
*/
public function install(){
Symphony::Configuration()->set('cookie-prefix', 'sym-members', 'members');
Administration::instance()->saveConfig();
return Symphony::Database()->import("
DROP TABLE IF EXISTS `tbl_members_roles`;
CREATE TABLE `tbl_members_roles` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`handle` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `handle` (`handle`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `tbl_members_roles` VALUES(1, 'Public', 'public');
DROP TABLE IF EXISTS `tbl_members_roles_event_permissions`;
CREATE TABLE `tbl_members_roles_event_permissions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`role_id` int(11) unsigned NOT NULL,
`event` varchar(50) NOT NULL,
`action` varchar(60) NOT NULL,
`level` smallint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `role_id` (`role_id`,`event`,`action`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
DROP TABLE IF EXISTS `tbl_members_roles_forbidden_pages`;
CREATE TABLE `tbl_members_roles_forbidden_pages` (
`id` int(11) unsigned NOT NULL auto_increment,
`role_id` int(11) unsigned NOT NULL,
`page_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `role_id` (`role_id`,`page_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
");
}
/**
* Remove's all `members` Configuration values and then drops all the
* database tables created by the Members extension
*
* @return boolean
*/
public function uninstall(){
Symphony::Configuration()->remove('members');
Administration::instance()->saveConfig();
return Symphony::Database()->query("
DROP TABLE IF EXISTS
`tbl_fields_memberusername`,
`tbl_fields_memberpassword`,
`tbl_fields_memberemail`,
`tbl_fields_memberactivation`,
`tbl_fields_memberrole`,
`tbl_fields_membertimezone`,
`tbl_members_roles`,
`tbl_members_roles_event_permissions`,
`tbl_members_roles_forbidden_pages`
");
}
public function update($previousVersion) {
if(version_compare($previousVersion, '1.0 Beta 3', '<')) {
$activation_table = Symphony::Database()->fetchRow(0, "SHOW TABLES LIKE 'tbl_fields_memberactivation';");
if(!empty($activation_table)) {
Symphony::Database()->import("
ALTER TABLE `tbl_fields_memberactivation` ADD `auto_login` ENUM('yes','no') NULL DEFAULT 'yes';
ALTER TABLE `tbl_fields_memberactivation` ADD `deny_login` ENUM('yes','no') NULL DEFAULT 'yes';
");
}
$password_table = Symphony::Database()->fetchRow(0, "SHOW TABLES LIKE 'tbl_fields_memberpassword';");
if(!empty($password_table)) {
Symphony::Database()->query("
ALTER TABLE `tbl_fields_memberpassword` ADD `code_expiry` VARCHAR(50) NOT NULL;
");
}
}
if(version_compare($previousVersion, '1.0RC1', '<')) {
// Move the auto_login setting from the Activation Field to the config
$field = extension_Members::getField('activation');
if($field instanceof Field) {
Symphony::Configuration()->set('activate-account-auto-login', $field->get('auto_login'));
$activation_table = Symphony::Database()->fetchRow(0, "SHOW TABLES LIKE 'tbl_fields_memberactivation';");
if(!empty($activation_table)) {
Symphony::Database()->query("
ALTER TABLE `tbl_fields_memberpassword` DROP `auto_login`;
");
}
}
// These are now loaded dynamically
Symphony::Configuration()->remove('timezone', 'members');
Symphony::Configuration()->remove('role', 'members');
Symphony::Configuration()->remove('activation', 'members');
Symphony::Configuration()->remove('identity', 'members');
Symphony::Configuration()->remove('email', 'members');
Symphony::Configuration()->remove('authentication', 'members');
Administration::instance()->saveConfig();
}
if(version_compare($previousVersion, '1.1 Beta 1', '<') || version_compare($previousVersion, '1.1.1RC1', '<')) {
$tables = array();
// For any Member: Username or Member: Email fields, add a handle column
// and adjust the indexes to reflect that. Uniqueness is on the handle,
// not the value.
$field = extension_Members::getField('identity');
if($field instanceof fieldMemberUsername) {
$identity_tables = Symphony::Database()->fetchCol("field_id", "SELECT `field_id` FROM `tbl_fields_memberusername`");
if(is_array($identity_tables) && !empty($identity_tables)) {
$tables = array_merge($tables, $identity_tables);
}
}
if(is_array($tables) && !empty($tables)) foreach($tables as $field) {
if(!extension_Members::tableContainsField('tbl_entries_data_' . $field, 'handle')) {
// Add handle field
Symphony::Database()->query(sprintf(
"ALTER TABLE `tbl_entries_data_%d` ADD `handle` VARCHAR(255) DEFAULT NULL",
$field
));
// Populate handle field
$rows = Symphony::Database()->fetch(sprintf(
"SELECT `id`, `value` FROM `tbl_entries_data_%d`",
$field
));
foreach($rows as $row) {
Symphony::Database()->query(sprintf("
UPDATE `tbl_entries_data_%d`
SET handle = '%s'
WHERE id = %d
", $field, Lang::createHandle($row['value']), $row['id']
));
}
}
// Try to drop the old `username` INDEX
try {
Symphony::Database()->query(sprintf(
'ALTER TABLE `tbl_entries_data_%d` DROP INDEX `username`, DROP INDEX `value`', $field
));
}
catch(Exception $ex) {}
// Create the new UNIQUE INDEX `username` on `handle`
try {
Symphony::Database()->query(sprintf(
'CREATE UNIQUE INDEX `username` ON `tbl_entries_data_%d` (`handle`)', $field
));
}
catch(Exception $ex) {}
// Create an index on the `value` column
try {
Symphony::Database()->query(sprintf(
'CREATE INDEX `value` ON `tbl_entries_data_%d` (`value`)', $field
));
}
catch(Exception $ex) {}
}
}
// So `handle` for Email fields is useless as [email protected] will become
// the same as [email protected]. Reverting previous change by dropping
// `handle` column from Member: Email tables and restoring the UNIQUE KEY
// index to the `value` column.
if(version_compare($previousVersion, '1.1 Beta 2', '<')) {
$tables = array();
$field = extension_Members::getField('email');
if($field instanceof fieldMemberEmail) {
$email_tables = Symphony::Database()->fetchCol("field_id", "SELECT `field_id` FROM `tbl_fields_memberemail`");
if(is_array($email_tables) && !empty($email_tables)) {
$tables = array_merge($tables, $email_tables);
}
}
if(is_array($tables) && !empty($tables)) foreach($tables as $field) {
if(extension_Members::tableContainsField('tbl_entries_data_' . $field, 'handle')) {
try {
// Drop handle field
Symphony::Database()->query(sprintf(
"ALTER TABLE `tbl_entries_data_%d` DROP `handle`",
$field
));
// Drop `value` index
Symphony::Database()->query(sprintf(
'ALTER TABLE `tbl_entries_data_%d` DROP INDEX `value`', $field
));
// Readd UNIQUE `value` index
Symphony::Database()->query(sprintf(
'CREATE UNIQUE INDEX `value` ON `tbl_entries_data_%d` (`value`)', $field
));
}
catch(Exception $ex) {
// Ignore, this may be because a user is updating directly from 1.0 and
// never had the INDEX's created during the 1.1* betas
}
}
}
}
}
/*-------------------------------------------------------------------------
Utilities:
-------------------------------------------------------------------------*/
public static function baseURL(){
return SYMPHONY_URL . '/extension/members/';
}
/**
* Returns an instance of the currently logged in Member, which is a `Entry` object.
* If there is no logged in Member, this function will return `null`
*
* @return Member
*/
public function getMemberDriver() {
return $this->Member;
}
/**
* Given a `$handle`, this function will return a value from the Members
* configuration. Typically this is an shortcut accessor to
* `Symphony::Configuration()->get($handle, 'members')`. If no `$handle`
* is given this function will return all the configuration values for
* the Members extension as an array.
*
* @param string $handle
* @return mixed
*/
public static function getSetting($handle = null) {
if(is_null($handle)) return Symphony::Configuration()->get('members');
$value = Symphony::Configuration()->get($handle, 'members');
return ((is_numeric($value) && $value == 0) || is_null($value) || empty($value)) ? null : $value;
}
/**
* Shortcut accessor for the active Members Section. This function
* caches the result of the `getSetting('section')`.
*
* @return integer
*/
public static function getMembersSection() {
if(is_null(extension_Members::$members_section)) {
extension_Members::$members_section = extension_Members::getSetting('section');
}
return extension_Members::$members_section;
}
/**
* Where `$name` is one of the following values, `role`, `timezone`,
* `email`, `activation`, `authentication` and `identity`, this function
* will return a Field instance. Typically this allows extensions to access
* the Fields that are currently being used in the active Members section.
* If no `$name` is given, an array of all Member fields will be returned.
*
* @param string $name
* @return Field
*/
public static function getField($name = null) {
if(is_null($name)) return extension_Members::$fields;
if(!isset(extension_Members::$fields[$name])) return null;
return extension_Members::$fields[$name];
}
/**
* Where `$name` is one of the following values, `role`, `timezone`,
* `email`, `activation`, `authentication` and `identity`, this function
* will return the Field's `element_name`. `element_name` is a handle
* of the Field's label, used most commonly by events in `$_POST` data.
* If no `$name` is given, an array of all Member field handles will
* be returned.
*
* @param string $name
* @return string
*/
public static function getFieldHandle($name = null) {
if(is_null($name)) return extension_Members::$handles;
if(!isset(extension_Members::$handles[$name])) return null;
return extension_Members::$handles[$name];
}
/**
* This function will adjust the locale for the currently logged in
* user if the active Member section has a Member: Timezone field.
*
* @param integer $member_id
* @return void
*/
public function updateSystemTimezoneOffset($member_id) {
$timezone = extension_Members::getField('timezone');
if(!$timezone instanceof fieldMemberTimezone) return;
$tz = $timezone->getMemberTimezone($member_id);
if(is_null($tz)) return;
try {
DateTimeObj::setDefaultTimezone($tz);
}
catch(Exception $ex) {
Symphony::$Log->pushToLog(__('Members Timezone') . ': ' . $ex->getMessage(), $code, true);
}
}
/**
* Given an array of grouped options ready for use in `Widget::Select`
* loop over all the options and compare the value to configuration value
* (as specified by `$handle`) and if it matches, set that option to true
*
* @param array $options
* @param string $handle
* @return array
*/
public static function setActiveTemplate(array $options, $handle) {
$templates = explode(',', extension_Members::getSetting($handle));
foreach($options as $index => $ext) {
foreach($ext['options'] as $key => $opt) {
if(in_array($opt[0], $templates)) {
$options[$index]['options'][$key][1] = true;
}
}
}
array_unshift($options, array(null,false,null));
return $options;
}
/**
* The Members extension provides a number of filters for users to add their
* events to do various functionality. This negates the need for custom events
*
* @uses AppendEventFilter
*/
public function appendFilter($context) {
$selected = !is_array($context['selected']) ? array() : $context['selected'];
// Add Member: Lock Role filter
$context['options'][] = array(
'member-lock-role',
in_array('member-lock-role', $selected),
__('Members: Lock Role')
);
if(!is_null(extension_Members::getFieldHandle('activation')) && !is_null(extension_Members::getFieldHandle('email'))) {
// Add Member: Lock Activation filter
$context['options'][] = array(
'member-lock-activation',
in_array('member-lock-activation', $selected),
__('Members: Lock Activation')
);
}
if(!is_null(extension_Members::getFieldHandle('authentication'))) {
// Add Member: Update Password filter
$context['options'][] = array(
'member-update-password',
in_array('member-update-password', $selected),
__('Members: Update Password')
);
}
}
public static function findCodeExpiry($table) {
$default = array('1 hour' => '1 hour', '24 hours' => '24 hours');
try {
$used = Symphony::Database()->fetchCol('code_expiry', sprintf("
SELECT DISTINCT(code_expiry) FROM `%s`
", $table));
if(is_array($used) && !empty($used)) {
$default = array_merge($default, array_combine($used, $used));
}
}
catch (DatabaseException $ex) {
// Table doesn't exist yet, it's ok we have defaults.
}
return $default;
}
public static function fetchEmailTemplates() {
$options = array();
// Email Template Filter
// @link http://symphony-cms.com/download/extensions/view/20743/
try {
$driver = Symphony::ExtensionManager()->getInstance('emailtemplatefilter');
if($driver instanceof Extension) {
$templates = $driver->getTemplates();
$g = array('label' => __('Email Template Filter'));
$group_options = array();
foreach($templates as $template) {
$group_options[] = array('etf-'.$template['id'], false, $template['name']);
}
$g['options'] = $group_options;
if(!empty($g['options'])) {
$options[] = $g;
}
}
}
catch(Exception $ex) {}
// Email Template Manager
// @link http://symphony-cms.com/download/extensions/view/64322/
try {
$handles = Symphony::ExtensionManager()->listInstalledHandles();
if(in_array('email_template_manager', $handles)){
if(file_exists(EXTENSIONS . '/email_template_manager/lib/class.emailtemplatemanager.php') && !class_exists("EmailTemplateManager")) {
include_once(EXTENSIONS . '/email_template_manager/lib/class.emailtemplatemanager.php');
}
if(class_exists("EmailTemplateManager")){
$templates = EmailTemplateManager::listAll();
$g = array('label' => __('Email Template Manager'));
$group_options = array();
foreach($templates as $template) {
$group_options[] = array('etm-'.$template->getHandle(), false, $template->getName());
}
$g['options'] = $group_options;
if(!empty($g['options'])) {
$options[] = $g;
}
}
}
}
catch(Exception $ex) {}
return $options;
}
public static function tableContainsField($table, $field){
$results = Symphony::Database()->fetch("DESC `{$table}` `{$field}`");
return (is_array($results) && !empty($results));
}
/*-------------------------------------------------------------------------
Preferences:
-------------------------------------------------------------------------*/
/**
* Allows a user to select which section they would like to use as their
* active members section. This allows developers to build multiple sections
* for migration during development.
*
* @uses AddCustomPreferenceFieldsets
* @todo Look at how this could be expanded so users can log into multiple
* sections. This is not in scope for 1.0
*/
public function appendPreferences($context) {
$fieldset = new XMLElement('fieldset');
$fieldset->setAttribute('class', 'settings');
$fieldset->appendChild(new XMLElement('legend', __('Members')));
$div = new XMLElement('div');
$label = new XMLElement('label', __('Active Members Section'));
// Get the Sections that contain a Member field.
$sectionManager = self::$entryManager->sectionManager;
$sections = $sectionManager->fetch();
$member_sections = array();
if(is_array($sections) && !empty($sections)) {
foreach($sections as $section) {
$schema = $section->fetchFieldsSchema();
foreach($schema as $field) {
if(!in_array($field['type'], extension_Members::$member_fields)) continue;
if(array_key_exists($section->get('id'), $member_sections)) continue;
$member_sections[$section->get('id')] = $section->get();
}
}
}
// Build the options
$options = array(
array(null, false, null)
);
foreach($member_sections as $section_id => $section) {
$options[] = array($section_id, ($section_id == extension_Members::getMembersSection()), $section['name']);
}
$label->appendChild(Widget::Select('settings[members][section]', $options));
$div->appendChild($label);
if(count($options) == 1) {
$div->appendChild(
new XMLElement('p', __('A Members section will at minimum contain either a Member: Email or a Member: Username field'), array('class' => 'help'))
);
}
$fieldset->appendChild($div);
$context['wrapper']->appendChild($fieldset);
}
/**
* Saves the Member Section to the configuration
*
* @uses savePreferences
*/
public function savePreferences(array &$context){
$settings = $context['settings'];
// Active Section
Symphony::Configuration()->set('section', $settings['members']['section'], 'members');
Administration::instance()->saveConfig();
}
/*-------------------------------------------------------------------------
Role Manager:
-------------------------------------------------------------------------*/
public function checkFrontendPagePermissions($context) {
$isLoggedIn = false;
$errors = array();
// Checks $_REQUEST to see if a Member Action has been requested,
// member-action['login'] and member-action['logout']/?member-action=logout
// are the only two supported at this stage.
if(is_array($_REQUEST['member-action'])){
list($action) = array_keys($_REQUEST['member-action']);
} else {
$action = $_REQUEST['member-action'];
}
// Check to see a Member is already logged in.
$isLoggedIn = $this->getMemberDriver()->isLoggedIn($errors);
// Logout
if(trim($action) == 'logout') {
/**
* Fired just before a member is logged out (and page redirection),
* this delegate provides the current Member ID
*
* @delegate MembersPreLogout
* @param string $context
* '/frontend/'
* @param integer $member_id
* The Member ID of the member who is about to logged out
*/
Symphony::ExtensionManager()->notifyMembers('MembersPreLogout', '/frontend/', array(
'member_id' => $this->getMemberDriver()->getMemberID()
));
$this->getMemberDriver()->logout();
// If a redirect is provided, redirect to that, otherwise return the user
// to the index of the site. Issue #51 & #121
if(isset($_REQUEST['redirect'])) redirect($_REQUEST['redirect']);
redirect(URL);
}
// Login
else if(trim($action) == 'login' && !is_null($_POST['fields'])) {
// If a Member is already logged in and another Login attempt is requested
// log the Member out first before trying to login with new details.
if($isLoggedIn) {
$this->getMemberDriver()->logout();
}
if($this->getMemberDriver()->login($_POST['fields'])) {
/**
* Fired just after a Member has successfully logged in, this delegate
* provides the current Member ID. This delegate is fired just before
* the page redirection (if it is provided)
*
* @delegate MembersPostLogin
* @param string $context
* '/frontend/'
* @param integer $member_id
* The Member ID of the member who just logged in.
* @param Entry $member
* The Entry object of the logged in Member.
*/
Symphony::ExtensionManager()->notifyMembers('MembersPostLogin', '/frontend/', array(
'member_id' => $this->getMemberDriver()->getMemberID(),
'member' => $this->getMemberDriver()->getMember()
));
if(isset($_POST['redirect'])) redirect($_POST['redirect']);
}
else {
self::$_failed_login_attempt = true;
}
}
$this->Member->initialiseMemberObject();
if($isLoggedIn && $this->getMemberDriver()->getMember() instanceOf Entry) {
$this->updateSystemTimezoneOffset($this->getMemberDriver()->getMemberID());
if(!is_null(extension_Members::getFieldHandle('role'))) {
$role_data = $this->getMemberDriver()->getMember()->getData(extension_Members::getField('role')->get('id'));
}
}
// If there is no role field, or a Developer is logged in, return, as Developers
// should be able to access every page.
if(
is_null(extension_Members::getFieldHandle('role'))
|| (Frontend::instance()->Author instanceof Author && Frontend::instance()->Author->isDeveloper())
) return;
$role_id = ($isLoggedIn) ? $role_data['role_id'] : Role::PUBLIC_ROLE;
$role = RoleManager::fetch($role_id);
if($role instanceof Role && !$role->canAccessPage((int)$context['page_data']['id'])) {
// User has no access to this page, so look for a custom 403 page
if($row = Symphony::Database()->fetchRow(0,"
SELECT `p`.*
FROM `tbl_pages` as `p`
LEFT JOIN `tbl_pages_types` AS `pt` ON(`p`.id = `pt`.page_id)
WHERE `pt`.type = '403'
")) {
$row['type'] = FrontendPage::fetchPageTypes($row['id']);
$row['filelocation'] = FrontendPage::resolvePageFileLocation($row['path'], $row['handle']);
$context['page_data'] = $row;
return;
}
else {
// No custom 403, just throw default 403
GenericExceptionHandler::$enabled = true;
throw new SymphonyErrorPage(
__('The page you have requested has restricted access permissions.'),
__('Forbidden'),
'error',
array('header' => 'HTTP/1.0 403 Forbidden')
);
}
}
}
/*-------------------------------------------------------------------------
Events:
-------------------------------------------------------------------------*/
/**
* Adds Javascript to the custom Members events when they are viewed in the
* backend to enable developers to set the appropriate Email Templates for
* each event
*
* @uses AdminPagePreGenerate
*/
public function appendAssets(&$context) {
if(class_exists('Administration')
&& Administration::instance() instanceof Administration
&& Administration::instance()->Page instanceof HTMLPage
) {
$callback = Administration::instance()->getPageCallback();
// Event Info
if(
$context['oPage'] instanceof contentBlueprintsEvents &&
$callback['context'][0] == "info" &&
in_array($callback['context'][1], extension_Members::$member_events)
) {
Administration::instance()->Page->addScriptToHead(URL . '/extensions/members/assets/members.events.js', 10001, false);
}
// Temporary fix
else if($context['oPage'] instanceof contentPublish) {
Administration::instance()->Page->addStylesheetToHead(URL . '/extensions/members/assets/members.publish.css', 'screen', 45);
}
}
}
/**
* This function will ensure that the user who has submitted the form (and
* hence is requesting that an event be triggered) is actually allowed to
* do this request.
* There are 2 action types, creation and editing. Creation is a simple yes/no
* affair, whereas editing has three levels of permission, None, Own Entries
* or All Entries:
* - None: This user can't do process this event
* - Own Entries: If the entry the user is trying to update is their own
* determined by if the `entry_id` or, in the case of a SBL or
* similar field, the `entry_id` of the linked entry matches the logged in
* user's id, process the event.
* - All Entries: The user can update any entry in Symphony.
* If there are no Roles in this system, or the event is set to ignore permissions
* (by including a function, `ignoreRolePermissions` that returns `true`, it will
* immediately proceed to processing any of the Filters attached to the event
* before returning.
*
* @uses EventPreSaveFilter
*/
public function checkEventPermissions(array &$context){
// If this system has no Roles, or the event is set to ignore role permissions
// continue straight to processing the Filters
if(
is_null(extension_Members::getFieldHandle('role')) ||
(method_exists($context['event'], 'ignoreRolePermissions') && $context['event']->ignoreRolePermissions() == true)
) {
return $this->__processEventFilters($context);