uc_roles.module 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  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. $allowed_uc_roles = _uc_roles_get_choices();
  294. foreach ($account->roles as $rid => $role) {
  295. if (isset($allowed_uc_roles[$rid]) && !$edit['roles'][$rid]) {
  296. uc_roles_delete($account, $rid);
  297. }
  298. }
  299. }
  300. }
  301. /**
  302. * Implements hook_user_view().
  303. *
  304. * Displays role expirations on the user account screen.
  305. */
  306. function uc_roles_user_view($account, $view_mode) {
  307. global $user;
  308. // Kick out anonymous.
  309. if (!$user->uid) {
  310. return;
  311. }
  312. // Only show if this user can access all role expirations, or if it's the same
  313. // user and the expirations are showing on the user pages.
  314. $show_expiration = variable_get('uc_roles_default_show_expiration', TRUE);
  315. if (!user_access('view all role expirations') && ($user->uid != $account->uid || !$show_expiration)) {
  316. return;
  317. }
  318. $items = array();
  319. $form = array();
  320. $expirations = db_query("SELECT * FROM {uc_roles_expirations} WHERE uid = :uid", array(':uid' => $account->uid));
  321. foreach ($expirations as $expiration) {
  322. $form[$expiration->rid] = array(
  323. '#type' => 'user_profile_item',
  324. '#title' => check_plain(_uc_roles_get_name($expiration->rid)),
  325. '#markup' => t('This role will expire on !date', array('!date' => format_date($expiration->expiration, 'short'))),
  326. );
  327. }
  328. // Don't display anything if there aren't any expirations.
  329. if (!count($form)) {
  330. return;
  331. }
  332. $item = array(
  333. '#type' => 'user_profile_category',
  334. '#weight' => '-1',
  335. '#title' => t('Expiring roles'),
  336. );
  337. $account->content['uc_roles'] = $item + $form;
  338. }
  339. /**
  340. * Implements hook_uc_order_product_can_ship().
  341. */
  342. function uc_roles_uc_order_product_can_ship($item) {
  343. $roles = db_query("SELECT * FROM {uc_roles_products} WHERE nid = :nid", array(':nid' => $item->nid));
  344. foreach ($roles as $role) {
  345. // If the model is empty, keep looking. (Everyone needs a role model...)
  346. if (empty($role->model)) {
  347. continue;
  348. }
  349. // If there's an adjusted SKU, use it... otherwise use the node SKU.
  350. $sku = (empty($item->data['model'])) ? $item->model : $item->data['model'];
  351. // Keep looking if it doesn't match.
  352. if ($sku != $role->model) {
  353. continue;
  354. }
  355. return $role->shippable;
  356. }
  357. }
  358. /**
  359. * Implements hook_uc_product_feature().
  360. */
  361. function uc_roles_uc_product_feature() {
  362. $features[] = array(
  363. 'id' => 'role',
  364. 'title' => t('Role assignment'),
  365. 'callback' => 'uc_roles_feature_form',
  366. 'delete' => 'uc_roles_feature_delete',
  367. 'settings' => 'uc_roles_feature_settings',
  368. );
  369. return $features;
  370. }
  371. /**
  372. * Implements hook_uc_store_status().
  373. */
  374. function uc_roles_uc_store_status() {
  375. $message = array();
  376. $role_choices = _uc_roles_get_choices();
  377. if (empty($role_choices)) {
  378. $message[] = array(
  379. 'status' => 'warning',
  380. 'title' => t('Roles'),
  381. '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'))),
  382. );
  383. }
  384. else {
  385. $message[] = array(
  386. 'status' => 'ok',
  387. 'title' => t('Roles'),
  388. 'desc' => t('The role(s) %roles are set to be used with the Role Assignment product feature.', array('%roles' => implode(', ', $role_choices))),
  389. );
  390. }
  391. return $message;
  392. }
  393. /**
  394. * Implements hook_uc_message().
  395. */
  396. function uc_roles_uc_message() {
  397. $messages['uc_roles_grant_subject'] = t('[store:name]: [expiration:name] role granted');
  398. $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]");
  399. $messages['uc_roles_revoke_subject'] = t('[store:name]: [expiration:name] role expired');
  400. $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]");
  401. $messages['uc_roles_renew_subject'] = t('[store:name]: [expiration:name] role renewed');
  402. $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]");
  403. $messages['uc_roles_reminder_subject'] = t('[store:name]: [expiration:name] role expiration notice');
  404. $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]");
  405. return $messages;
  406. }
  407. /**
  408. * Form builder for hook_uc_product_feature().
  409. *
  410. * @see uc_roles_feature_form_validate()
  411. * @see uc_roles_feature_form_submit()
  412. * @ingroup forms
  413. */
  414. function uc_roles_feature_form($form, &$form_state, $node, $feature) {
  415. $models = uc_product_get_models($node->nid);
  416. // Check if editing or adding to set default values.
  417. if (!empty($feature)) {
  418. $product_role = db_query("SELECT * FROM {uc_roles_products} WHERE pfid = :pfid", array(':pfid' => $feature['pfid']))->fetchObject();
  419. $default_model = $product_role->model;
  420. $default_role = $product_role->rid;
  421. $default_qty = $product_role->duration;
  422. $default_granularity = $product_role->granularity;
  423. $default_shippable = $product_role->shippable;
  424. $default_by_quantity = $product_role->by_quantity;
  425. if ($product_role->end_time) {
  426. $end_time = array(
  427. 'day' => date('j', $product_role->end_time),
  428. 'month' => date('n', $product_role->end_time),
  429. 'year' => date('Y', $product_role->end_time),
  430. );
  431. $default_end_type = 'abs';
  432. }
  433. else {
  434. $temp = _uc_roles_get_expiration($default_qty, $default_granularity);
  435. $end_time = array(
  436. 'day' => date('j', $temp),
  437. 'month' => date('n', $temp),
  438. 'year' => date('Y', $temp),
  439. );
  440. $default_end_type = 'rel';
  441. }
  442. $form['pfid'] = array(
  443. '#type' => 'value',
  444. '#value' => $feature['pfid'],
  445. );
  446. $form['rpid'] = array(
  447. '#type' => 'value',
  448. '#value' => $product_role->rpid,
  449. );
  450. $default_end_override = $product_role->end_override;
  451. }
  452. else {
  453. $default_model = 0;
  454. $default_role = variable_get('uc_roles_default_role', NULL);
  455. $default_qty = (variable_get('uc_roles_default_granularity', 'never') == 'never') ? NULL : variable_get('uc_roles_default_length', NULL);
  456. $default_granularity = variable_get('uc_roles_default_granularity', 'never');
  457. $default_shippable = $node->shippable;
  458. $default_by_quantity = variable_get('uc_roles_default_by_quantity', FALSE);
  459. $end_time = variable_get('uc_roles_default_end_time', array(
  460. 'day' => date('j'),
  461. 'month' => date('n'),
  462. 'year' => date('Y'),
  463. ));
  464. $default_end_type = variable_get('uc_roles_default_end_expiration', 'rel');
  465. $default_end_override = FALSE;
  466. }
  467. $roles = _uc_roles_get_choices();
  468. if (!count($roles)) {
  469. // No actions can be done. Remove submit buttons.
  470. unset($form['buttons']);
  471. $form['no_roles'] = array(
  472. '#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'))))),
  473. '#prefix' => '<p>',
  474. '#suffix' => '</p>',
  475. );
  476. return $form;
  477. }
  478. $form['nid'] = array(
  479. '#type' => 'value',
  480. '#value' => $node->nid,
  481. );
  482. $form['uc_roles_model'] = array(
  483. '#type' => 'select',
  484. '#title' => t('SKU'),
  485. '#default_value' => $default_model,
  486. '#description' => t('This is the SKU of the product that will grant the role.'),
  487. '#options' => $models,
  488. );
  489. $form['uc_roles_role'] = array(
  490. '#type' => 'select',
  491. '#title' => t('Role'),
  492. '#default_value' => $default_role,
  493. '#description' => t('This is the role the customer will receive after purchasing the product.'),
  494. '#options' => $roles,
  495. );
  496. $form['uc_roles_shippable'] = array(
  497. '#type' => 'checkbox',
  498. '#title' => t('Shippable product'),
  499. '#default_value' => $default_shippable,
  500. '#description' => t('Check if this product SKU that uses role assignment is associated with a shippable product.'),
  501. );
  502. $form['end_override'] = array(
  503. '#type' => 'checkbox',
  504. '#title' => t('Override the <a href="!url">default role expiration</a>.', array('!url' => url('admin/store/settings/products'))),
  505. '#default_value' => $default_end_override,
  506. );
  507. $form['role_lifetime'] = array(
  508. '#type' => 'fieldset',
  509. '#title' => t('Role expiration'),
  510. '#states' => array(
  511. 'visible' => array('input[name="end_override"]' => array('checked' => TRUE)),
  512. ),
  513. );
  514. $form['role_lifetime']['expiration'] = array(
  515. '#type' => 'select',
  516. '#title' => t('Expiration type'),
  517. '#options' => array(
  518. 'rel' => t('Relative to purchase date'),
  519. 'abs' => t('Fixed date'),
  520. ),
  521. '#default_value' => $default_end_type,
  522. );
  523. $form['role_lifetime']['uc_roles_expire_relative_duration'] = array(
  524. '#type' => 'textfield',
  525. '#default_value' => $default_qty,
  526. '#size' => 4,
  527. '#maxlength' => 4,
  528. '#prefix' => '<div class="expiration">',
  529. '#suffix' => '</div>',
  530. '#states' => array(
  531. 'visible' => array('select[name="expiration"]' => array('value' => 'rel')),
  532. 'invisible' => array('select[name="uc_roles_expire_relative_granularity"]' => array('value' => 'never')),
  533. ),
  534. );
  535. $form['role_lifetime']['uc_roles_expire_relative_granularity'] = array(
  536. '#type' => 'select',
  537. '#options' => array(
  538. 'never' => t('never'),
  539. 'day' => t('day(s)'),
  540. 'week' => t('week(s)'),
  541. 'month' => t('month(s)'),
  542. 'year' => t('year(s)')
  543. ),
  544. '#default_value' => $default_granularity,
  545. '#description' => t('From the time the role was purchased.'),
  546. '#prefix' => '<div class="expiration">',
  547. '#suffix' => '</div>',
  548. '#states' => array(
  549. 'visible' => array('select[name="expiration"]' => array('value' => 'rel')),
  550. ),
  551. );
  552. $form['role_lifetime']['absolute'] = array(
  553. '#type' => 'container',
  554. '#states' => array(
  555. 'visible' => array('select[name="expiration"]' => array('value' => 'abs')),
  556. ),
  557. );
  558. $form['role_lifetime']['absolute']['uc_roles_expire_absolute'] = array(
  559. '#type' => 'date',
  560. '#description' => t('Expire the role at the beginning of this day.'),
  561. );
  562. if ($end_time) {
  563. $form['role_lifetime']['absolute']['uc_roles_expire_absolute']['#default_value'] = $end_time;
  564. }
  565. $form['role_lifetime']['uc_roles_by_quantity'] = array(
  566. '#type' => 'checkbox',
  567. '#title' => t('Multiply by quantity'),
  568. '#default_value' => $default_by_quantity,
  569. '#description' => t('Check if the role duration should be multiplied by the quantity purchased.'),
  570. );
  571. return $form;
  572. }
  573. /**
  574. * Validation function for the roles feature form.
  575. *
  576. * @see uc_roles_feature_form()
  577. * @see uc_roles_feature_form_submit()
  578. */
  579. function uc_roles_feature_form_validate($form, &$form_state) {
  580. // Invalid quantity?
  581. if ($form_state['values']['expiration'] === 'abs') {
  582. $form_state['values']['uc_roles_expire_absolute'] = mktime(0, 0, 0,
  583. $form_state['values']['uc_roles_expire_absolute']['month'],
  584. $form_state['values']['uc_roles_expire_absolute']['day'],
  585. $form_state['values']['uc_roles_expire_absolute']['year']
  586. );
  587. if ($form_state['values']['uc_roles_expire_absolute'] <= REQUEST_TIME) {
  588. 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']))));
  589. }
  590. }
  591. else {
  592. if ($form_state['values']['uc_roles_expire_relative_granularity'] != 'never' && intval($form_state['values']['uc_roles_expire_relative_duration']) < 1) {
  593. form_set_error('uc_roles_expire_relative_duration', t('The amount of time must be a positive integer.'));
  594. }
  595. }
  596. // No roles?
  597. if (empty($form_state['values']['uc_roles_role'])) {
  598. 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'))));
  599. }
  600. // This role already set on this SKU?
  601. 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())) {
  602. form_set_error('uc_roles_role', t('The combination of SKU and role already exists for this product.'));
  603. form_set_error('uc_roles_model', ' ');
  604. }
  605. }
  606. /**
  607. * Little helper for cleaning up input to drupal_write_record().
  608. */
  609. function uc_roles_product_write_record($product_role) {
  610. foreach (array('duration', 'granularity', 'end_time') as $property) {
  611. $product_role[$property] = $product_role[$property] === NULL ? 0 : $product_role[$property];
  612. }
  613. $key = array();
  614. if ($product_role['rpid']) {
  615. $key = 'rpid';
  616. }
  617. drupal_write_record('uc_roles_products', $product_role, $key);
  618. }
  619. /**
  620. * Submission handler for uc_roles_feature_form().
  621. *
  622. * @see uc_roles_feature_form()
  623. * @see uc_roles_feature_form_validate()
  624. */
  625. function uc_roles_feature_form_submit($form, &$form_state) {
  626. $product_role = array(
  627. 'pfid' => isset($form_state['values']['pfid']) ? $form_state['values']['pfid'] : NULL,
  628. 'rpid' => isset($form_state['values']['rpid']) ? $form_state['values']['rpid'] : NULL,
  629. 'nid' => $form_state['values']['nid'],
  630. 'model' => $form_state['values']['uc_roles_model'],
  631. 'rid' => $form_state['values']['uc_roles_role'],
  632. 'duration' => $form_state['values']['uc_roles_expire_relative_granularity'] != 'never' ? $form_state['values']['uc_roles_expire_relative_duration'] : NULL,
  633. 'granularity' => $form_state['values']['uc_roles_expire_relative_granularity'],
  634. 'by_quantity' => $form_state['values']['uc_roles_by_quantity'],
  635. 'shippable' => $form_state['values']['uc_roles_shippable'],
  636. // We should be setting NULL, but drupal_write_record() ...
  637. 'end_override' => $form_state['values']['end_override'],
  638. 'end_time' => $form_state['values']['expiration' ] === 'abs' ? $form_state['values']['uc_roles_expire_absolute'] : NULL,
  639. );
  640. $description = empty($product_role['model']) ? t('<strong>SKU:</strong> Any<br />') : t('<strong>SKU:</strong> !sku<br />', array('!sku' => $product_role['model']));
  641. $description .= t('<strong>Role:</strong> @role_name<br />', array('@role_name' => _uc_roles_get_name($product_role['rid'])));
  642. if ($product_role['end_override']) {
  643. if ($product_role['end_time']) {
  644. $description .= t('<strong>Expiration:</strong> !date<br />', array('!date' => format_date($product_role['end_time'])));
  645. }
  646. else {
  647. switch ($product_role['granularity']) {
  648. case 'never':
  649. $description .= t('<strong>Expiration:</strong> never<br />');
  650. break;
  651. case 'day':
  652. $description .= t('<strong>Expiration:</strong> !qty day(s)<br />', array('!qty' => $product_role['duration']));
  653. break;
  654. case 'week':
  655. $description .= t('<strong>Expiration:</strong> !qty week(s)<br />', array('!qty' => $product_role['duration']));
  656. break;
  657. case 'month':
  658. $description .= t('<strong>Expiration:</strong> !qty month(s)<br />', array('!qty' => $product_role['duration']));
  659. break;
  660. case 'year':
  661. $description .= t('<strong>Expiration:</strong> !qty year(s)<br />', array('!qty' => $product_role['duration']));
  662. break;
  663. default:
  664. break;
  665. }
  666. }
  667. }
  668. else {
  669. $description .= t('<strong>Expiration:</strong> !link (not overridden)<br />', array('!link' => l(t('Global expiration'), 'admin/store/settings/products')));
  670. }
  671. $description .= $product_role['shippable'] ? t('<strong>Shippable:</strong> Yes<br />') : t('<strong>Shippable:</strong> No<br />');
  672. $description .= $product_role['by_quantity'] ? t('<strong>Multiply by quantity:</strong> Yes') : t('<strong>Multiply by quantity:</strong> No');
  673. $data = array(
  674. 'pfid' => $product_role['pfid'],
  675. 'nid' => $product_role['nid'],
  676. 'fid' => 'role',
  677. 'description' => $description,
  678. );
  679. $form_state['redirect'] = uc_product_feature_save($data);
  680. $product_role['pfid'] = $data['pfid'];
  681. // Insert or update uc_file_product table.
  682. uc_roles_product_write_record($product_role);
  683. }
  684. /**
  685. * Form builder for role settings.
  686. *
  687. * @ingroup forms
  688. */
  689. function uc_roles_feature_settings($form, &$form_state) {
  690. $default_role_choices = user_roles(TRUE);
  691. unset($default_role_choices[DRUPAL_AUTHENTICATED_RID]);
  692. if (!count($default_role_choices)) {
  693. $form['no_roles'] = array(
  694. '#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'))))),
  695. '#prefix' => '<p>',
  696. '#suffix' => '</p>',
  697. );
  698. return $form;
  699. }
  700. foreach (uc_order_status_list('general') as $status) {
  701. $statuses[$status['id']] = $status['title'];
  702. }
  703. $form['uc_roles_default_role'] = array(
  704. '#type' => 'select',
  705. '#title' => t('Default role'),
  706. '#default_value' => variable_get('uc_roles_default_role', NULL),
  707. '#description' => t('The default role Ubercart grants on specified products.'),
  708. '#options' => _uc_roles_get_choices(),
  709. );
  710. $form['uc_roles_default_role_choices'] = array(
  711. '#type' => 'checkboxes',
  712. '#title' => t('Product roles'),
  713. '#default_value' => variable_get('uc_roles_default_role_choices', array()),
  714. '#multiple' => TRUE,
  715. '#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.'),
  716. '#options' => $default_role_choices,
  717. );
  718. $form['role_lifetime'] = array(
  719. '#type' => 'fieldset',
  720. '#title' => t('Default role expiration'),
  721. );
  722. $form['role_lifetime']['uc_roles_default_end_expiration'] = array(
  723. '#type' => 'select',
  724. '#title' => t('Expiration type'),
  725. '#options' => array(
  726. 'rel' => t('Relative to purchase date'),
  727. 'abs' => t('Fixed date'),
  728. ),
  729. '#default_value' => variable_get('uc_roles_default_end_expiration', 'rel'),
  730. );
  731. $form['role_lifetime']['uc_roles_default_length'] = array(
  732. '#type' => 'textfield',
  733. '#default_value' => (variable_get('uc_roles_default_granularity', 'never') == 'never') ? NULL : variable_get('uc_roles_default_length', NULL),
  734. '#size' => 4,
  735. '#maxlength' => 4,
  736. '#prefix' => '<div class="expiration">',
  737. '#suffix' => '</div>',
  738. '#states' => array(
  739. 'visible' => array('select[name="uc_roles_default_end_expiration"]' => array('value' => 'rel')),
  740. 'invisible' => array('select[name="uc_roles_default_granularity"]' => array('value' => 'never')),
  741. ),
  742. );
  743. $form['role_lifetime']['uc_roles_default_granularity'] = array(
  744. '#type' => 'select',
  745. '#default_value' => variable_get('uc_roles_default_granularity', 'never'),
  746. '#options' => array(
  747. 'never' => t('never'),
  748. 'day' => t('day(s)'),
  749. 'week' => t('week(s)'),
  750. 'month' => t('month(s)'),
  751. 'year' => t('year(s)')
  752. ),
  753. '#description' => t('From the time the role was purchased.'),
  754. '#prefix' => '<div class="expiration">',
  755. '#suffix' => '</div>',
  756. '#states' => array(
  757. 'visible' => array('select[name="uc_roles_default_end_expiration"]' => array('value' => 'rel')),
  758. ),
  759. );
  760. $form['role_lifetime']['absolute'] = array(
  761. '#type' => 'container',
  762. '#states' => array(
  763. 'visible' => array('select[name="uc_roles_default_end_expiration"]' => array('value' => 'abs')),
  764. ),
  765. );
  766. $form['role_lifetime']['absolute']['uc_roles_default_end_time'] = array(
  767. '#type' => 'date',
  768. '#description' => t('Expire the role at the beginning of this day.'),
  769. '#default_value' => variable_get('uc_roles_default_end_time', array(
  770. 'day' => date('j'),
  771. 'month' => date('n'),
  772. 'year' => date('Y'),
  773. )),
  774. );
  775. $form['role_lifetime']['uc_roles_default_by_quantity'] = array(
  776. '#type' => 'checkbox',
  777. '#title' => t('Multiply by quantity'),
  778. '#description' => t('Check if the role duration should be multiplied by the quantity purchased.'),
  779. '#default_value' => variable_get('uc_roles_default_by_quantity', FALSE),
  780. );
  781. $form['reminder']['uc_roles_reminder_length'] = array(
  782. '#type' => 'textfield',
  783. '#title' => t('Time before reminder'),
  784. '#default_value' => (variable_get('uc_roles_reminder_granularity', 'never') == 'never') ? NULL : variable_get('uc_roles_reminder_length', NULL),
  785. '#size' => 4,
  786. '#maxlength' => 4,
  787. '#prefix' => '<div class="expiration">',
  788. '#suffix' => '</div>',
  789. '#states' => array(
  790. 'disabled' => array('select[name="uc_roles_reminder_granularity"]' => array('value' => 'never')),
  791. ),
  792. );
  793. $form['reminder']['uc_roles_reminder_granularity'] = array(
  794. '#type' => 'select',
  795. '#default_value' => variable_get('uc_roles_reminder_granularity', 'never'),
  796. '#options' => array(
  797. 'never' => t('never'),
  798. 'day' => t('day(s)'),
  799. 'week' => t('week(s)'),
  800. 'month' => t('month(s)'),
  801. 'year' => t('year(s)')
  802. ),
  803. '#description' => t('The amount of time before a role expiration takes place that a customer is notified of its expiration.'),
  804. '#prefix' => '<div class="expiration">',
  805. '#suffix' => '</div>',
  806. );
  807. $form['uc_roles_default_show_expiration'] = array(
  808. '#type' => 'checkbox',
  809. '#title' => t('Show expirations on user page'),
  810. '#default_value' => variable_get('uc_roles_default_show_expiration', TRUE),
  811. '#description' => t('If users have any role expirations they will be displayed on their account page.'),
  812. );
  813. return $form;
  814. }
  815. /**
  816. * Gets role name.
  817. *
  818. * @param $rid
  819. * The Drupal role id number.
  820. *
  821. * @return
  822. * A string containing the name of the role, returns FALSE if rid is invalid.
  823. */
  824. function _uc_roles_get_name($rid) {
  825. $roles = user_roles(TRUE);
  826. return (!is_null($roles[$rid])) ? $roles[$rid] : FALSE;
  827. }
  828. /**
  829. * Gets available roles for granting on product purchase.
  830. *
  831. * @param $exclude
  832. * A list of role ids to exclude from the list.
  833. *
  834. * @return
  835. * An assoc array with key = rid and value = role name.
  836. */
  837. function _uc_roles_get_choices($exclude = array()) {
  838. $output = array();
  839. // Get roles from Drupal, excluding Anonymous and Authenticated.
  840. $roles = user_roles(TRUE);
  841. unset($roles[DRUPAL_AUTHENTICATED_RID]);
  842. // User set specific roles that we must use?
  843. $selected = variable_get('uc_roles_default_role_choices', array());
  844. // If there's none, or if none are checked, use all of em.
  845. $default = empty($selected) || array_sum($selected) == 0;
  846. foreach ($roles as $rid => $name) {
  847. if ($default || (!empty($selected[$rid]) && !in_array($rid, $exclude))) {
  848. $output[$rid] = $roles[$rid];
  849. }
  850. }
  851. return $output;
  852. }
  853. /**
  854. * Deletes all role data associated with a given product feature.
  855. *
  856. * @param $pfid
  857. * An Ubercart product feature ID.
  858. */
  859. function uc_roles_feature_delete($pfid) {
  860. db_delete('uc_roles_products')
  861. ->condition('pfid', $pfid)
  862. ->execute();
  863. }
  864. /**
  865. * Deletes an expiration using user id or user id and rid.
  866. *
  867. * This function deletes expirations associated with users and roles. If
  868. * no role ID is passed, the function deletes all role expirations associated
  869. * with the given user. Otherwise, the function only deletes expirations whose
  870. * user and role IDs match. If any roles were actually deleted, the function
  871. * notifies the user. The menu cache is then flushed, as privileges to view
  872. * menu items may have been lost in the process.
  873. *
  874. * @param $account
  875. * A Drupal user object.
  876. * @param $rid
  877. * A Drupal role ID.
  878. * @param $silent
  879. * When set to TRUE will suppress any Drupal messages from this function.
  880. */
  881. function uc_roles_delete($account, $rid = NULL, $silent = FALSE) {
  882. global $user;
  883. $query = db_delete('uc_roles_expirations')
  884. ->condition('uid', $account->uid);
  885. if ($rid) {
  886. $query->condition('rid', $rid);
  887. }
  888. // Echo the deletion only if something was actually deleted.
  889. if ($query->execute() && !$silent) {
  890. if ($user->uid == $account->uid) {
  891. drupal_set_message(t('The expiration of your %role_name role has been deleted.', array('%role_name' => _uc_roles_get_name($rid))));
  892. }
  893. else {
  894. drupal_set_message(t('The expiration of %role_name role for the user !user has been deleted.', array(
  895. '!user' => theme('username', array(
  896. 'account' => $account,
  897. 'name' => check_plain(format_username($account)),
  898. 'link_path' => 'user/' . $account->uid,
  899. )),
  900. '%role_name' => _uc_roles_get_name($rid),
  901. )));
  902. }
  903. }
  904. // Flush visible menu items, since our permissions could've changed.
  905. _uc_roles_flush_menu_cache($account);
  906. }
  907. /**
  908. * Revokes a role on a given user
  909. *
  910. * This function deletes a given role from a user's list of roles, as
  911. * well as removing any expiration data associated with the user/role.
  912. * The function notifies the user of revocation.
  913. *
  914. * @param $account
  915. * A Drupal user object.
  916. * @param $rid
  917. * A Drupal role ID.
  918. * @param $silent
  919. * When set to TRUE will suppress any Drupal messages from this function.
  920. */
  921. function uc_roles_revoke(&$account, $rid, $silent = FALSE) {
  922. global $user;
  923. // Remove this role from the user's list.
  924. $roles_list = $account->roles;
  925. unset($roles_list[$rid]);
  926. $account = user_save($account, array('roles' => $roles_list));
  927. // Remove our record of the expiration.
  928. uc_roles_delete($account, $rid, $silent);
  929. $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => $rid))->fetchField();
  930. if (!$silent) {
  931. if ($user->uid == $account->uid) {
  932. drupal_set_message(t('Your %role role has been revoked.', array('%role' => $role_name)));
  933. }
  934. else {
  935. drupal_set_message(t('!user has had the %role role revoked.', array(
  936. '!user' => theme('username', array(
  937. 'account' => $account,
  938. 'name' => check_plain(format_username($account)),
  939. 'link_path' => 'user/' . $account->uid,
  940. )),
  941. '%role' => $role_name,
  942. )));
  943. }
  944. }
  945. }
  946. /**
  947. * Grants a role to a given user
  948. *
  949. * This function grants a given role to a user's list of roles. If there
  950. * is a previous record of this user/role combination, it is first removed.
  951. * The function then saves the user (if $user_save is TRUE). Next, a check
  952. * to verify the role actually exists, if not, no expiration data is stored.
  953. * The menu cache is flushed, as new menu items may be visible after the
  954. * new role is granted. The function notifies the user of the role grant.
  955. *
  956. * @param $account
  957. * A Drupal user object.
  958. * @param $rid
  959. * A Drupal role ID.
  960. * @param $timestamp
  961. * When this role will expire.
  962. * @param $save_user
  963. * Optimization to prevent unnecessary user saving when calling from
  964. * uc_roles_user_presave().
  965. * @param $silent
  966. * When set to TRUE will suppress any Drupal messages from this function.
  967. */
  968. function uc_roles_grant(&$account, $rid, $timestamp, $save_user = TRUE, $silent = FALSE) {
  969. global $user;
  970. // First, delete any previous record of this user/role association.
  971. uc_roles_delete($account, $rid, $silent);
  972. if ($save_user) {
  973. // Punch the role into the user object.
  974. $roles_list = $account->roles + array($rid => _uc_roles_get_name($rid));
  975. $account = user_save($account, array('roles' => $roles_list));
  976. }
  977. // If the role expires, keep a record.
  978. if (!is_null($timestamp)) {
  979. db_insert('uc_roles_expirations')
  980. ->fields(array(
  981. 'uid' => $account->uid,
  982. 'rid' => $rid,
  983. 'expiration' => $timestamp,
  984. ))
  985. ->execute();
  986. }
  987. // Flush visible menu items, since our permissions could've changed.
  988. _uc_roles_flush_menu_cache($account);
  989. // Display the message if appropriate.
  990. if (!$silent) {
  991. $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => $rid))->fetchField();
  992. if ($user->uid == $account->uid) {
  993. $message = t('You have been granted the %role role.', array('%role' => $role_name));
  994. }
  995. else {
  996. $message = t('!user has been granted the %role role.', array(
  997. '!user' => theme('username', array(
  998. 'account' => $account,
  999. 'name' => check_plain(format_username($account)),
  1000. 'link_path' => 'user/' . $account->uid,
  1001. )),
  1002. '%role' => $role_name,
  1003. ));
  1004. }
  1005. if ($timestamp) {
  1006. $message .= ' ' . t('It will expire on %date', array('%date' => format_date($timestamp, 'short')));
  1007. }
  1008. drupal_set_message($message);
  1009. }
  1010. }
  1011. /**
  1012. * Renews a given role on a user.
  1013. *
  1014. * This function updates expiration time on a role already granted to a
  1015. * user. First the function checks the new expiration. If it never expires,
  1016. * the function deletes the past expiration record and returns, leaving
  1017. * management up to Drupal. Otherwise, the record is updated with the new
  1018. * expiration time, and the user is notified of the change.
  1019. *
  1020. * @param $account
  1021. * A Drupal user object.
  1022. * @param $rid
  1023. * A Drupal role ID.
  1024. * @param $timestamp
  1025. * When this role will expire.
  1026. * @param $silent
  1027. * When set to TRUE will suppress any Drupal messages from this function.
  1028. */
  1029. function uc_roles_renew($account, $rid, $timestamp, $silent = FALSE) {
  1030. global $user;
  1031. // If it doesn't expire, we'll remove our data associated with it.
  1032. // After that, Drupal will take care of it.
  1033. if (is_null($timestamp)) {
  1034. uc_roles_delete($account, $rid);
  1035. return;
  1036. }
  1037. // Update the expiration date and reset the notified flag.
  1038. db_update('uc_roles_expirations')
  1039. ->fields(array(
  1040. 'expiration' => $timestamp,
  1041. 'notified' => NULL,
  1042. ))
  1043. ->condition('uid', $account->uid)
  1044. ->condition('rid', $rid)
  1045. ->execute();
  1046. if (!$silent) {
  1047. $role_name = db_query("SELECT name FROM {role} WHERE rid = :rid", array(':rid' => $rid))->fetchField();
  1048. if ($user->uid == $account->uid) {
  1049. $message = t('Your %role role has been renewed. It will expire on %date.', array('%role' => $role_name, '%date' => format_date($timestamp, 'short')));
  1050. }
  1051. else {
  1052. $message = t("!user's %role role has been renewed. It will expire on %date.", array(
  1053. '!user' => theme('username', array(
  1054. 'account' => $account,
  1055. 'name' => check_plain(format_username($account)),
  1056. 'link_path' => 'user/' . $account->uid,
  1057. )),
  1058. '%role' => $role_name,
  1059. '%date' => format_date($timestamp, 'short'),
  1060. ));
  1061. }
  1062. drupal_set_message($message);
  1063. }
  1064. }
  1065. /**
  1066. * Flushes the menu cache.
  1067. *
  1068. * When roles are gained/lost, menu items might appear/disappear respectively,
  1069. * so we have to ensure the cache is rebuilt with any new values.
  1070. *
  1071. * @param $account
  1072. * A Drupal user object.
  1073. *
  1074. * @see uc_roles_delete()
  1075. * @see uc_roles_grant()
  1076. */
  1077. function _uc_roles_flush_menu_cache($account) {
  1078. cache_clear_all($account->uid . ':', 'cache_menu', TRUE);
  1079. }
  1080. /**
  1081. * Calculates the expiration time using a role_product object.
  1082. *
  1083. * @param $role_product
  1084. * The role product object whose expiration times to calculate.
  1085. * @param $quantity
  1086. * Used to multiply any relative expiration time, if the $role_product
  1087. * says to.
  1088. * @param $time
  1089. * The current time to use as a starting point for relative expiration
  1090. * calculation.
  1091. */
  1092. function _uc_roles_product_get_expiration($role_product, $quantity, $time) {
  1093. // Override the end expiration?
  1094. if ($role_product->end_override) {
  1095. // Absolute times are easy...
  1096. if ($role_product->end_time) {
  1097. return $role_product->end_time;
  1098. }
  1099. // We're gonna have to calculate the relative time from $time.
  1100. $length = $role_product->duration * ($role_product->by_quantity ? $quantity : 1);
  1101. return _uc_roles_get_expiration($length, $role_product->granularity, $time);
  1102. }
  1103. // No override, use the default expiration values.
  1104. else {
  1105. // Relative...
  1106. if (variable_get('uc_roles_default_end_expiration', 'rel') === 'rel') {
  1107. $length = variable_get('uc_roles_default_length', NULL) * ($role_product->by_quantity ? $quantity : 1);
  1108. return _uc_roles_get_expiration($length, variable_get('uc_roles_default_granularity', 'never'), $time);
  1109. }
  1110. // Absolute...
  1111. $end_time = variable_get('uc_roles_default_end_time', NULL);
  1112. if ($end_time) {
  1113. $end_time = mktime(0, 0, 0, $end_time['month'], $end_time['day'], $end_time['year']);
  1114. }
  1115. return $end_time;
  1116. }
  1117. }
  1118. /**
  1119. * Returns an expiration time stamp given a period of time.
  1120. *
  1121. * @param $duration
  1122. * The amount of time until expiration.
  1123. * @param $granularity
  1124. * A string representing the granularity's name (e.g. "day", "month", etc.).
  1125. * @param $start_time
  1126. * (optional) The starting date for when the role will last. Defaults to
  1127. * the current time.
  1128. *
  1129. * @return
  1130. * A UNIX timestamp representing the second that expiration takes place,
  1131. * or NULL if the expiration should never occur.
  1132. */
  1133. function _uc_roles_get_expiration($duration, $granularity, $start_time = NULL) {
  1134. // Never expires?
  1135. if ($granularity == 'never') {
  1136. return NULL;
  1137. }
  1138. $start_time = (!is_null($start_time)) ? $start_time : REQUEST_TIME;
  1139. $operator = ($duration < 0) ? '' : '+';
  1140. return strtotime($operator . $duration . ' ' . $granularity, $start_time);
  1141. }
  1142. /**
  1143. * Implements hook_views_api().
  1144. */
  1145. function uc_roles_views_api() {
  1146. return array(
  1147. 'api' => '2.0',
  1148. 'path' => drupal_get_path('module', 'uc_roles') . '/views',
  1149. );
  1150. }