PluginProbe
AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress / trunk
AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress vtrunk
11.0.5 11.0.4 11.0.3 11.0.2 11.0.1 11.0.0 10.11.1 10.11.0 10.10.2 10.10.1 10.10.0 10.9.1 trunk 10.0.0 10.0.1 10.1.0 10.1.1 10.1.2 10.1.3 10.1.4 10.2.0 10.2.1 10.2.2 10.3.0 10.4.0 All 60 releases
acymailing / back / dynamics / createuser / plugin.php

plugin.php in AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress trunk, at back/dynamics/createuser/plugin.php

333 lines 12.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 use AcyMailing\Core\AcymPlugin;
4 use AcyMailing\Classes\UserClass;
5 use Joomla\Registry\Registry;
6 use Joomla\CMS\Access\Access;
7 use Joomla\CMS\Plugin\PluginHelper;
8 use Joomla\CMS\User\User;
9 use Joomla\CMS\User\UserHelper;
10 use Joomla\CMS\Factory;
11 use Joomla\CMS\Component\ComponentHelper;
12 use Joomla\CMS\Application\ApplicationHelper;
13
14 class plgAcymcreateuser extends AcymPlugin
15 {
16 public function __construct()
17 {
18 parent::__construct();
19 $this->cms = 'all';
20 }
21
22 protected function initSettings(): void
23 {
24 if ('joomla' === ACYM_CMS) {
25 $joomlaUsersparams = ComponentHelper::getParams('com_users');
26 $defaultUsergroup = $joomlaUsersparams->get('new_usertype');
27 } else {
28 $defaultUsergroup = get_option('default_role');
29 }
30
31 $this->settings = [
32 'enableCreate' => [
33 'type' => 'switch',
34 'label' => 'ACYM_ALLOW_CMS_USER_CREATION',
35 'value' => 0,
36 ],
37 'onlyFront' => [
38 'type' => 'select',
39 'label' => 'ACYM_CREATE_FROM_SUB_ON',
40 'value' => 1,
41 'data' => [
42 'front' => acym_translation('ACYM_FRONT'),
43 'both' => acym_translation('ACYM_FRONT_BACK'),
44 ],
45 ],
46 'onModif' => [
47 'type' => 'switch',
48 'label' => 'ACYM_CREATE_ON_USER_MODIFICATION',
49 'value' => 0,
50 ],
51 'group' => [
52 'type' => 'select',
53 'label' => 'ACYM_USER_GROUP',
54 'value' => $defaultUsergroup,
55 'data' => acym_getGroups(),
56 ],
57 ];
58 }
59
60 public function onAcymAfterUserCreate(&$user)
61 {
62 $this->createCmsUser($user);
63 }
64
65 public function onAcymAfterUserModify(&$user, &$oldUser)
66 {
67 if ($this->getParam('onModif', '0') === '0') return;
68
69 $this->createCmsUser($user);
70 }
71
72 public function createCmsUser($user)
73 {
74 $enableCreate = $this->getParam('enableCreate', '0');
75 if (empty($user->email) || !empty($user->cms_id) || empty($enableCreate)) return;
76
77 // Should we only create from front subscriber creation
78 if ($this->getParam('onlyFront', 'front') === 'front' && acym_isAdmin()) return;
79
80 if ('wordpress' === ACYM_CMS) {
81 $this->createWordpressUser($user);
82 } else {
83 $this->createJoomlaUser($user);
84 }
85 }
86
87 protected function createJoomlaUser($user)
88 {
89 $joomlaUsersparams = ComponentHelper::getParams('com_users');
90 $joomlaConfig = Factory::getConfig();
91
92 $useractivation = $joomlaUsersparams->get('useractivation');
93 $allowUserRegistration = $joomlaUsersparams->get('allowUserRegistration');
94 if ($allowUserRegistration == 0) return;
95
96 acym_loadLanguageFile('com_users', JPATH_SITE);
97
98 // Generate the password
99 $minimum_integers = $joomlaUsersparams->get('minimum_integers');
100 $minimum_symbols = $joomlaUsersparams->get('minimum_symbols');
101 $minimum_uppercase = $joomlaUsersparams->get('minimum_uppercase');
102 $length = 8;
103 if ($joomlaUsersparams->get('minimum_length') > 8) $length = $joomlaUsersparams->get('minimum_length');
104 $tryCount = 0;
105 do {
106 $password = UserHelper::genrandompassword($length);
107 $tryCount++;
108 //Could happen if the admin selected 90 as min integers and min length = 9, in this case we will never generate a satisfying password
109 if ($tryCount > 50) break;
110 } while ($this->getConditionPassword($password, $minimum_integers, $minimum_symbols, $minimum_uppercase));
111
112 $defaultUsergroup = $joomlaUsersparams->get('new_usertype');
113 $configUserGroup = $this->getParam('group', $defaultUsergroup);
114
115 if (empty($user->name)) {
116 $user->name = ucwords(trim(str_replace(['.', '_', ')', ',', '(', '-', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0], ' ', substr($user->email, 0, strpos($user->email, '@')))));
117 }
118 $userData = [
119 'name' => $user->name,
120 'username' => $user->email,
121 'password' => $password,
122 'password2' => $password,
123 'email' => $user->email,
124 'block' => 0,
125 'groups' => [$configUserGroup],
126 ];
127
128 $joomlaUser = new User();
129
130 // Check if the user needs to activate his account.
131 if (in_array($useractivation, [1, 2])) {
132 $userData['activation'] = ApplicationHelper::getHash(UserHelper::genrandompassword());
133 $userData['block'] = 1;
134 }
135
136 // Write to database
137 if (!$joomlaUser->bind($userData)) return false;
138 // Store the data.
139 if (!$this->save($joomlaUser)) return false;
140
141 $user->cms_id = $joomlaUser->id;
142 $userClass = new UserClass();
143 // We don't want to send the confirmation because it already has been set in the AcyMailing user creation
144 $userClass->sendConf = false;
145 $userClass->save($user);
146
147 // Compile the notification mail values.
148 $data = $joomlaUser->getProperties();
149 $data['fromname'] = $joomlaConfig->get('fromname');
150 $data['mailfrom'] = $joomlaConfig->get('mailfrom');
151 $data['sitename'] = $joomlaConfig->get('sitename');
152 $data['siteurl'] = str_replace('/administrator', '', acym_baseURI());
153
154 // Handle account activation/confirmation emails.
155 $emailSubject = acym_translationSprintf('COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename']);
156 if (in_array($useractivation, [1, 2])) {
157 $base = acym_currentURL();
158 $activationLink = 'index.php?option=com_users&task=registration.activate&token=';
159 $data['activate'] = $data['siteurl'].$activationLink.$data['activation'];
160
161 if ($useractivation == 2) {
162 $emailBody = acym_translationSprintf(
163 'COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY',
164 $data['name'],
165 $data['sitename'],
166 $data['activate'],
167 $data['siteurl'],
168 $data['username'],
169 $data['password_clear']
170 );
171 } else {
172 $activationMessage = 'COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY';
173 $emailBody = acym_translationSprintf(
174 $activationMessage,
175 $data['name'],
176 $data['sitename'],
177 $data['activate'],
178 $data['siteurl'],
179 $data['username'],
180 $data['password_clear']
181 );
182 }
183 } else {
184 $emailBody = acym_translationSprintf(
185 'COM_USERS_EMAIL_REGISTERED_BODY',
186 $data['name'],
187 $data['sitename'],
188 $data['siteurl'],
189 $data['username'],
190 $data['password_clear']
191 );
192 }
193
194 // Replace variables for Joomla 4
195 if (ACYM_J40) {
196 $keys = [];
197 $replaceData = [];
198 foreach ($data as $key => $oneKey) {
199 if (is_array($oneKey)) continue;
200
201 $keys[] = '{'.strtoupper($key).'}';
202 $replaceData[] = $oneKey;
203 }
204 $emailSubject = str_replace($keys, $replaceData, $emailSubject);
205 $emailBody = str_replace($keys, $replaceData, $emailBody);
206 }
207
208 $mailer = Factory::getMailer();
209 /* Set a sender - The sender of an email is set with setSender. The function takes an array with an email address and a name as an argument.
210 We fetch the site's email address and name from the global configuration.
211 This info is set in Global Configuration -> Server -> Mail Settings. */
212 $sender = [$joomlaConfig->get('mailfrom'), $joomlaConfig->get('fromname')];
213 $mailer->setSender($sender);
214 /* Recipient - You set the recipient of an email with the function addRecipient.
215 To set the email address to the currently logged in user, we fetch it from the user object. */
216 $mailer->addRecipient($user->email);
217 /* Set the subject and the body. The easy way to create an email body is as a string with plain text.
218 You can also attach a file with addAttachment. It takes a single file name or an array of file names as argument.*/
219 $mailer->setSubject($emailSubject);
220 $mailer->setBody($emailBody);
221 // Send the mail - It is sent with the function Send. It returns true on success or a JError object.
222 $send = $mailer->Send();
223 if ($send !== true) return false;
224 }
225
226 public function save($joomlaUser)
227 {
228 // Create the user table object
229 $table = $joomlaUser->getTable();
230 $joomlaUser->params = '{}';
231 $table->bind($joomlaUser->getProperties());
232
233 try {
234 if (!$table->check()) {
235 $joomlaUser->setError($table->getError());
236
237 return false;
238 }
239
240 $isNew = empty($joomlaUser->id);
241
242 $my = Factory::getUser();
243
244 $oldUser = new User($joomlaUser->id);
245
246 $iAmRehashingSuperadmin = false;
247 if (($my->id == 0 && !$isNew) && $joomlaUser->id == $oldUser->id && $oldUser->authorise('core.admin') && $oldUser->password != $joomlaUser->password) {
248 $iAmRehashingSuperadmin = true;
249 }
250
251 // We are only worried about edits to this account if I am not a Super Admin.
252 $iAmSuperAdmin = $my->authorise('core.admin');
253 if ($iAmSuperAdmin != true && $iAmRehashingSuperadmin != true) {
254 // I am not a Super Admin, and this one is, so fail.
255 if (!$isNew && Access::check($joomlaUser->id, 'core.admin')) {
256 throw new \RuntimeException('User not Super Administrator');
257 }
258
259 if ($joomlaUser->groups != null) {
260 // I am not a Super Admin and I'm trying to make one.
261 foreach ($joomlaUser->groups as $groupId) {
262 if (Access::checkGroup($groupId, 'core.admin')) {
263 throw new \RuntimeException('User not Super Administrator');
264 }
265 }
266 }
267 }
268
269 // Fire the onUserBeforeSave event.
270 PluginHelper::importPlugin('user');
271 if (ACYM_J40) {
272 $result = Factory::getApplication()->triggerEvent('onUserBeforeSave', [$oldUser->getProperties(), $isNew, $joomlaUser->getProperties()]);
273 } else {
274 $dispatcher = \JEventDispatcher::getInstance();
275 $result = $dispatcher->trigger('onUserBeforeSave', [$oldUser->getProperties(), $isNew, $joomlaUser->getProperties()]);
276 }
277 if (in_array(false, $result, true)) return false;
278
279 $result = $table->store();
280
281 if (empty($joomlaUser->id)) {
282 $joomlaUser->id = $table->get('id');
283 }
284
285 if ($my->id == $table->id) {
286 $registry = new Registry($table->params);
287 $my->setParameters($registry);
288 }
289 } catch (\Exception $e) {
290 $joomlaUser->setError($e->getMessage());
291
292 return false;
293 }
294
295 return $result;
296 }
297
298 protected function createWordpressUser($user)
299 {
300 if (!get_option('users_can_register')) return;
301
302 if (false !== username_exists($user->email)) return false;
303
304 $defaultUsergroup = get_option('default_role');
305 $configUserGroup = $this->getParam('group', $defaultUsergroup);
306
307 $pwdTemp = wp_generate_password(12, true);
308 $result = wp_create_user($user->email, $pwdTemp, $user->email);
309
310 if (is_wp_error($result)) {
311 return false;
312 } else {
313 $user->cms_id = $result;
314 $userClass = new UserClass();
315 // We don't want to send the confirmation because it already has been set in the AcyMailing user creation
316 $userClass->sendConf = false;
317 $userClass->save($user);
318 $wpUser = new WP_User($result);
319 $wpUser->set_role($configUserGroup);
320 wp_new_user_notification($result, null, 'user');
321 }
322 }
323
324 protected function getConditionPassword($password, $minimum_integers, $minimum_symbols, $minimum_uppercase)
325 {
326 $notEnoughInt = !empty($minimum_integers) && preg_match_all("/[0-9]/", $password, $out) < $minimum_integers;
327 $notEnoughSymbols = !empty($minimum_symbols) && preg_match_all("/[a-z]/", $password, $out) < $minimum_symbols;
328 $notEnoughUpperCase = !empty($minimum_uppercase) && preg_match_all("/[A-Z]/", $password, $out) < $minimum_uppercase;
329
330 return $notEnoughInt || $notEnoughSymbols || $notEnoughUpperCase;
331 }
332 }
333