uc_roles.module 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. <?php
  2. /**
  3. * @file
  4. * Grants roles upon accepted payment of products.
  5. *
  6. * The uc_roles module will grant specified roles upon purchase of specified
  7. * products. Granted roles can be set to have a expiration date. Users can also
  8. * be notified of the roles they are granted and when the roles will
  9. * expire/need to be renewed/etc.
  10. */
  11. /**
  12. * Implements hook_help().
  13. */
  14. function uc_roles_help($path, $arg) {
  15. if ($path == 'node/%/edit/features/%/%' && $arg[4] == 'role') {
  16. return '<p>' . t('Add roles through this page and then use the <a href="!url">Rules interface</a> to limit which orders they are applied to. Most important is the order status on which role granting will be triggered.', array('!url' => url('admin/config/workflow/rules/reaction'))) . '</p>';
  17. }
  18. switch ($path) {
  19. case 'admin/people/expiration':
  20. return '<p>' . t('Ubercart grants certain roles to customers when they purchase products with a role assignment feature. These can be permanent or temporary roles. Here you can view and edit when temporary roles are set to expire.') . '</p>';
  21. }
  22. }
  23. /**
  24. * Implements hook_cron().
  25. */
  26. function uc_roles_cron() {
  27. $reminder_granularity = variable_get('uc_roles_reminder_granularity', 'never');
  28. $reminder_qty = variable_get('uc_roles_reminder_length', NULL);
  29. $query = db_select('uc_roles_expirations', 'e')
  30. ->fields('e');
  31. $condition = db_or()
  32. ->condition('e.expiration', REQUEST_TIME, '<=');
  33. if ($reminder_granularity != 'never') {
  34. $condition->condition(db_and()
  35. ->isNull('e.notified')
  36. ->condition('e.expiration', _uc_roles_get_expiration($reminder_qty, $reminder_granularity, REQUEST_TIME), '<=')
  37. );
  38. }
  39. $query->condition($condition);
  40. $result = $query->execute();
  41. foreach ($result as $expiration) {
  42. $account = user_load($expiration->uid);
  43. // Cleanup if user or role was deleted already.
  44. if (!$account || !in_array($expiration->rid, array_keys($account->roles))) {
  45. uc_roles_delete($expiration, $expiration->rid, TRUE);
  46. }
  47. // Role expired.
  48. elseif ($expiration->expiration <= REQUEST_TIME) {
  49. rules_invoke_event('uc_roles_notify_revoke', $account, $expiration);
  50. uc_roles_revoke($account, $expiration->rid);
  51. }
  52. // Remind the user about an upcoming expiration.
  53. elseif ($reminder_granularity != 'never') {
  54. rules_invoke_event('uc_roles_notify_reminder', $account, $expiration);
  55. db_update('uc_roles_expirations')
  56. ->fields(array('notified' => 1))
  57. ->condition('uid', $account->uid)
  58. ->condition('rid', $expiration->rid)
  59. ->execute();
  60. }
  61. }
  62. }
  63. /**
  64. * Implements hook_menu().
  65. */
  66. function uc_roles_menu() {
  67. $items = array();
  68. $items['admin/people/expiration'] = array(
  69. 'title' => 'Role expiration',
  70. 'description' => 'Edit and view role expirations set by Ubercart',
  71. 'page callback' => 'drupal_get_form',
  72. 'page arguments' => array('uc_roles_expiration'),
  73. 'access arguments' => array('administer users'),
  74. 'type' => MENU_LOCAL_TASK,
  75. 'file' => 'uc_roles.admin.inc',
  76. );
  77. $items['admin/people/expiration/delete/%user/%'] = array(
  78. 'title' => 'Delete role expiration',
  79. 'description' => 'Delete a specified role expiration',
  80. 'page callback' => 'drupal_get_form',
  81. 'page arguments' => array('uc_roles_deletion_form', 4, 5),
  82. 'access arguments' => array('administer users'),
  83. 'type' => MENU_CALLBACK,
  84. 'file' => 'uc_roles.admin.inc',
  85. );
  86. return $items;
  87. }
  88. /**
  89. * Implements hook_permission().
  90. */
  91. function uc_roles_permission() {
  92. return array(
  93. 'view all role expirations' => array(
  94. 'title' => t('View all role expirations'),
  95. )
  96. );
  97. }
  98. /**
  99. * Implements hook_theme().
  100. */
  101. function uc_roles_theme() {
  102. return array(
  103. 'uc_roles_expiration' => array(
  104. 'render element' => 'form',
  105. 'file' => 'uc_roles.admin.inc',
  106. ),
  107. 'uc_roles_user_expiration' => array(
  108. 'render element' => 'form',
  109. 'file' => 'uc_roles.theme.inc',
  110. ),
  111. 'uc_roles_user_new' => array(
  112. 'render element' => 'form',
  113. 'file' => 'uc_roles.theme.inc',
  114. ),
  115. );
  116. }
  117. /**
  118. * Implements hook_form_user_profile_form_alter().
  119. */
  120. function uc_roles_form_user_profile_form_alter(&$form, &$form_state) {
  121. $account = $form_state['build_info']['args'][0];
  122. if (isset($form_state['build_info']['args'][1])) {
  123. $category = $form_state['build_info']['args'][1];
  124. }
  125. else {
  126. // user_profile_form() has a default value for $category.
  127. $category = 'account';
  128. }
  129. if (!user_access('administer users') || $category != 'account') {
  130. return;
  131. }
  132. $role_choices = _uc_roles_get_choices(array_keys($account->roles));
  133. $polarity_widget = array(
  134. '#type' => 'select',
  135. '#options' => array(
  136. 'add' => '+',
  137. 'remove' => '-',
  138. ),
  139. );
  140. $quantity_widget = array(
  141. '#type' => 'textfield',
  142. '#size' => 4,
  143. '#maxlength' => 4
  144. );
  145. $granularity_widget = array(
  146. '#type' => 'select',
  147. '#options' => array(
  148. 'day' => t('day(s)'),
  149. 'week' => t('week(s)'),
  150. 'month' => t('month(s)'),
  151. 'year' => t('year(s)'),
  152. ),
  153. );
  154. $form['uc_roles'] = array(
  155. '#type' => 'fieldset',
  156. '#title' => t('Ubercart roles'),
  157. '#collapsible' => TRUE,
  158. '#collapsed' => TRUE,
  159. '#weight' => 10,
  160. '#theme' => 'uc_roles_user_new',
  161. );
  162. $form['uc_roles']['expirations'] = array(
  163. '#type' => 'fieldset',
  164. '#title' => t('Pending expirations'),
  165. '#collapsible' => FALSE,
  166. '#weight' => 0,
  167. '#theme' => 'uc_roles_user_expiration',
  168. );
  169. $form['uc_roles']['expirations']['table']['#tree'] = TRUE;
  170. // Create the expirations table.
  171. $expirations = db_query("SELECT * FROM {uc_roles_expirations} WHERE uid = :uid", array(':uid' => $account->uid));
  172. foreach ($expirations as $expiration) {
  173. $form['uc_roles']['expirations']['table'][$expiration->rid] = array(
  174. 'name' => array(
  175. '#type' => 'value',
  176. '#value' => _uc_roles_get_name($expiration->rid),
  177. ),
  178. 'remove' => array(
  179. '#type' => 'checkbox',
  180. ),
  181. 'expiration' => array(
  182. '#type' => 'value',
  183. '#value' => $expiration->expiration,
  184. ),
  185. 'polarity' => $polarity_widget,
  186. 'qty' => $quantity_widget,
  187. 'granularity' => $granularity_widget,
  188. );
  189. }
  190. // Option to allow temporary roles.
  191. if (!empty($role_choices)) {
  192. $form['uc_roles']['new_role'] = array(
  193. '#type' => 'checkbox',
  194. '#title' => t('Add role'),
  195. );
  196. $form['uc_roles']['new_role_add'] = array(
  197. '#type' => 'select',
  198. '#default_value' => variable_get('uc_roles_default_role', NULL),
  199. '#options' => $role_choices,
  200. );
  201. $form['uc_roles']['new_role_add_for'] = array(
  202. '#markup' => ' ' . t('for') . ' ',
  203. );
  204. $form['uc_roles']['new_role_add_qty'] = $quantity_widget;
  205. $form['uc_roles']['new_role_add_granularity'] = $granularity_widget;
  206. if (($default_granularity = variable_get('uc_roles_default_granularity', 'never')) != 'never') {
  207. $form['uc_roles']['new_role_add_qty'] = $form['uc_roles']['new_role_add_qty'] + array('#default_value' => variable_get('uc_roles_default_length', NULL));
  208. $form['uc_roles']['new_role_add_granularity'] = $form['uc_roles']['new_role_add_granularity'] + array('#default_value' => $default_granularity);
  209. }
  210. }
  211. $form['#validate'][] = 'uc_roles_user_validate';
  212. return $form;
  213. }
  214. /**
  215. * User profile form validate handler.
  216. *
  217. * @see uc_roles_form_user_profile_form_alter()
  218. */
  219. function uc_roles_user_validate($form, &$form_state) {
  220. $edit = $form_state['values'];
  221. $account = $form_state['build_info']['args'][0];
  222. if (isset($form_state['build_info']['args'][1])) {
  223. $category = $form_state['build_info']['args'][1];
  224. }
  225. else {
  226. // user_profile_form() has a default value for $category.
  227. $category = 'account';
  228. }
  229. // Validate the amount of time for the expiration.
  230. if (!empty($edit['new_role']) && $category == 'account') {
  231. if (intval($edit['new_role_add_qty']) < 1) {
  232. form_set_error('new_role_add_qty', t('The expiration length must be a positive integer'));
  233. }
  234. }
  235. // Validate adjusted expirations.
  236. if (isset($edit['table'])) {
  237. foreach ((array)$edit['table'] as $rid => $value) {
  238. // We don't validate if nothing was actually selected, the role, or the
  239. // expiration is removed.
  240. if ($value['qty'] == 0 || $value['remove'] == 1 || !$edit['roles'][$rid]) {
  241. continue;
  242. }
  243. $qty = $value['qty'];
  244. $qty *= $value['polarity'] == 'add' ? 1 : -1;
  245. $new_expiration = _uc_roles_get_expiration($qty, $value['granularity'], $value['expiration']);
  246. if (REQUEST_TIME > $new_expiration) {
  247. form_set_error('qty', t("The new expiration date, %date, has already occurred.", array('%date' => format_date($new_expiration, 'short'))));
  248. }
  249. }
  250. }
  251. }
  252. /**
  253. * Implements hook_user_cancel().
  254. */
  255. function uc_roles_user_cancel($edit, $account, $method) {
  256. uc_roles_delete($account);
  257. }
  258. /**
  259. * Implements hook_user_presave().
  260. */
  261. function uc_roles_user_presave(&$edit, $account, $category) {
  262. if (!user_access('administer users') || $category != 'account') {
  263. return;
  264. }
  265. // Grant a new role if a new temporary role is added.
  266. if (isset($edit['new_role']) && $edit['new_role'] && $category == 'account') {
  267. // Save our role info, but don't save the user; user.module will do that.
  268. uc_roles_grant($account, $edit['new_role_add'], _uc_roles_get_expiration($edit['new_role_add_qty'], $edit['new_role_add_granularity']), FALSE);
  269. // Push in values so user.module will save in the roles.
  270. $edit['roles'][$edit['new_role_add']] = _uc_roles_get_name($edit['new_role_add']);
  271. // Reset the new role form.
  272. $edit['new_role'] = $edit['new_role_add'] = $edit['new_role_add_qty'] = $edit['new_role_add_granularity'] = NULL;
  273. }
  274. // Check if any temporary role actions were taken.
  275. if (isset($edit['table'])) {
  276. foreach ((array)$edit['table'] as $rid => $value) {
  277. // Remove this expiration.
  278. if ($value['remove']) {
  279. uc_roles_delete($account, $rid);
  280. }
  281. // Adjust it.
  282. else {
  283. if ($value['qty'] && $edit['roles'][$rid]) {
  284. $qty = $value['qty'];
  285. $qty *= $value['polarity'] == 'add' ? 1 : -1;
  286. uc_roles_renew($account, $rid, _uc_roles_get_expiration($qty, $value['granularity'], $value['expiration']));
  287. }
  288. }
  289. }
  290. }
  291. // If a user's role is removed using Drupal, then so is any expiration data.
  292. if (isset($edit['roles']) && is_array($edit['roles']) && isset($account->roles)) {
  293. foreach ($account->roles as $rid => $role) {
  294. if (!in_array($rid, array_keys($edit['roles'])) && $rid != DRUPAL_AUTHENTICATED_RID) {
  295. uc_roles_delete($account, $rid);
  296. }
  297. }
  298. }
  299. }
  300. /**
  301. * Implements hook_user_view().
  302. *
  303. * Displays role expirations on the user account screen.
  304. */
  305. function uc_roles_user_view($account, $view_mode) {
  306. global $user;
  307. // Kick out anonymous.
  308. if (!$user->uid) {
  309. return;
  310. }
  311. // Only show if this user can access all role expirations, or if it's the same
  312. // user and the expirations are showing on the user pages.
  313. $show_expiration = variable_get('uc_roles_default_show_expiration', TRUE);
  314. if (!user_access('view all role expirations') && ($user->uid != $account->uid || !$show_expiration)) {
  315. return;
  316. }
  317. $items = array();
  318. $form = array();
  319. $expirations = db_query("SELECT * FROM {uc_roles_expirations} WHERE uid = :uid", array(':uid' => $account->uid));
  320. foreach ($expirations as $expiration) {
  321. $form[$expiration->rid] = array(
  322. '#type' => 'user_profile_item',
  323. '#title' => check_plain(_uc_roles_get_name($expiration->rid)),
  324. '#markup' => t('This role will expire on !date', array('!date' => format_date($expiration->expiration, 'short'))),
  325. );
  326. }
  327. // Don't display anything if there aren't any expirations.
  328. if (!count($form)) {
  329. return;
  330. }
  331. $item = array(
  332. '#type' => 'user_profile_category',
  333. '#weight' => '-1',
  334. '#title' => t('Expiring roles'),
  335. );
  336. $account->content['uc_roles'] = $item + $form;
  337. }
  338. /**
  339. * Implements hook_uc_order_product_can_ship().
  340. */
  341. function uc_roles_uc_order_product_can_ship($item) {
  342. $roles = db_query("SELECT * FROM {uc_roles_products} WHERE nid = :nid", array(':nid' => $item->nid));
  343. foreach ($roles as $role) {
  344. // If the model is empty, keep looking. (Everyone needs a role model...)
  345. if (empty($role->model)) {
  346. continue;
  347. }
  348. // If there's an adjusted SKU, use it... otherwise use the node SKU.
  349. $sku = (empty($item->data['model'])) ? $item->model : $item->data['model'];
  350. // Keep looking if it doesn't match.
  351. if ($sku != $role->model) {
  352. continue;
  353. }
  354. return $role->shippable;
  355. }
  356. }
  357. /**
  358. * Implements hook_uc_product_feature().
  359. */
  360. function uc_roles_uc_product_feature() {
  361. $features[] = array(
  362. 'id' => 'role',
  363. 'title' => t('Role assignment'),
  364. 'callback' => 'uc_roles_feature_form',
  365. 'delete' => 'uc_roles_feature_delete',
  366. 'settings' => 'uc_roles_feature_settings',
  367. );
  368. return $features;
  369. }
  370. /**
  371. * Implements hook_uc_store_status().
  372. */
  373. function uc_roles_uc_store_status() {
  374. $message = array();
  375. $role_choices = _uc_roles_get_choices();
  376. if (empty($role_choices)) {
  377. $message[] = array(
  378. 'status' => 'warning',
  379. 'title' => t('Roles'),
  380. 'desc' => t('There are no product role(s) that can be assigned upon product purchase. Set product roles in the <a href="!url">product settings</a> under the role assignment settings tab.', array('!url' => url('admin/store/settings/products'))),
  381. );
  382. }
  383. else {
  384. $message[] = array(
  385. 'status' => 'ok',
  386. 'title' => t('Roles'),
  387. 'desc' => t('The role(s) %roles are set to be used with the Role Assignment product feature.', array('%roles' => implode(', ', $role_choices))),
  388. );
  389. }
  390. return $message;
  391. }
  392. /**
  393. * Implements hook_uc_message().
  394. */
  395. function uc_roles_uc_message() {
  396. $messages['uc_roles_grant_subject'] = t('[store:name]: [expiration:name] role granted');
  397. $messages['uc_roles_grant_message'] = t("[order:first-name] [order:last-name], \n\nThanks to your order, [order:link], at [store:name] you now have a new role, [expiration:name].\n\nThanks again, \n\n[store:name]\n[site:slogan]");
  398. $messages['uc_roles_revoke_subject'] = t('[store:name]: [expiration:name] role expired');
  399. $messages['uc_roles_revoke_message'] = t("The role, [expiration:name], you acquired by purchasing a product at our store has expired. Any special access or privileges that came with it are now gone. You can purchase it again by going to [store:link]\n\nThanks again, \n\n[store:name]\n[site:slogan]");
  400. $messages['uc_roles_renew_subject'] = t('[store:name]: [expiration:name] role renewed');
  401. $messages['uc_roles_renew_message'] = t("[order:first-name] [order:last-name], \n\nThanks to your order, [order:link], at [store:name] you have renewed the role, [expiration:name]. It is now set to expire on [expiration:expiration:short].\n\nThanks again, \n\n[store:name]\n[site:slogan]");
  402. $messages['uc_roles_reminder_subject'] = t('[store:name]: [expiration:name] role expiration notice');
  403. $messages['uc_roles_reminder_message'] = t("This message is to remind you that the role, [expiration:name], you acquired by making a purchase at our store will expire at [expiration:expiration:short]. You may visit [store:link] to renew this role before it expires.\n\nThanks again, \n\n[store:name]\n[site:slogan]");
  404. return $messages;
  405. }
  406. /**
  407. * Form builder for hook_uc_product_feature().
  408. *
  409. * @see uc_roles_feature_form_validate()
  410. * @see uc_roles_feature_form_submit()
  411. * @ingroup forms
  412. */
  413. function uc_roles_feature_form($form, &$form_state, $node, $feature) {
  414. $models = uc_product_get_models($node->nid);
  415. // Check if editing or adding to set default values.
  416. if (!empty($feature)) {
  417. $product_role = db_query("SELECT * FROM {uc_roles_products} WHERE pfid = :pfid", array(':pfid' => $feature['pfid']))->fetchObject();
  418. $default_model = $product_role->model;
  419. $default_role = $product_role->rid;
  420. $default_qty = $product_role->duration;
  421. $default_granularity = $product_role->granularity;
  422. $default_shippable = $product_role->shippable;
  423. $default_by_quantity = $product_role->by_quantity;
  424. if ($product_role->end_time) {
  425. $end_time = array(
  426. 'day' => date('j', $product_role->end_time),
  427. 'month' => date('n', $product_role->end_time),
  428. 'year' => date('Y', $product_role->end_time),
  429. );
  430. $default_end_type = 'abs';
  431. }
  432. else {
  433. $temp = _uc_roles_get_expiration($default_qty, $default_granularity);
  434. $end_time = array(
  435. 'day' => date('j', $temp),
  436. 'month' => date('n', $temp),
  437. 'year' => date('Y', $temp),
  438. );
  439. $default_end_type = 'rel';
  440. }
  441. $form['pfid'] = array(
  442. '#type' => 'value',
  443. '#value' => $feature['pfid'],
  444. );
  445. $form['rpid'] = array(
  446. '#type' => 'value',
  447. '#value' => $product_role->rpid,
  448. );
  449. $default_end_override = $product_role->end_override;
  450. }
  451. else {
  452. $default_model = 0;
  453. $default_role = variable_get('uc_roles_default_role', NULL);
  454. $default_qty = (variable_get('uc_roles_default_granularity', 'never') == 'never') ? NULL : variable_get('uc_roles_default_length', NULL);
  455. $default_granularity = variable_get('uc_roles_default_granularity', 'never');
  456. $default_shippable = $node->shippable;
  457. $default_by_quantity = variable_get('uc_roles_default_by_quantity', FALSE);
  458. $end_time = variable_get('uc_roles_default_end_time', array(
  459. 'day' => date('j'),
  460. 'month' => date('n'),
  461. 'year' => date('Y'),
  462. ));
  463. $default_end_type = variable_get('uc_roles_default_end_expiration', 'rel');
  464. $default_end_override = FALSE;
  465. }
  466. $roles = _uc_roles_get_choices();
  467. if (!count($roles)) {
  468. // No actions can be done. Remove submit buttons.
  469. unset($form['buttons']);
  470. $form['no_roles'] = array(
  471. '#markup' => t('You need to <a href="!url">create new roles</a> before any can be added as product features.', array('!url' => url('admin/people/permissions/roles', array('query' => array('destination' => 'admin/store/settings/products'))))),
  472. '#prefix' => '<p>',
  473. '#suffix' => '</p>',
  474. );
  475. return $form;
  476. }
  477. $form['nid'] = array(
  478. '#type' => 'value',
  479. '#value' => $node->nid,
  480. );
  481. $form['uc_roles_model'] = array(
  482. '#type' => 'select',
  483. '#title' => t('SKU'),
  484. '#default_value' => $default_model,
  485. '#description' => t('This is the SKU of the product that will grant the role.'),
  486. '#options' => $models,
  487. );
  488. $form['uc_roles_role'] = array(
  489. '#type' => 'select',
  490. '#title' => t('Role'),
  491. '#default_value' => $default_role,
  492. '#description' => t('This is the role the customer will receive after purchasing the product.'),
  493. '#options' => $roles,
  494. );
  495. $form['uc_roles_shippable'] = array(
  496. '#type' => 'checkbox',
  497. '#title' => t('Shippable product'),
  498. '#default_value' => $default_shippable,
  499. '#description' => t('Check if this product SKU that uses role assignment is associated with a shippable product.'),
  500. );
  501. $form['end_override'] = array(
  502. '#type' => 'checkbox',
  503. '#title' => t('Override the <a href="!url">default role expiration</a>.', array('!url' => url('admin/store/settings/products'))),
  504. '#default_value' => $default_end_override,
  505. );
  506. $form['role_lifetime'] = array(
  507. '#type' => 'fieldset',
  508. '#title' => t('Role expiration'),
  509. '#states' => array(
  510. 'visible' => array('input[name="end_override"]' => array('checked' => TRUE)),
  511. ),
  512. );
  513. $form['role_lifetime']['expiration'] = array(
  514. '#type' => 'select',
  515. '#title' => t('Expiration type'),
  516. '#options' => array(
  517. 'rel' => t('Relative to purchase date'),
  518. 'abs' => t('Fixed date'),
  519. ),
  520. '#default_value' => $default_end_type,
  521. );
  522. $form['role_lifetime']['uc_roles_expire_relative_duration'] = array(
  523. '#type' => 'textfield',
  524. '#default_value' => $default_qty,
  525. '#size' => 4,
  526. '#maxlength' => 4,
  527. '#prefix' => '<div class="expiration">',
  528. '#suffix' => '</div>',
  529. '#states' => array(
  530. 'visible' => array('select[name="expiration"]' => array('value' => 'rel')),
  531. 'invisible' => array('select[name="uc_roles_expire_relative_granularity"]' => array('value' => 'never')),
  532. ),
  533. );
  534. $form['role_lifetime']['uc_roles_expire_relative_granularity'] = array(
  535. '#type' => 'select',
  536. '#options' => array(
  537. 'never' => t('never'),
  538. 'day' => t('day(s)'),
  539. 'week' => t('week(s)'),
  540. 'month' => t('month(s)'),
  541. 'year' => t('year(s)')
  542. ),
  543. '#default_value' => $default_granularity,
  544. '#description' => t('From the time the role was purchased.'),
  545. '#prefix' => '<div class="expiration">',
  546. '#suffix' => '</div>',
  547. '#states' => array(
  548. 'visible' => array('select[name="expiration"]' => array('value' => 'rel')),
  549. ),
  550. );
  551. $form['role_lifetime']['absolute'] = array(
  552. '#type' => 'container',
  553. '#states' => array(
  554. 'visible' => array('select[name="expiration"]' => array('value' => 'abs')),
  555. ),
  556. );
  557. $form['role_lifetime']['absolute']['uc_roles_expire_absolute'] = array(
  558. '#type' => 'date',
  559. '#description' => t('Expire the role at the beginning of this day.'),
  560. );
  561. if ($end_time) {
  562. $form['role_lifetime']['absolute']['uc_roles_expire_absolute']['#default_value'] = $end_time;
  563. }
  564. $form['role_lifetime']['uc_roles_by_quantity'] = array(
  565. '#type' => 'checkbox',
  566. '#title' => t('Multiply by quantity'),
  567. '#default_value' => $default_by_quantity,
  568. '#description' => t('Check if the role duration should be multiplied by the quantity purchased.'),
  569. );
  570. return $form;
  571. }
  572. /**
  573. * Validation function for the roles feature form.
  574. *
  575. * @see uc_roles_feature_form()
  576. * @see uc_roles_feature_form_submit()
  577. */
  578. function uc_roles_feature_form_validate($form, &$form_state) {
  579. // Invalid quantity?
  580. if ($form_state['values']['expiration'] === 'abs') {
  581. $form_state['values']['uc_roles_expire_absolute'] = mktime(0, 0, 0,
  582. $form_state['values']['uc_roles_expire_absolute']['month'],
  583. $form_state['values']['uc_roles_expire_absolute']['day'],
  584. $form_state['values']['uc_roles_expire_absolute']['year']
  585. );
  586. if ($form_state['values']['uc_roles_expire_absolute'] <= REQUEST_TIME) {
  587. form_set_error('uc_roles_expire_absolute', t('The specified date !date has already occurred. Please choose another.', array('!date' => format_date($form_state['values']['uc_roles_expire_absolute']))));
  588. }
  589. }
  590. else {
  591. if ($form_state['values']['uc_roles_expire_relative_granularity'] != 'never' && intval($form_state['values']['uc_roles_expire_relative_duration']) < 1) {
  592. form_set_error('uc_roles_expire_relative_duration', t('The amount of time must be a positive integer.'));
  593. }
  594. }
  595. // No roles?
  596. if (empty($form_state['values']['uc_roles_role'])) {
  597. form_set_error('uc_roles_role', t('You must have a role to assign. You may need to <a href="!role_url">create a new role</a> or perhaps <a href="!feature_url">set role assignment defaults</a>.', array('!role_url' => url('admin/people/permissions/roles'), '!feature_url' => url('admin/store/settings/products'))));
  598. }
  599. // This role already set on this SKU?
  600. if (!isset($form_state['values']['pfid']) && ($product_roles = db_query("SELECT * FROM {uc_roles_products} WHERE nid = :nid AND model = :model AND rid = :rid", array(':nid' => $form_state['values']['nid'], ':model' => $form_state['values']['uc_roles_model'], ':rid' => $form_state['values']['uc_roles_role']))->fetchObject())) {
  601. form_set_error('uc_roles_role', t('The combination of SKU and role already exists for this product.'));
  602. form_set_error('uc_roles_model', ' ');
  603. }
  604. }
  605. /**
  606. * Little helper for cleaning up input to drupal_write_record().
  607. */
  608. function uc_roles_product_write_record($product_role) {
  609. foreach (array('duration', 'granularity', 'end_time') as $property) {
  610. $product_role[$property] = $product_role[$property] === NULL ? 0 : $product_role[$property];
  611. }
  612. $key = array();
  613. if ($product_role['rpid']) {
  614. $key = 'rpid';
  615. }
  616. drupal_write_record('uc_roles_products', $product_role, $key);
  617. }
  618. /**
  619. * Submission handler for uc_roles_feature_form().
  620. *
  621. * @see uc_roles_feature_form()
  622. * @see uc_roles_feature_form_validate()
  623. */
  624. function uc_roles_feature_form_submit($form, &$form_state) {
  625. $product_role = array(
  626. 'pfid' => isset($form_state['values']['pfid']) ? $form_state['values']['pfid'] : NULL,
  627. 'rpid' => isset($form_state['values']['rpid']) ? $form_state['values']['rpid'] : NULL,
  628. 'nid' => $form_state['values']['nid'],
  629. 'model' => $form_state['values']['uc_roles_model'],
  630. 'rid' => $form_state['values']['uc_roles_role'],
  631. 'duration' => $form_state['values']['uc_roles_expire_relative_granularity'] != 'never' ? $form_state['values']['uc_roles_expire_relative_duration'] : NULL,
  632. 'granularity' => $form_state['values']['uc_roles_expire_relative_granularity'],
  633. 'by_quantity' => $form_state['values']['uc_roles_by_quantity'],
  634. 'shippable' => $form_state['values']['uc_roles_shippable'],
  635. // We should be setting NULL, but drupal_write_record() ...
  636. 'end_override' => $form_state['values']['end_override'],
  637. 'end_time' => $form_state['values']['expiration' ] === 'abs' ? $form_state['values']['uc_roles_expire_absolute'] : NULL,
  638. );
  639. $description = empty($product_role['model']) ? t('<strong>SKU:</strong> Any<br />') : t('<strong>SKU:</strong> !sku<br />', array('!sku' => $product_role['model']));
  640. $description .= t('<strong>Role:</strong> @role_name<br />', array('@role_name' => _uc_roles_get_name($product_role['rid'])));
  641. if ($product_role['end_override']) {
  642. if ($product_role['end_time']) {
  643. $description .= t('<strong>Expiration:</strong> !date<br />', array('!date' => format_date($product_role['end_time'])));
  644. }
  645. else {
  646. switch ($product_role['granularity']) {
  647. case 'never':
  648. $description .= t('<strong>Expiration:</strong> never<br />');
  649. break;
  650. case 'day':
  651. $description .= t('<strong>Expiration:</strong> !qty day(s)<br />', array('!qty' => $product_role['duration']));
  652. break;
  653. case 'week':
  654. $description .= t('<strong>Expiration:</strong> !qty week(s)<br />', array('!qty' => $product_role['duration']));
  655. break;
  656. case 'month':
  657. $description .= t('<strong>Expiration:</strong> !qty month(s)<br />', array('!qty' => $product_role['duration']));
  658. break;
  659. case 'year':
  660. $description .= t('<strong>Expiration:</strong> !qty year(s)<br />', array('!qty' => $product_role['duration']));
  661. break;
  662. default:
  663. break;
  664. }
  665. }
  666. }
  667. else {
  668. $description .= t('<strong>Expiration:</strong> !link (not overridden)<br />', array('!link' => l(t('Global expiration'), 'admin/store/settings/products')));
  669. }
  670. $description .= $product_role['shippable'] ? t('<strong>Shippable:</strong> Yes<br />') : t('<strong>Shippable:</strong> No<br />');
  671. $description .= $product_role['by_quantity'] ? t('<strong>Multiply by quantity:</strong> Yes') : t('<strong>Multiply by quantity:</strong> No');
  672. $data = array(
  673. 'pfid' => $product_role['pfid'],
  674. 'nid' => $product_role['nid'],
  675. 'fid' => 'role',
  676. 'description' => $description,
  677. );
  678. $form_state['redirect'] = uc_product_feature_save($data);
  679. $product_role['pfid'] = $data['pfid'];
  680. // Insert or update uc_file_product table.
  681. uc_roles_product_write_record($product_role);
  682. }
  683. /**
  684. * Form builder for role settings.
  685. *
  686. * @ingroup forms
  687. */
  688. function uc_roles_feature_settings($form, &$form_state) {
  689. $default_role_choices = user_roles(TRUE);
  690. unset($default_role_choices[DRUPAL_AUTHENTICATED_RID]);
  691. if (!count($default_role_choices)) {
  692. $form['no_roles'] = array(
  693. '#markup' => t('You need to <a href="!url">create new roles</a> before any can be added as product features.', array('!url' => url('admin/people/permissions/roles', array('query' => array('destination' => 'admin/store/settings/products'))))),
  694. '#prefix' => '<p>',
  695. '#suffix' => '</p>',
  696. );
  697. return $form;
  698. }
  699. foreach (uc_order_status_list('general') as $status) {
  700. $statuses[$status['id']] = $status['title'];
  701. }
  702. $form['uc_roles_default_role'] = array(
  703. '#type' => 'select',
  704. '#title' => t('Default role'),
  705. '#default_value' => variable_get('uc_roles_default_role', NULL),
  706. '#description' => t('The default role Ubercart grants on specified products.'),
  707. '#options' => _uc_roles_get_choices(),
  708. );
  709. $form['uc_roles_default_role_choices'] = array(
  710. '#type' => 'checkboxes',
  711. '#title' => t('Product roles'),
  712. '#default_value' => variable_get('uc_roles_default_role_choices', array()),
  713. '#multiple' => TRUE,
  714. '#description' => t('These are roles that Ubercart can grant to customers who purchase specified products. If you leave all roles unchecked, they will all be eligible for adding to a product.'),
  715. '#options' => $default_role_choices,
  716. );
  717. $form['role_lifetime'] = array(
  718. '#type' => 'fieldset',
  719. '#title' => t('Default role expiration'),
  720. );
  721. $form['role_lifetime']['uc_roles_default_end_expiration'] = array(
  722. '#type' => 'select',
  723. '#title' => t('Expiration type'),
  724. '#options' => array(
  725. 'rel' => t('Relative to purchase date'),
  726. 'abs' => t('Fixed date'),
  727. ),
  728. '#default_value' => variable_get('uc_roles_default_end_expiration', 'rel'),
  729. );
  730. $form['role_lifetime']['uc_roles_default_length'] = array(
  731. '#type' => 'textfield',
  732. '#default_value' => (variable_get('uc_roles_default_granularity', 'never') == 'never') ? NULL : variable_get('uc_roles_default_length', NULL),
  733. '#size' => 4,
  734. '#maxlength' => 4,
  735. '#prefix' => '<div class="expiration">',
  736. '#suffix' => '</div>',
  737. '#states' => array(
  738. 'visible' => array('select[name="uc_roles_default_end_expiration"]' => array('value' => 'rel')),
  739. 'invisible' => array('select[name="uc_roles_default_granularity"]' => array('value' => 'never')),
  740. ),
  741. );
  742. $form['role_lifetime']['uc_roles_default_granularity'] = array(
  743. '#type' => 'select',
  744. '#default_value' => variable_get('uc_roles_default_granularity', 'never'),
  745. '#options' => array(
  746. 'never' => t('never'),
  747. 'day' => t('day(s)'),
  748. 'week' => t('week(s)'),
  749. 'month' => t('month(s)'),
  750. 'year' => t('year(s)')
  751. ),
  752. '#description' => t('From the time the role was purchased.'),
  753. '#prefix' => '<div class="expiration">',
  754. '#suffix' => '</div>',
  755. '#states' => array(
  756. 'visible' => array('select[name="uc_roles_default_end_expiration"]' => array('value' => 'rel')),
  757. ),
  758. );
  759. $form['role_lifetime']['absolute'] = array(
  760. '#type' => 'container',
  761. '#states' => array(
  762. 'visible' => array('select[name="uc_roles_default_end_expiration"]' => array('value' => 'abs')),
  763. ),
  764. );
  765. $form['role_lifetime']['absolute']['uc_roles_default_end_time'] = array(
  766. '#type' => 'date',
  767. '#description' => t('Expire the role at the beginning of this day.'),
  768. '#default_value' => variable_get('uc_roles_default_end_time', array(
  769. 'day' => date('j'),
  770. 'month' => date('n'),
  771. 'year' => date('Y'),
  772. )),
  773. );
  774. $form['role_lifetime']['uc_roles_default_by_quantity'] = array(
  775. '#type' => 'checkbox',
  776. '#title' => t('Multiply by quantity'),
  777. '#description' => t('Check if the role duration should be multiplied by the quantity purchased.'),
  778. '#default_value' => variable_get('uc_roles_default_by_quantity', FALSE),
  779. );
  780. $form['reminder']['uc_roles_reminder_length'] = array(
  781. '#type' => 'textfield',
  782. '#title' => t('Time before reminder'),
  783. '#default_value' => (variable_get('uc_roles_reminder_granularity', 'never') == 'never') ? NULL : variable_get('uc_roles_reminder_length', NULL),
  784. '#size' => 4,
  785. '#maxlength' => 4,
  786. '#prefix' => '<div class="expiration">',
  787. '#suffix' => '</div>',
  788. '#states' => array(
  789. 'disabled' => array('select[name="uc_roles_reminder_granularity"]' => array('value' => 'never')),
  790. ),
  791. );
  792. $form['reminder']['uc_roles_reminder_granularity'] = array(
  793. '#type' => 'select',
  794. '#default_value' => variable_get('uc_roles_reminder_granularity', 'never'),
  795. '#options' => array(
  796. 'never' => t('never'),
  797. 'day' => t('day(s)'),
  798. 'week' => t('week(s)'),
  799. 'month' => t('month(s)'),
  800. 'year' => t('year(s)')
  801. ),
  802. '#description' => t('The amount of time before a role expiration takes place that a customer is notified of its expiration.'),
  803. '#prefix' => '<div class="expiration">',
  804. '#suffix' => '</div>',
  805. );
  806. $form['uc_roles_default_show_expiration'] = array(
  807. '#type' => 'checkbox',
  808. '#title' => t('Show expirations on user page'),
  809. '#default_value' => variable_get('uc_roles_default_show_expiration', TRUE),
  810. '#description' => t('If users have any role expirations they will be displayed on their account page.'),
  811. );
  812. return $form;
  813. }
  814. /**
  815. * Gets role name.
  816. *
  817. * @param $rid
  818. * The Drupal role id number.
  819. *
  820. * @return
  821. * A string containing the name of the role, returns FALSE if rid is invalid.
  822. */
  823. function _uc_roles_get_name($rid) {
  824. $roles = user_roles(TRUE);
  825. return (!is_null($roles[$rid])) ? $roles[$rid] : FALSE;
  826. }
  827. /**
  828. * Gets available roles for granting on product purchase.
  829. *
  830. * @param $exclude
  831. * A list of role ids to exclude from the list.
  832. *
  833. * @return
  834. * An assoc array with key = rid and value = role name.
  835. */
  836. function _uc_roles_get_choices($exclude = array()) {
  837. $output = array();
  838. // Get roles from Drupal, excluding Anonymous and Authenticated.
  839. $roles = user_roles(TRUE);
  840. unset($roles[DRUPAL_AUTHENTICATED_RID]);
  841. // User set specific roles that we must use?
  842. $selected = variable_get('uc_roles_default_role_choices', array());
  843. // If there's none, or if none are checked, use all of em.
  844. $default = empty($selected) || array_sum($selected) == 0;
  845. foreach ($roles as $rid => $name) {
  846. if ($default || (!empty($selected[$rid]) && !in_array($rid, $exclude))) {
  847. $output[$rid] = $roles[$rid];
  848. }
  849. }
  850. return $output;
  851. }
  852. /**
  853. * Deletes all data associated with a given product feature.
  854. *
  855. * @param $pfid
  856. * An Ubercart product feature ID.
  857. */
  858. function uc_roles_feature_delete($pfid) {
  859. db_delete('uc_roles_products')
  860. ->condition('pfid', $pfid)
  861. ->execute();
  862. }
  863. /**
  864. * Deletes an expiration using user id or user id and rid.
  865. *
  866. * This function deletes expirations associated with users and roles. If
  867. * no role ID is passed, the function deletes all role expirations associated
  868. * with the given user. Otherwise, the function only deletes expirations whose
  869. * user and role IDs match. If any roles were actually deleted, the function
  870. * notifies the user. The menu cache is then flushed, as privileges to view
  871. * menu items may have been lost in the process.
  872. *
  873. * @param $account
  874. * A Drupal user object.
  875. * @param $rid
  876. * A Drupal role ID.
  877. * @param $silent
  878. * When set to TRUE will suppress any Drupal messages from this function.
  879. */
  880. function uc_roles_delete($account, $rid = NULL, $silent = FALSE) {
  881. global $user;
  882. $query = db_delete('uc_roles_expirations')
  883. ->condition('uid', $account->uid);
  884. if ($rid) {
  885. $query->condition('rid', $rid);
  886. }
  887. // Echo the deletion only if something was actually deleted.
  888. if ($query->execute() && !$silent) {
  889. if ($user->uid == $account->uid) {
  890. drupal_set_message(t('The expiration of your %role_name role has been deleted.', array('%role_name' => _uc_roles_get_name($rid))));
  891. }
  892. else {
  893. drupal_set_message(t('The expiration of %role_name role for the user !user has been deleted.', array(
  894. '!user' => theme('username', array(
  895. 'account' => $account,
  896. 'name' => check_plain(format_username($account)),
  897. 'link_path' => 'user/' . $account->uid,
  898. )),
  899. '%role_name' => _uc_roles_get_name($rid),
  900. )));
  901. }
  902. }
  903. // Flush visible menu items, since our permissions could've changed.
  904. _uc_roles_flush_menu_cache($account);
  905. }
  906. /**
  907. * Revokes a role on a given user
  908. *
  909. * This function deletes a given role from a user's list of roles, as
  910. * well as removing any expiration data associated with the user/role.
  911. * The function notifies the user of revocation.
  912. *
  913. * @param $account
  914. * A Drupal user object.
  915. * @param $rid
  916. * A Drupal role ID.
  917. * @param $silent
  918. * When set to TRUE will suppress any Drupal messages from this function.
  919. */
  920. function uc_roles_revoke(&$account, $rid, $silent = FALSE) {
  921. global $user;
  922. // Remove this role from the user's list.
  923. $roles_list = $account->roles;
  924. unset($roles_list[$rid]);
  925. $account = user_save($account, array('roles' => $roles_list));
  926. // Remove our record of the expiration.
  927. uc_roles_delete($account, $rid, $silent);
  928. $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => $rid))->fetchField();
  929. if (!$silent) {
  930. if ($user->uid == $account->uid) {
  931. drupal_set_message(t('Your %role role has been revoked.', array('%role' => $role_name)));
  932. }
  933. else {
  934. drupal_set_message(t('!user has had the %role role revoked.', array(
  935. '!user' => theme('username', array(
  936. 'account' => $account,
  937. 'name' => check_plain(format_username($account)),
  938. 'link_path' => 'user/' . $account->uid,
  939. )),
  940. '%role' => $role_name,
  941. )));
  942. }
  943. }
  944. }
  945. /**
  946. * Grants a role to a given user
  947. *
  948. * This function grants a given role to a user's list of roles. If there
  949. * is a previous record of this user/role combination, it is first removed.
  950. * The function then saves the user (if $user_save is TRUE). Next, a check
  951. * to verify the role actually exists, if not, no expiration data is stored.
  952. * The menu cache is flushed, as new menu items may be visible after the
  953. * new role is granted. The function notifies the user of the role grant.
  954. *
  955. * @param $account
  956. * A Drupal user object.
  957. * @param $rid
  958. * A Drupal role ID.
  959. * @param $timestamp
  960. * When this role will expire.
  961. * @param $save_user
  962. * Optimization to prevent unnecessary user saving when calling from
  963. * uc_roles_user_presave().
  964. * @param $silent
  965. * When set to TRUE will suppress any Drupal messages from this function.
  966. */
  967. function uc_roles_grant(&$account, $rid, $timestamp, $save_user = TRUE, $silent = FALSE) {
  968. global $user;
  969. // First, delete any previous record of this user/role association.
  970. uc_roles_delete($account, $rid, $silent);
  971. if ($save_user) {
  972. // Punch the role into the user object.
  973. $roles_list = $account->roles + array($rid => _uc_roles_get_name($rid));
  974. $account = user_save($account, array('roles' => $roles_list));
  975. }
  976. // If the role expires, keep a record.
  977. if (!is_null($timestamp)) {
  978. db_insert('uc_roles_expirations')
  979. ->fields(array(
  980. 'uid' => $account->uid,
  981. 'rid' => $rid,
  982. 'expiration' => $timestamp,
  983. ))
  984. ->execute();
  985. }
  986. // Flush visible menu items, since our permissions could've changed.
  987. _uc_roles_flush_menu_cache($account);
  988. // Display the message if appropriate.
  989. if (!$silent) {
  990. $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => $rid))->fetchField();
  991. if ($user->uid == $account->uid) {
  992. $message = t('You have been granted the %role role.', array('%role' => $role_name));
  993. }
  994. else {
  995. $message = t('!user has been granted the %role role.', array(
  996. '!user' => theme('username', array(
  997. 'account' => $account,
  998. 'name' => check_plain(format_username($account)),
  999. 'link_path' => 'user/' . $account->uid,
  1000. )),
  1001. '%role' => $role_name,
  1002. ));
  1003. }
  1004. if ($timestamp) {
  1005. $message .= ' ' . t('It will expire on %date', array('%date' => format_date($timestamp, 'short')));
  1006. }
  1007. drupal_set_message($message);
  1008. }
  1009. }
  1010. /**
  1011. * Renews a given role on a user.
  1012. *
  1013. * This function updates expiration time on a role already granted to a
  1014. * user. First the function checks the new expiration. If it never expires,
  1015. * the function deletes the past expiration record and returns, leaving
  1016. * management up to Drupal. Otherwise, the record is updated with the new
  1017. * expiration time, and the user is notified of the change.
  1018. *
  1019. * @param $account
  1020. * A Drupal user object.
  1021. * @param $rid
  1022. * A Drupal role ID.
  1023. * @param $timestamp
  1024. * When this role will expire.
  1025. * @param $silent
  1026. * When set to TRUE will suppress any Drupal messages from this function.
  1027. */
  1028. function uc_roles_renew($account, $rid, $timestamp, $silent = FALSE) {
  1029. global $user;
  1030. // If it doesn't expire, we'll remove our data associated with it.
  1031. // After that, Drupal will take care of it.
  1032. if (is_null($timestamp)) {
  1033. uc_roles_delete($account, $rid);
  1034. return;
  1035. }
  1036. // Update the expiration date and reset the notified flag.
  1037. db_update('uc_roles_expirations')
  1038. ->fields(array(
  1039. 'expiration' => $timestamp,
  1040. 'notified' => NULL,
  1041. ))
  1042. ->condition('uid', $account->uid)
  1043. ->condition('rid', $rid)
  1044. ->execute();
  1045. if (!$silent) {
  1046. $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => $rid))->fetchField();
  1047. if ($user->uid == $account->uid) {
  1048. $message = t('Your %role role has been renewed. It will expire on %date.', array('%role' => $role_name, '%date' => format_date($timestamp, 'short')));
  1049. }
  1050. else {
  1051. $message = t("!user's %role role has been renewed. It will expire on %date.", array(
  1052. '!user' => theme('username', array(
  1053. 'account' => $account,
  1054. 'name' => check_plain(format_username($account)),
  1055. 'link_path' => 'user/' . $account->uid,
  1056. )),
  1057. '%role' => $role_name,
  1058. '%date' => format_date($timestamp, 'short'),
  1059. ));
  1060. }
  1061. drupal_set_message($message);
  1062. }
  1063. }
  1064. /**
  1065. * Flushes the menu cache.
  1066. *
  1067. * When roles are gained/lost, menu items might appear/disappear respectively,
  1068. * so we have to ensure the cache is rebuilt with any new values.
  1069. *
  1070. * @param $account
  1071. * A Drupal user object.
  1072. *
  1073. * @see uc_roles_delete()
  1074. * @see uc_roles_grant()
  1075. */
  1076. function _uc_roles_flush_menu_cache($account) {
  1077. cache_clear_all($account->uid . ':', 'cache_menu', TRUE);
  1078. }
  1079. /**
  1080. * Calculates the expiration time using a role_product object.
  1081. *
  1082. * @param $role_product
  1083. * The role product object whose expiration times to calculate.
  1084. * @param $quantity
  1085. * Used to multiply any relative expiration time, if the $role_product
  1086. * says to.
  1087. * @param $time
  1088. * The current time to use as a starting point for relative expiration
  1089. * calculation.
  1090. */
  1091. function _uc_roles_product_get_expiration($role_product, $quantity, $time) {
  1092. // Override the end expiration?
  1093. if ($role_product->end_override) {
  1094. // Absolute times are easy...
  1095. if ($role_product->end_time) {
  1096. return $role_product->end_time;
  1097. }
  1098. // We're gonna have to calculate the relative time from $time.
  1099. $length = $role_product->duration * ($role_product->by_quantity ? $quantity : 1);
  1100. return _uc_roles_get_expiration($length, $role_product->granularity, $time);
  1101. }
  1102. // No override, use the default expiration values.
  1103. else {
  1104. // Relative...
  1105. if (variable_get('uc_roles_default_end_expiration', 'rel') === 'rel') {
  1106. $length = variable_get('uc_roles_default_length', NULL) * ($role_product->by_quantity ? $quantity : 1);
  1107. return _uc_roles_get_expiration($length, variable_get('uc_roles_default_granularity', 'never'), $time);
  1108. }
  1109. // Absolute...
  1110. $end_time = variable_get('uc_roles_default_end_time', NULL);
  1111. if ($end_time) {
  1112. $end_time = mktime(0, 0, 0, $end_time['month'], $end_time['day'], $end_time['year']);
  1113. }
  1114. return $end_time;
  1115. }
  1116. }
  1117. /**
  1118. * Returns an expiration time stamp given a period of time.
  1119. *
  1120. * @param $duration
  1121. * The amount of time until expiration.
  1122. * @param $granularity
  1123. * A string representing the granularity's name (e.g. "day", "month", etc.).
  1124. * @param $start_time
  1125. * (optional) The starting date for when the role will last. Defaults to
  1126. * the current time.
  1127. *
  1128. * @return
  1129. * A UNIX timestamp representing the second that expiration takes place,
  1130. * or NULL if the expiration should never occur.
  1131. */
  1132. function _uc_roles_get_expiration($duration, $granularity, $start_time = NULL) {
  1133. // Never expires?
  1134. if ($granularity == 'never') {
  1135. return NULL;
  1136. }
  1137. $start_time = (!is_null($start_time)) ? $start_time : REQUEST_TIME;
  1138. $operator = ($duration < 0) ? '' : '+';
  1139. return strtotime($operator . $duration . ' ' . $granularity, $start_time);
  1140. }
  1141. /**
  1142. * Implements hook_views_api().
  1143. */
  1144. function uc_roles_views_api() {
  1145. return array('api' => '3.0');
  1146. }