user.module 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967
  1. <?php
  2. /**
  3. * @file
  4. * Enables the user registration and login system.
  5. */
  6. /**
  7. * Maximum length of username text field.
  8. */
  9. define('USERNAME_MAX_LENGTH', 60);
  10. /**
  11. * Maximum length of user e-mail text field.
  12. */
  13. define('EMAIL_MAX_LENGTH', 254);
  14. /**
  15. * Only administrators can create user accounts.
  16. */
  17. define('USER_REGISTER_ADMINISTRATORS_ONLY', 0);
  18. /**
  19. * Visitors can create their own accounts.
  20. */
  21. define('USER_REGISTER_VISITORS', 1);
  22. /**
  23. * Visitors can create accounts, but they don't become active without
  24. * administrative approval.
  25. */
  26. define('USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL', 2);
  27. /**
  28. * Implement hook_help().
  29. */
  30. function user_help($path, $arg) {
  31. global $user;
  32. switch ($path) {
  33. case 'admin/help#user':
  34. $output = '';
  35. $output .= '<h3>' . t('About') . '</h3>';
  36. $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles (used to classify users) and permissions associated with those roles. For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/documentation/modules/user')) . '</p>';
  37. $output .= '<h3>' . t('Uses') . '</h3>';
  38. $output .= '<dl>';
  39. $output .= '<dt>' . t('Creating and managing users') . '</dt>';
  40. $output .= '<dd>' . t('The User module allows users with the appropriate <a href="@permissions">permissions</a> to create user accounts through the <a href="@people">People administration page</a>, where they can also assign users to one or more roles, and block or delete user accounts. If allowed, users without accounts (anonymous users) can create their own accounts on the <a href="@register">Create new account</a> page.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-user')), '@people' => url('admin/people'), '@register' => url('user/register'))) . '</dd>';
  41. $output .= '<dt>' . t('User roles and permissions') . '</dt>';
  42. $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. By default there are two roles: <em>anonymous user</em> (users that are not logged in) and <em>authenticated user</em> (users that are registered and logged in). Depending on choices you made when you installed Drupal, the installation process may have defined more roles, and you can create additional custom roles on the <a href="@roles">Roles page</a>. After creating roles, you can set permissions for each role on the <a href="@permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing a particular type of content, editing or creating content, administering settings for a particular module, or using a particular function of the site (such as search).', array('@permissions_user' => url('admin/people/permissions'), '@roles' => url('admin/people/permissions/roles'))) . '</dd>';
  43. $output .= '<dt>' . t('Account settings') . '</dt>';
  44. $output .= '<dd>' . t('The <a href="@accounts">Account settings page</a> allows you to manage settings for the displayed name of the anonymous user role, personal contact forms, user registration, and account cancellation. On this page you can also manage settings for account personalization (including signatures and user pictures), and adapt the text for the e-mail messages that are sent automatically during the user registration process.', array('@accounts' => url('admin/config/people/accounts'))) . '</dd>';
  45. $output .= '</dl>';
  46. return $output;
  47. case 'admin/people/create':
  48. return '<p>' . t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") . '</p>';
  49. case 'admin/people/permissions':
  50. return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href="@role">Roles</a> page to create a role). Two important roles to consider are Authenticated Users and Administrators. Any permissions granted to the Authenticated Users role will be given to any user who can log into your site. You can make any role the Administrator role for the site, meaning this will be granted all new permissions automatically. You can do this on the <a href="@settings">User Settings</a> page. You should be careful to ensure that only trusted users are given this access and level of control of your site.', array('@role' => url('admin/people/permissions/roles'), '@settings' => url('admin/config/people/accounts'))) . '</p>';
  51. case 'admin/people/permissions/roles':
  52. $output = '<p>' . t('Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined on the <a href="@permissions">permissions page</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".', array('@permissions' => url('admin/people/permissions'))) . '</p>';
  53. $output .= '<p>' . t('By default, Drupal comes with two user roles:') . '</p>';
  54. $output .= '<ul>';
  55. $output .= '<li>' . t("Anonymous user: this role is used for users that don't have a user account or that are not authenticated.") . '</li>';
  56. $output .= '<li>' . t('Authenticated user: this role is automatically granted to all logged in users.') . '</li>';
  57. $output .= '</ul>';
  58. return $output;
  59. case 'admin/config/people/accounts/fields':
  60. return '<p>' . t('This form lets administrators add, edit, and arrange fields for storing user data.') . '</p>';
  61. case 'admin/config/people/accounts/display':
  62. return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
  63. case 'admin/people/search':
  64. return '<p>' . t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') . '</p>';
  65. }
  66. }
  67. /**
  68. * Invokes a user hook in every module.
  69. *
  70. * We cannot use module_invoke() for this, because the arguments need to
  71. * be passed by reference.
  72. *
  73. * @param $type
  74. * A text string that controls which user hook to invoke. Valid choices are:
  75. * - cancel: Invokes hook_user_cancel().
  76. * - insert: Invokes hook_user_insert().
  77. * - login: Invokes hook_user_login().
  78. * - presave: Invokes hook_user_presave().
  79. * - update: Invokes hook_user_update().
  80. * @param $edit
  81. * An associative array variable containing form values to be passed
  82. * as the first parameter of the hook function.
  83. * @param $account
  84. * The user account object to be passed as the second parameter of the hook
  85. * function.
  86. * @param $category
  87. * The category of user information being acted upon.
  88. */
  89. function user_module_invoke($type, &$edit, $account, $category = NULL) {
  90. foreach (module_implements('user_' . $type) as $module) {
  91. $function = $module . '_user_' . $type;
  92. $function($edit, $account, $category);
  93. }
  94. }
  95. /**
  96. * Implements hook_theme().
  97. */
  98. function user_theme() {
  99. return array(
  100. 'user_picture' => array(
  101. 'variables' => array('account' => NULL),
  102. 'template' => 'user-picture',
  103. ),
  104. 'user_profile' => array(
  105. 'render element' => 'elements',
  106. 'template' => 'user-profile',
  107. 'file' => 'user.pages.inc',
  108. ),
  109. 'user_profile_category' => array(
  110. 'render element' => 'element',
  111. 'template' => 'user-profile-category',
  112. 'file' => 'user.pages.inc',
  113. ),
  114. 'user_profile_item' => array(
  115. 'render element' => 'element',
  116. 'template' => 'user-profile-item',
  117. 'file' => 'user.pages.inc',
  118. ),
  119. 'user_list' => array(
  120. 'variables' => array('users' => NULL, 'title' => NULL),
  121. ),
  122. 'user_admin_permissions' => array(
  123. 'render element' => 'form',
  124. 'file' => 'user.admin.inc',
  125. ),
  126. 'user_admin_roles' => array(
  127. 'render element' => 'form',
  128. 'file' => 'user.admin.inc',
  129. ),
  130. 'user_permission_description' => array(
  131. 'variables' => array('permission_item' => NULL, 'hide' => NULL),
  132. 'file' => 'user.admin.inc',
  133. ),
  134. 'user_signature' => array(
  135. 'variables' => array('signature' => NULL),
  136. ),
  137. );
  138. }
  139. /**
  140. * Implements hook_entity_info().
  141. */
  142. function user_entity_info() {
  143. $return = array(
  144. 'user' => array(
  145. 'label' => t('User'),
  146. 'controller class' => 'UserController',
  147. 'base table' => 'users',
  148. 'uri callback' => 'user_uri',
  149. 'label callback' => 'format_username',
  150. 'fieldable' => TRUE,
  151. // $user->language is only the preferred user language for the user
  152. // interface textual elements. As it is not necessarily related to the
  153. // language assigned to fields, we do not define it as the entity language
  154. // key.
  155. 'entity keys' => array(
  156. 'id' => 'uid',
  157. ),
  158. 'bundles' => array(
  159. 'user' => array(
  160. 'label' => t('User'),
  161. 'admin' => array(
  162. 'path' => 'admin/config/people/accounts',
  163. 'access arguments' => array('administer users'),
  164. ),
  165. ),
  166. ),
  167. 'view modes' => array(
  168. 'full' => array(
  169. 'label' => t('User account'),
  170. 'custom settings' => FALSE,
  171. ),
  172. ),
  173. ),
  174. );
  175. return $return;
  176. }
  177. /**
  178. * Entity URI callback.
  179. */
  180. function user_uri($user) {
  181. return array(
  182. 'path' => 'user/' . $user->uid,
  183. );
  184. }
  185. /**
  186. * Implements hook_field_info_alter().
  187. */
  188. function user_field_info_alter(&$info) {
  189. // Add the 'user_register_form' instance setting to all field types.
  190. foreach ($info as $field_type => &$field_type_info) {
  191. $field_type_info += array('instance_settings' => array());
  192. $field_type_info['instance_settings'] += array(
  193. 'user_register_form' => FALSE,
  194. );
  195. }
  196. }
  197. /**
  198. * Implements hook_field_extra_fields().
  199. */
  200. function user_field_extra_fields() {
  201. $return['user']['user'] = array(
  202. 'form' => array(
  203. 'account' => array(
  204. 'label' => t('User name and password'),
  205. 'description' => t('User module account form elements.'),
  206. 'weight' => -10,
  207. ),
  208. 'timezone' => array(
  209. 'label' => t('Timezone'),
  210. 'description' => t('User module timezone form element.'),
  211. 'weight' => 6,
  212. ),
  213. ),
  214. 'display' => array(
  215. 'summary' => array(
  216. 'label' => t('History'),
  217. 'description' => t('User module history view element.'),
  218. 'weight' => 5,
  219. ),
  220. ),
  221. );
  222. return $return;
  223. }
  224. /**
  225. * Fetches a user object based on an external authentication source.
  226. *
  227. * @param string $authname
  228. * The external authentication username.
  229. *
  230. * @return
  231. * A fully-loaded user object if the user is found or FALSE if not found.
  232. */
  233. function user_external_load($authname) {
  234. $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchField();
  235. if ($uid) {
  236. return user_load($uid);
  237. }
  238. else {
  239. return FALSE;
  240. }
  241. }
  242. /**
  243. * Load multiple users based on certain conditions.
  244. *
  245. * This function should be used whenever you need to load more than one user
  246. * from the database. Users are loaded into memory and will not require
  247. * database access if loaded again during the same page request.
  248. *
  249. * @param $uids
  250. * An array of user IDs.
  251. * @param $conditions
  252. * (deprecated) An associative array of conditions on the {users}
  253. * table, where the keys are the database fields and the values are the
  254. * values those fields must have. Instead, it is preferable to use
  255. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  256. * this function.
  257. * @param $reset
  258. * A boolean indicating that the internal cache should be reset. Use this if
  259. * loading a user object which has been altered during the page request.
  260. *
  261. * @return
  262. * An array of user objects, indexed by uid.
  263. *
  264. * @see entity_load()
  265. * @see user_load()
  266. * @see user_load_by_mail()
  267. * @see user_load_by_name()
  268. * @see EntityFieldQuery
  269. *
  270. * @todo Remove $conditions in Drupal 8.
  271. */
  272. function user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) {
  273. return entity_load('user', $uids, $conditions, $reset);
  274. }
  275. /**
  276. * Controller class for users.
  277. *
  278. * This extends the DrupalDefaultEntityController class, adding required
  279. * special handling for user objects.
  280. */
  281. class UserController extends DrupalDefaultEntityController {
  282. function attachLoad(&$queried_users, $revision_id = FALSE) {
  283. // Build an array of user picture IDs so that these can be fetched later.
  284. $picture_fids = array();
  285. foreach ($queried_users as $key => $record) {
  286. $picture_fids[] = $record->picture;
  287. $queried_users[$key]->data = unserialize($record->data);
  288. $queried_users[$key]->roles = array();
  289. if ($record->uid) {
  290. $queried_users[$record->uid]->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
  291. }
  292. else {
  293. $queried_users[$record->uid]->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
  294. }
  295. }
  296. // Add any additional roles from the database.
  297. $result = db_query('SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids)', array(':uids' => array_keys($queried_users)));
  298. foreach ($result as $record) {
  299. $queried_users[$record->uid]->roles[$record->rid] = $record->name;
  300. }
  301. // Add the full file objects for user pictures if enabled.
  302. if (!empty($picture_fids) && variable_get('user_pictures', 1) == 1) {
  303. $pictures = file_load_multiple($picture_fids);
  304. foreach ($queried_users as $account) {
  305. if (!empty($account->picture) && isset($pictures[$account->picture])) {
  306. $account->picture = $pictures[$account->picture];
  307. }
  308. else {
  309. $account->picture = NULL;
  310. }
  311. }
  312. }
  313. // Call the default attachLoad() method. This will add fields and call
  314. // hook_user_load().
  315. parent::attachLoad($queried_users, $revision_id);
  316. }
  317. }
  318. /**
  319. * Loads a user object.
  320. *
  321. * Drupal has a global $user object, which represents the currently-logged-in
  322. * user. So to avoid confusion and to avoid clobbering the global $user object,
  323. * it is a good idea to assign the result of this function to a different local
  324. * variable, generally $account. If you actually do want to act as the user you
  325. * are loading, it is essential to call drupal_save_session(FALSE); first.
  326. * See
  327. * @link http://drupal.org/node/218104 Safely impersonating another user @endlink
  328. * for more information.
  329. *
  330. * @param $uid
  331. * Integer specifying the user ID to load.
  332. * @param $reset
  333. * TRUE to reset the internal cache and load from the database; FALSE
  334. * (default) to load from the internal cache, if set.
  335. *
  336. * @return
  337. * A fully-loaded user object upon successful user load, or FALSE if the user
  338. * cannot be loaded.
  339. *
  340. * @see user_load_multiple()
  341. */
  342. function user_load($uid, $reset = FALSE) {
  343. $users = user_load_multiple(array($uid), array(), $reset);
  344. return reset($users);
  345. }
  346. /**
  347. * Fetch a user object by email address.
  348. *
  349. * @param $mail
  350. * String with the account's e-mail address.
  351. * @return
  352. * A fully-loaded $user object upon successful user load or FALSE if user
  353. * cannot be loaded.
  354. *
  355. * @see user_load_multiple()
  356. */
  357. function user_load_by_mail($mail) {
  358. $users = user_load_multiple(array(), array('mail' => $mail));
  359. return reset($users);
  360. }
  361. /**
  362. * Fetch a user object by account name.
  363. *
  364. * @param $name
  365. * String with the account's user name.
  366. * @return
  367. * A fully-loaded $user object upon successful user load or FALSE if user
  368. * cannot be loaded.
  369. *
  370. * @see user_load_multiple()
  371. */
  372. function user_load_by_name($name) {
  373. $users = user_load_multiple(array(), array('name' => $name));
  374. return reset($users);
  375. }
  376. /**
  377. * Save changes to a user account or add a new user.
  378. *
  379. * @param $account
  380. * (optional) The user object to modify or add. If you want to modify
  381. * an existing user account, you will need to ensure that (a) $account
  382. * is an object, and (b) you have set $account->uid to the numeric
  383. * user ID of the user account you wish to modify. If you
  384. * want to create a new user account, you can set $account->is_new to
  385. * TRUE or omit the $account->uid field.
  386. * @param $edit
  387. * An array of fields and values to save. For example array('name'
  388. * => 'My name'). Key / value pairs added to the $edit['data'] will be
  389. * serialized and saved in the {users.data} column.
  390. * @param $category
  391. * (optional) The category for storing profile information in.
  392. *
  393. * @return
  394. * A fully-loaded $user object upon successful save or FALSE if the save failed.
  395. *
  396. * @todo D8: Drop $edit and fix user_save() to be consistent with others.
  397. */
  398. function user_save($account, $edit = array(), $category = 'account') {
  399. $transaction = db_transaction();
  400. try {
  401. if (!empty($edit['pass'])) {
  402. // Allow alternate password hashing schemes.
  403. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  404. $edit['pass'] = user_hash_password(trim($edit['pass']));
  405. // Abort if the hashing failed and returned FALSE.
  406. if (!$edit['pass']) {
  407. return FALSE;
  408. }
  409. }
  410. else {
  411. // Avoid overwriting an existing password with a blank password.
  412. unset($edit['pass']);
  413. }
  414. if (isset($edit['mail'])) {
  415. $edit['mail'] = trim($edit['mail']);
  416. }
  417. // Load the stored entity, if any.
  418. if (!empty($account->uid) && !isset($account->original)) {
  419. $account->original = entity_load_unchanged('user', $account->uid);
  420. }
  421. if (empty($account)) {
  422. $account = new stdClass();
  423. }
  424. if (!isset($account->is_new)) {
  425. $account->is_new = empty($account->uid);
  426. }
  427. // Prepopulate $edit['data'] with the current value of $account->data.
  428. // Modules can add to or remove from this array in hook_user_presave().
  429. if (!empty($account->data)) {
  430. $edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
  431. }
  432. // Invoke hook_user_presave() for all modules.
  433. user_module_invoke('presave', $edit, $account, $category);
  434. // Invoke presave operations of Field Attach API and Entity API. Those APIs
  435. // require a fully-fledged and updated entity object. Therefore, we need to
  436. // copy any new property values of $edit into it.
  437. foreach ($edit as $key => $value) {
  438. $account->$key = $value;
  439. }
  440. field_attach_presave('user', $account);
  441. module_invoke_all('entity_presave', $account, 'user');
  442. if (is_object($account) && !$account->is_new) {
  443. // Process picture uploads.
  444. if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
  445. $picture = $account->picture;
  446. // If the picture is a temporary file move it to its final location and
  447. // make it permanent.
  448. if (!$picture->status) {
  449. $info = image_get_info($picture->uri);
  450. $picture_directory = file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
  451. // Prepare the pictures directory.
  452. file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
  453. $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);
  454. // Move the temporary file into the final location.
  455. if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
  456. $picture->status = FILE_STATUS_PERMANENT;
  457. $account->picture = file_save($picture);
  458. file_usage_add($picture, 'user', 'user', $account->uid);
  459. }
  460. }
  461. // Delete the previous picture if it was deleted or replaced.
  462. if (!empty($account->original->picture->fid)) {
  463. file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
  464. file_delete($account->original->picture);
  465. }
  466. }
  467. elseif (isset($edit['picture_delete']) && $edit['picture_delete']) {
  468. file_usage_delete($account->original->picture, 'user', 'user', $account->uid);
  469. file_delete($account->original->picture);
  470. }
  471. $account->picture = empty($account->picture->fid) ? 0 : $account->picture->fid;
  472. // Do not allow 'uid' to be changed.
  473. $account->uid = $account->original->uid;
  474. // Save changes to the user table.
  475. $success = drupal_write_record('users', $account, 'uid');
  476. if ($success === FALSE) {
  477. // The query failed - better to abort the save than risk further
  478. // data loss.
  479. return FALSE;
  480. }
  481. // Reload user roles if provided.
  482. if ($account->roles != $account->original->roles) {
  483. db_delete('users_roles')
  484. ->condition('uid', $account->uid)
  485. ->execute();
  486. $query = db_insert('users_roles')->fields(array('uid', 'rid'));
  487. foreach (array_keys($account->roles) as $rid) {
  488. if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
  489. $query->values(array(
  490. 'uid' => $account->uid,
  491. 'rid' => $rid,
  492. ));
  493. }
  494. }
  495. $query->execute();
  496. }
  497. // Delete a blocked user's sessions to kick them if they are online.
  498. if ($account->original->status != $account->status && $account->status == 0) {
  499. drupal_session_destroy_uid($account->uid);
  500. }
  501. // If the password changed, delete all open sessions and recreate
  502. // the current one.
  503. if ($account->pass != $account->original->pass) {
  504. drupal_session_destroy_uid($account->uid);
  505. if ($account->uid == $GLOBALS['user']->uid) {
  506. drupal_session_regenerate();
  507. }
  508. }
  509. // Save Field data.
  510. field_attach_update('user', $account);
  511. // Send emails after we have the new user object.
  512. if ($account->status != $account->original->status) {
  513. // The user's status is changing; conditionally send notification email.
  514. $op = $account->status == 1 ? 'status_activated' : 'status_blocked';
  515. _user_mail_notify($op, $account);
  516. }
  517. // Update $edit with any interim changes to $account.
  518. foreach ($account as $key => $value) {
  519. if (!property_exists($account->original, $key) || $value !== $account->original->$key) {
  520. $edit[$key] = $value;
  521. }
  522. }
  523. user_module_invoke('update', $edit, $account, $category);
  524. module_invoke_all('entity_update', $account, 'user');
  525. }
  526. else {
  527. // Allow 'uid' to be set by the caller. There is no danger of writing an
  528. // existing user as drupal_write_record will do an INSERT.
  529. if (empty($account->uid)) {
  530. $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
  531. }
  532. // Allow 'created' to be set by the caller.
  533. if (!isset($account->created)) {
  534. $account->created = REQUEST_TIME;
  535. }
  536. $success = drupal_write_record('users', $account);
  537. if ($success === FALSE) {
  538. // On a failed INSERT some other existing user's uid may be returned.
  539. // We must abort to avoid overwriting their account.
  540. return FALSE;
  541. }
  542. // Make sure $account is properly initialized.
  543. $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
  544. field_attach_insert('user', $account);
  545. $edit = (array) $account;
  546. user_module_invoke('insert', $edit, $account, $category);
  547. module_invoke_all('entity_insert', $account, 'user');
  548. // Save user roles.
  549. if (count($account->roles) > 1) {
  550. $query = db_insert('users_roles')->fields(array('uid', 'rid'));
  551. foreach (array_keys($account->roles) as $rid) {
  552. if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
  553. $query->values(array(
  554. 'uid' => $account->uid,
  555. 'rid' => $rid,
  556. ));
  557. }
  558. }
  559. $query->execute();
  560. }
  561. }
  562. // Clear internal properties.
  563. unset($account->is_new);
  564. unset($account->original);
  565. // Clear the static loading cache.
  566. entity_get_controller('user')->resetCache(array($account->uid));
  567. return $account;
  568. }
  569. catch (Exception $e) {
  570. $transaction->rollback();
  571. watchdog_exception('user', $e);
  572. throw $e;
  573. }
  574. }
  575. /**
  576. * Verify the syntax of the given name.
  577. */
  578. function user_validate_name($name) {
  579. if (!$name) {
  580. return t('You must enter a username.');
  581. }
  582. if (substr($name, 0, 1) == ' ') {
  583. return t('The username cannot begin with a space.');
  584. }
  585. if (substr($name, -1) == ' ') {
  586. return t('The username cannot end with a space.');
  587. }
  588. if (strpos($name, ' ') !== FALSE) {
  589. return t('The username cannot contain multiple spaces in a row.');
  590. }
  591. if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
  592. return t('The username contains an illegal character.');
  593. }
  594. if (preg_match('/[\x{80}-\x{A0}' . // Non-printable ISO-8859-1 + NBSP
  595. '\x{AD}' . // Soft-hyphen
  596. '\x{2000}-\x{200F}' . // Various space characters
  597. '\x{2028}-\x{202F}' . // Bidirectional text overrides
  598. '\x{205F}-\x{206F}' . // Various text hinting characters
  599. '\x{FEFF}' . // Byte order mark
  600. '\x{FF01}-\x{FF60}' . // Full-width latin
  601. '\x{FFF9}-\x{FFFD}' . // Replacement characters
  602. '\x{0}-\x{1F}]/u', // NULL byte and control characters
  603. $name)) {
  604. return t('The username contains an illegal character.');
  605. }
  606. if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
  607. return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
  608. }
  609. }
  610. /**
  611. * Validates a user's email address.
  612. *
  613. * Checks that a user's email address exists and follows all standard
  614. * validation rules. Returns error messages when the address is invalid.
  615. *
  616. * @param $mail
  617. * A user's email address.
  618. *
  619. * @return
  620. * If the address is invalid, a human-readable error message is returned.
  621. * If the address is valid, nothing is returned.
  622. */
  623. function user_validate_mail($mail) {
  624. if (!$mail) {
  625. return t('You must enter an e-mail address.');
  626. }
  627. if (!valid_email_address($mail)) {
  628. return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
  629. }
  630. }
  631. /**
  632. * Validates an image uploaded by a user.
  633. *
  634. * @see user_account_form()
  635. */
  636. function user_validate_picture(&$form, &$form_state) {
  637. // If required, validate the uploaded picture.
  638. $validators = array(
  639. 'file_validate_is_image' => array(),
  640. 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
  641. 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  642. );
  643. // Save the file as a temporary file.
  644. $file = file_save_upload('picture_upload', $validators);
  645. if ($file === FALSE) {
  646. form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
  647. }
  648. elseif ($file !== NULL) {
  649. $form_state['values']['picture_upload'] = $file;
  650. }
  651. }
  652. /**
  653. * Generate a random alphanumeric password.
  654. */
  655. function user_password($length = 10) {
  656. // This variable contains the list of allowable characters for the
  657. // password. Note that the number 0 and the letter 'O' have been
  658. // removed to avoid confusion between the two. The same is true
  659. // of 'I', 1, and 'l'.
  660. $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  661. // Zero-based count of characters in the allowable list:
  662. $len = strlen($allowable_characters) - 1;
  663. // Declare the password as a blank string.
  664. $pass = '';
  665. // Loop the number of times specified by $length.
  666. for ($i = 0; $i < $length; $i++) {
  667. // Each iteration, pick a random character from the
  668. // allowable string and append it to the password:
  669. $pass .= $allowable_characters[mt_rand(0, $len)];
  670. }
  671. return $pass;
  672. }
  673. /**
  674. * Determine the permissions for one or more roles.
  675. *
  676. * @param $roles
  677. * An array whose keys are the role IDs of interest, such as $user->roles.
  678. *
  679. * @return
  680. * An array indexed by role ID. Each value is an array whose keys are the
  681. * permission strings for the given role ID.
  682. */
  683. function user_role_permissions($roles = array()) {
  684. $cache = &drupal_static(__FUNCTION__, array());
  685. $role_permissions = $fetch = array();
  686. if ($roles) {
  687. foreach ($roles as $rid => $name) {
  688. if (isset($cache[$rid])) {
  689. $role_permissions[$rid] = $cache[$rid];
  690. }
  691. else {
  692. // Add this rid to the list of those needing to be fetched.
  693. $fetch[] = $rid;
  694. // Prepare in case no permissions are returned.
  695. $cache[$rid] = array();
  696. }
  697. }
  698. if ($fetch) {
  699. // Get from the database permissions that were not in the static variable.
  700. // Only role IDs with at least one permission assigned will return rows.
  701. $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
  702. foreach ($result as $row) {
  703. $cache[$row->rid][$row->permission] = TRUE;
  704. }
  705. foreach ($fetch as $rid) {
  706. // For every rid, we know we at least assigned an empty array.
  707. $role_permissions[$rid] = $cache[$rid];
  708. }
  709. }
  710. }
  711. return $role_permissions;
  712. }
  713. /**
  714. * Determine whether the user has a given privilege.
  715. *
  716. * @param $string
  717. * The permission, such as "administer nodes", being checked for.
  718. * @param $account
  719. * (optional) The account to check, if not given use currently logged in user.
  720. *
  721. * @return
  722. * Boolean TRUE if the current user has the requested permission.
  723. *
  724. * All permission checks in Drupal should go through this function. This
  725. * way, we guarantee consistent behavior, and ensure that the superuser
  726. * can perform all actions.
  727. */
  728. function user_access($string, $account = NULL) {
  729. global $user;
  730. if (!isset($account)) {
  731. $account = $user;
  732. }
  733. // User #1 has all privileges:
  734. if ($account->uid == 1) {
  735. return TRUE;
  736. }
  737. // To reduce the number of SQL queries, we cache the user's permissions
  738. // in a static variable.
  739. // Use the advanced drupal_static() pattern, since this is called very often.
  740. static $drupal_static_fast;
  741. if (!isset($drupal_static_fast)) {
  742. $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  743. }
  744. $perm = &$drupal_static_fast['perm'];
  745. if (!isset($perm[$account->uid])) {
  746. $role_permissions = user_role_permissions($account->roles);
  747. $perms = array();
  748. foreach ($role_permissions as $one_role) {
  749. $perms += $one_role;
  750. }
  751. $perm[$account->uid] = $perms;
  752. }
  753. return isset($perm[$account->uid][$string]);
  754. }
  755. /**
  756. * Checks for usernames blocked by user administration.
  757. *
  758. * @param $name
  759. * A string containing a name of the user.
  760. *
  761. * @return
  762. * Object with property 'name' (the user name), if the user is blocked;
  763. * FALSE if the user is not blocked.
  764. */
  765. function user_is_blocked($name) {
  766. return db_select('users')
  767. ->fields('users', array('name'))
  768. ->condition('name', db_like($name), 'LIKE')
  769. ->condition('status', 0)
  770. ->execute()->fetchObject();
  771. }
  772. /**
  773. * Implements hook_permission().
  774. */
  775. function user_permission() {
  776. return array(
  777. 'administer permissions' => array(
  778. 'title' => t('Administer permissions'),
  779. 'restrict access' => TRUE,
  780. ),
  781. 'administer users' => array(
  782. 'title' => t('Administer users'),
  783. 'restrict access' => TRUE,
  784. ),
  785. 'access user profiles' => array(
  786. 'title' => t('View user profiles'),
  787. ),
  788. 'change own username' => array(
  789. 'title' => t('Change own username'),
  790. ),
  791. 'cancel account' => array(
  792. 'title' => t('Cancel own user account'),
  793. 'description' => t('Note: content may be kept, unpublished, deleted or transferred to the %anonymous-name user depending on the configured <a href="@user-settings-url">user settings</a>.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')), '@user-settings-url' => url('admin/config/people/accounts'))),
  794. ),
  795. 'select account cancellation method' => array(
  796. 'title' => t('Select method for cancelling own account'),
  797. 'restrict access' => TRUE,
  798. ),
  799. );
  800. }
  801. /**
  802. * Implements hook_file_download().
  803. *
  804. * Ensure that user pictures (avatars) are always downloadable.
  805. */
  806. function user_file_download($uri) {
  807. if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
  808. $info = image_get_info($uri);
  809. return array('Content-Type' => $info['mime_type']);
  810. }
  811. }
  812. /**
  813. * Implements hook_file_move().
  814. */
  815. function user_file_move($file, $source) {
  816. // If a user's picture is replaced with a new one, update the record in
  817. // the users table.
  818. if (isset($file->fid) && isset($source->fid) && $file->fid != $source->fid) {
  819. db_update('users')
  820. ->fields(array(
  821. 'picture' => $file->fid,
  822. ))
  823. ->condition('picture', $source->fid)
  824. ->execute();
  825. }
  826. }
  827. /**
  828. * Implements hook_file_delete().
  829. */
  830. function user_file_delete($file) {
  831. // Remove any references to the file.
  832. db_update('users')
  833. ->fields(array('picture' => 0))
  834. ->condition('picture', $file->fid)
  835. ->execute();
  836. }
  837. /**
  838. * Implements hook_search_info().
  839. */
  840. function user_search_info() {
  841. return array(
  842. 'title' => 'Users',
  843. );
  844. }
  845. /**
  846. * Implements hook_search_access().
  847. */
  848. function user_search_access() {
  849. return user_access('access user profiles');
  850. }
  851. /**
  852. * Implements hook_search_execute().
  853. */
  854. function user_search_execute($keys = NULL, $conditions = NULL) {
  855. $find = array();
  856. // Replace wildcards with MySQL/PostgreSQL wildcards.
  857. $keys = preg_replace('!\*+!', '%', $keys);
  858. $query = db_select('users')->extend('PagerDefault');
  859. $query->fields('users', array('uid'));
  860. if (user_access('administer users')) {
  861. // Administrators can also search in the otherwise private email field,
  862. // and they don't need to be restricted to only active users.
  863. $query->fields('users', array('mail'));
  864. $query->condition(db_or()->
  865. condition('name', '%' . db_like($keys) . '%', 'LIKE')->
  866. condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
  867. }
  868. else {
  869. // Regular users can only search via usernames, and we do not show them
  870. // blocked accounts.
  871. $query->condition('name', '%' . db_like($keys) . '%', 'LIKE')
  872. ->condition('status', 1);
  873. }
  874. $uids = $query
  875. ->limit(15)
  876. ->execute()
  877. ->fetchCol();
  878. $accounts = user_load_multiple($uids);
  879. $results = array();
  880. foreach ($accounts as $account) {
  881. $result = array(
  882. 'title' => format_username($account),
  883. 'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
  884. );
  885. if (user_access('administer users')) {
  886. $result['title'] .= ' (' . $account->mail . ')';
  887. }
  888. $results[] = $result;
  889. }
  890. return $results;
  891. }
  892. /**
  893. * Implements hook_element_info().
  894. */
  895. function user_element_info() {
  896. $types['user_profile_category'] = array(
  897. '#theme_wrappers' => array('user_profile_category'),
  898. );
  899. $types['user_profile_item'] = array(
  900. '#theme' => 'user_profile_item',
  901. );
  902. return $types;
  903. }
  904. /**
  905. * Implements hook_user_view().
  906. */
  907. function user_user_view($account) {
  908. $account->content['user_picture'] = array(
  909. '#markup' => theme('user_picture', array('account' => $account)),
  910. '#weight' => -10,
  911. );
  912. if (!isset($account->content['summary'])) {
  913. $account->content['summary'] = array();
  914. }
  915. $account->content['summary'] += array(
  916. '#type' => 'user_profile_category',
  917. '#attributes' => array('class' => array('user-member')),
  918. '#weight' => 5,
  919. '#title' => t('History'),
  920. );
  921. $account->content['summary']['member_for'] = array(
  922. '#type' => 'user_profile_item',
  923. '#title' => t('Member for'),
  924. '#markup' => format_interval(REQUEST_TIME - $account->created),
  925. );
  926. }
  927. /**
  928. * Helper function to add default user account fields to user registration and edit form.
  929. *
  930. * @see user_account_form_validate()
  931. * @see user_validate_current_pass()
  932. * @see user_validate_picture()
  933. * @see user_validate_mail()
  934. */
  935. function user_account_form(&$form, &$form_state) {
  936. global $user;
  937. $account = $form['#user'];
  938. $register = ($form['#user']->uid > 0 ? FALSE : TRUE);
  939. $admin = user_access('administer users');
  940. $form['#validate'][] = 'user_account_form_validate';
  941. // Account information.
  942. $form['account'] = array(
  943. '#type' => 'container',
  944. '#weight' => -10,
  945. );
  946. // Only show name field on registration form or user can change own username.
  947. $form['account']['name'] = array(
  948. '#type' => 'textfield',
  949. '#title' => t('Username'),
  950. '#maxlength' => USERNAME_MAX_LENGTH,
  951. '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
  952. '#required' => TRUE,
  953. '#attributes' => array('class' => array('username')),
  954. '#default_value' => (!$register ? $account->name : ''),
  955. '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
  956. '#weight' => -10,
  957. );
  958. $form['account']['mail'] = array(
  959. '#type' => 'textfield',
  960. '#title' => t('E-mail address'),
  961. '#maxlength' => EMAIL_MAX_LENGTH,
  962. '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
  963. '#required' => TRUE,
  964. '#default_value' => (!$register ? $account->mail : ''),
  965. );
  966. // Display password field only for existing users or when user is allowed to
  967. // assign a password during registration.
  968. if (!$register) {
  969. $form['account']['pass'] = array(
  970. '#type' => 'password_confirm',
  971. '#size' => 25,
  972. '#description' => t('To change the current user password, enter the new password in both fields.'),
  973. );
  974. // To skip the current password field, the user must have logged in via a
  975. // one-time link and have the token in the URL.
  976. $pass_reset = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);
  977. $protected_values = array();
  978. $current_pass_description = '';
  979. // The user may only change their own password without their current
  980. // password if they logged in via a one-time login link.
  981. if (!$pass_reset) {
  982. $protected_values['mail'] = $form['account']['mail']['#title'];
  983. $protected_values['pass'] = t('Password');
  984. $request_new = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  985. $current_pass_description = t('Enter your current password to change the %mail or %pass. !request_new.', array('%mail' => $protected_values['mail'], '%pass' => $protected_values['pass'], '!request_new' => $request_new));
  986. }
  987. // The user must enter their current password to change to a new one.
  988. if ($user->uid == $account->uid) {
  989. $form['account']['current_pass_required_values'] = array(
  990. '#type' => 'value',
  991. '#value' => $protected_values,
  992. );
  993. $form['account']['current_pass'] = array(
  994. '#type' => 'password',
  995. '#title' => t('Current password'),
  996. '#size' => 25,
  997. '#access' => !empty($protected_values),
  998. '#description' => $current_pass_description,
  999. '#weight' => -5,
  1000. '#attributes' => array('autocomplete' => 'off'),
  1001. );
  1002. $form['#validate'][] = 'user_validate_current_pass';
  1003. }
  1004. }
  1005. elseif (!variable_get('user_email_verification', TRUE) || $admin) {
  1006. $form['account']['pass'] = array(
  1007. '#type' => 'password_confirm',
  1008. '#size' => 25,
  1009. '#description' => t('Provide a password for the new account in both fields.'),
  1010. '#required' => TRUE,
  1011. );
  1012. }
  1013. if ($admin) {
  1014. $status = isset($account->status) ? $account->status : 1;
  1015. }
  1016. else {
  1017. $status = $register ? variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS : $account->status;
  1018. }
  1019. $form['account']['status'] = array(
  1020. '#type' => 'radios',
  1021. '#title' => t('Status'),
  1022. '#default_value' => $status,
  1023. '#options' => array(t('Blocked'), t('Active')),
  1024. '#access' => $admin,
  1025. );
  1026. $roles = array_map('check_plain', user_roles(TRUE));
  1027. // The disabled checkbox subelement for the 'authenticated user' role
  1028. // must be generated separately and added to the checkboxes element,
  1029. // because of a limitation in Form API not supporting a single disabled
  1030. // checkbox within a set of checkboxes.
  1031. // @todo This should be solved more elegantly. See issue #119038.
  1032. $checkbox_authenticated = array(
  1033. '#type' => 'checkbox',
  1034. '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
  1035. '#default_value' => TRUE,
  1036. '#disabled' => TRUE,
  1037. );
  1038. unset($roles[DRUPAL_AUTHENTICATED_RID]);
  1039. $form['account']['roles'] = array(
  1040. '#type' => 'checkboxes',
  1041. '#title' => t('Roles'),
  1042. '#default_value' => (!$register && isset($account->roles) ? array_keys($account->roles) : array()),
  1043. '#options' => $roles,
  1044. '#access' => $roles && user_access('administer permissions'),
  1045. DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
  1046. );
  1047. $form['account']['notify'] = array(
  1048. '#type' => 'checkbox',
  1049. '#title' => t('Notify user of new account'),
  1050. '#access' => $register && $admin,
  1051. );
  1052. // Signature.
  1053. $form['signature_settings'] = array(
  1054. '#type' => 'fieldset',
  1055. '#title' => t('Signature settings'),
  1056. '#weight' => 1,
  1057. '#access' => (!$register && variable_get('user_signatures', 0)),
  1058. );
  1059. $form['signature_settings']['signature'] = array(
  1060. '#type' => 'text_format',
  1061. '#title' => t('Signature'),
  1062. '#default_value' => isset($account->signature) ? $account->signature : '',
  1063. '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
  1064. '#format' => isset($account->signature_format) ? $account->signature_format : NULL,
  1065. );
  1066. // Picture/avatar.
  1067. $form['picture'] = array(
  1068. '#type' => 'fieldset',
  1069. '#title' => t('Picture'),
  1070. '#weight' => 1,
  1071. '#access' => (!$register && variable_get('user_pictures', 0)),
  1072. );
  1073. $form['picture']['picture'] = array(
  1074. '#type' => 'value',
  1075. '#value' => isset($account->picture) ? $account->picture : NULL,
  1076. );
  1077. $form['picture']['picture_current'] = array(
  1078. '#markup' => theme('user_picture', array('account' => $account)),
  1079. );
  1080. $form['picture']['picture_delete'] = array(
  1081. '#type' => 'checkbox',
  1082. '#title' => t('Delete picture'),
  1083. '#access' => !empty($account->picture->fid),
  1084. '#description' => t('Check this box to delete your current picture.'),
  1085. );
  1086. $form['picture']['picture_upload'] = array(
  1087. '#type' => 'file',
  1088. '#title' => t('Upload picture'),
  1089. '#size' => 48,
  1090. '#description' => t('Your virtual face or picture. Pictures larger than @dimensions pixels will be scaled down.', array('@dimensions' => variable_get('user_picture_dimensions', '85x85'))) . ' ' . filter_xss_admin(variable_get('user_picture_guidelines', '')),
  1091. );
  1092. $form['#validate'][] = 'user_validate_picture';
  1093. }
  1094. /**
  1095. * Form validation handler for the current password on the user_account_form().
  1096. *
  1097. * @see user_account_form()
  1098. */
  1099. function user_validate_current_pass(&$form, &$form_state) {
  1100. $account = $form['#user'];
  1101. foreach ($form_state['values']['current_pass_required_values'] as $key => $name) {
  1102. // This validation only works for required textfields (like mail) or
  1103. // form values like password_confirm that have their own validation
  1104. // that prevent them from being empty if they are changed.
  1105. if ((strlen(trim($form_state['values'][$key])) > 0) && ($form_state['values'][$key] != $account->$key)) {
  1106. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  1107. $current_pass_failed = empty($form_state['values']['current_pass']) || !user_check_password($form_state['values']['current_pass'], $account);
  1108. if ($current_pass_failed) {
  1109. form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
  1110. form_set_error($key);
  1111. }
  1112. // We only need to check the password once.
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. /**
  1118. * Form validation handler for user_account_form().
  1119. *
  1120. * @see user_account_form()
  1121. */
  1122. function user_account_form_validate($form, &$form_state) {
  1123. if ($form['#user_category'] == 'account' || $form['#user_category'] == 'register') {
  1124. $account = $form['#user'];
  1125. // Validate new or changing username.
  1126. if (isset($form_state['values']['name'])) {
  1127. if ($error = user_validate_name($form_state['values']['name'])) {
  1128. form_set_error('name', $error);
  1129. }
  1130. elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
  1131. form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
  1132. }
  1133. }
  1134. // Trim whitespace from mail, to prevent confusing 'e-mail not valid'
  1135. // warnings often caused by cutting and pasting.
  1136. $mail = trim($form_state['values']['mail']);
  1137. form_set_value($form['account']['mail'], $mail, $form_state);
  1138. // Validate the e-mail address, and check if it is taken by an existing user.
  1139. if ($error = user_validate_mail($form_state['values']['mail'])) {
  1140. form_set_error('mail', $error);
  1141. }
  1142. elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('mail', db_like($form_state['values']['mail']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
  1143. // Format error message dependent on whether the user is logged in or not.
  1144. if ($GLOBALS['user']->uid) {
  1145. form_set_error('mail', t('The e-mail address %email is already taken.', array('%email' => $form_state['values']['mail'])));
  1146. }
  1147. else {
  1148. form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $form_state['values']['mail'], '@password' => url('user/password'))));
  1149. }
  1150. }
  1151. // Make sure the signature isn't longer than the size of the database field.
  1152. // Signatures are disabled by default, so make sure it exists first.
  1153. if (isset($form_state['values']['signature'])) {
  1154. // Move text format for user signature into 'signature_format'.
  1155. $form_state['values']['signature_format'] = $form_state['values']['signature']['format'];
  1156. // Move text value for user signature into 'signature'.
  1157. $form_state['values']['signature'] = $form_state['values']['signature']['value'];
  1158. $user_schema = drupal_get_schema('users');
  1159. if (drupal_strlen($form_state['values']['signature']) > $user_schema['fields']['signature']['length']) {
  1160. form_set_error('signature', t('The signature is too long: it must be %max characters or less.', array('%max' => $user_schema['fields']['signature']['length'])));
  1161. }
  1162. }
  1163. }
  1164. }
  1165. /**
  1166. * Implements hook_user_presave().
  1167. */
  1168. function user_user_presave(&$edit, $account, $category) {
  1169. if ($category == 'account' || $category == 'register') {
  1170. if (!empty($edit['picture_upload'])) {
  1171. $edit['picture'] = $edit['picture_upload'];
  1172. }
  1173. // Delete picture if requested, and if no replacement picture was given.
  1174. elseif (!empty($edit['picture_delete'])) {
  1175. $edit['picture'] = NULL;
  1176. }
  1177. // Prepare user roles.
  1178. if (isset($edit['roles'])) {
  1179. $edit['roles'] = array_filter($edit['roles']);
  1180. }
  1181. }
  1182. // Move account cancellation information into $user->data.
  1183. foreach (array('user_cancel_method', 'user_cancel_notify') as $key) {
  1184. if (isset($edit[$key])) {
  1185. $edit['data'][$key] = $edit[$key];
  1186. }
  1187. }
  1188. }
  1189. /**
  1190. * Implements hook_user_categories().
  1191. */
  1192. function user_user_categories() {
  1193. return array(array(
  1194. 'name' => 'account',
  1195. 'title' => t('Account settings'),
  1196. 'weight' => 1,
  1197. ));
  1198. }
  1199. function user_login_block($form) {
  1200. $form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));
  1201. $form['#id'] = 'user-login-form';
  1202. $form['#validate'] = user_login_default_validators();
  1203. $form['#submit'][] = 'user_login_submit';
  1204. $form['name'] = array('#type' => 'textfield',
  1205. '#title' => t('Username'),
  1206. '#maxlength' => USERNAME_MAX_LENGTH,
  1207. '#size' => 15,
  1208. '#required' => TRUE,
  1209. );
  1210. $form['pass'] = array('#type' => 'password',
  1211. '#title' => t('Password'),
  1212. '#size' => 15,
  1213. '#required' => TRUE,
  1214. );
  1215. $form['actions'] = array('#type' => 'actions');
  1216. $form['actions']['submit'] = array('#type' => 'submit',
  1217. '#value' => t('Log in'),
  1218. );
  1219. $items = array();
  1220. if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
  1221. $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  1222. }
  1223. $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  1224. $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
  1225. return $form;
  1226. }
  1227. /**
  1228. * Implements hook_block_info().
  1229. */
  1230. function user_block_info() {
  1231. global $user;
  1232. $blocks['login']['info'] = t('User login');
  1233. // Not worth caching.
  1234. $blocks['login']['cache'] = DRUPAL_NO_CACHE;
  1235. $blocks['new']['info'] = t('Who\'s new');
  1236. $blocks['new']['properties']['administrative'] = TRUE;
  1237. // Too dynamic to cache.
  1238. $blocks['online']['info'] = t('Who\'s online');
  1239. $blocks['online']['cache'] = DRUPAL_NO_CACHE;
  1240. $blocks['online']['properties']['administrative'] = TRUE;
  1241. return $blocks;
  1242. }
  1243. /**
  1244. * Implements hook_block_configure().
  1245. */
  1246. function user_block_configure($delta = '') {
  1247. global $user;
  1248. switch ($delta) {
  1249. case 'new':
  1250. $form['user_block_whois_new_count'] = array(
  1251. '#type' => 'select',
  1252. '#title' => t('Number of users to display'),
  1253. '#default_value' => variable_get('user_block_whois_new_count', 5),
  1254. '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
  1255. );
  1256. return $form;
  1257. case 'online':
  1258. $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
  1259. $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
  1260. $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
  1261. return $form;
  1262. }
  1263. }
  1264. /**
  1265. * Implements hook_block_save().
  1266. */
  1267. function user_block_save($delta = '', $edit = array()) {
  1268. global $user;
  1269. switch ($delta) {
  1270. case 'new':
  1271. variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
  1272. break;
  1273. case 'online':
  1274. variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
  1275. variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
  1276. break;
  1277. }
  1278. }
  1279. /**
  1280. * Implements hook_block_view().
  1281. */
  1282. function user_block_view($delta = '') {
  1283. global $user;
  1284. $block = array();
  1285. switch ($delta) {
  1286. case 'login':
  1287. // For usability's sake, avoid showing two login forms on one page.
  1288. if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
  1289. $block['subject'] = t('User login');
  1290. $block['content'] = drupal_get_form('user_login_block');
  1291. }
  1292. return $block;
  1293. case 'new':
  1294. if (user_access('access content')) {
  1295. // Retrieve a list of new users who have subsequently accessed the site successfully.
  1296. $items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5))->fetchAll();
  1297. $output = theme('user_list', array('users' => $items));
  1298. $block['subject'] = t('Who\'s new');
  1299. $block['content'] = $output;
  1300. }
  1301. return $block;
  1302. case 'online':
  1303. if (user_access('access content')) {
  1304. // Count users active within the defined period.
  1305. $interval = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
  1306. // Perform database queries to gather online user lists. We use s.timestamp
  1307. // rather than u.access because it is much faster.
  1308. $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();
  1309. $output = '<p>' . format_plural($authenticated_count, 'There is currently 1 user online.', 'There are currently @count users online.') . '</p>';
  1310. // Display a list of currently online users.
  1311. $max_users = variable_get('user_block_max_list_count', 10);
  1312. if ($authenticated_count && $max_users) {
  1313. $items = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS max_timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= :interval AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY max_timestamp DESC', 0, $max_users, array(':interval' => $interval))->fetchAll();
  1314. $output .= theme('user_list', array('users' => $items));
  1315. }
  1316. $block['subject'] = t('Who\'s online');
  1317. $block['content'] = $output;
  1318. }
  1319. return $block;
  1320. }
  1321. }
  1322. /**
  1323. * Process variables for user-picture.tpl.php.
  1324. *
  1325. * The $variables array contains the following arguments:
  1326. * - $account: A user, node or comment object with 'name', 'uid' and 'picture'
  1327. * fields.
  1328. *
  1329. * @see user-picture.tpl.php
  1330. */
  1331. function template_preprocess_user_picture(&$variables) {
  1332. $variables['user_picture'] = '';
  1333. if (variable_get('user_pictures', 0)) {
  1334. $account = $variables['account'];
  1335. if (!empty($account->picture)) {
  1336. // @TODO: Ideally this function would only be passed file objects, but
  1337. // since there's a lot of legacy code that JOINs the {users} table to
  1338. // {node} or {comments} and passes the results into this function if we
  1339. // a numeric value in the picture field we'll assume it's a file id
  1340. // and load it for them. Once we've got user_load_multiple() and
  1341. // comment_load_multiple() functions the user module will be able to load
  1342. // the picture files in mass during the object's load process.
  1343. if (is_numeric($account->picture)) {
  1344. $account->picture = file_load($account->picture);
  1345. }
  1346. if (!empty($account->picture->uri)) {
  1347. $filepath = $account->picture->uri;
  1348. }
  1349. }
  1350. elseif (variable_get('user_picture_default', '')) {
  1351. $filepath = variable_get('user_picture_default', '');
  1352. }
  1353. if (isset($filepath)) {
  1354. $alt = t("@user's picture", array('@user' => format_username($account)));
  1355. // If the image does not have a valid Drupal scheme (for eg. HTTP),
  1356. // don't load image styles.
  1357. if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
  1358. $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  1359. }
  1360. else {
  1361. $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
  1362. }
  1363. if (!empty($account->uid) && user_access('access user profiles')) {
  1364. $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
  1365. $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
  1366. }
  1367. }
  1368. }
  1369. }
  1370. /**
  1371. * Returns HTML for a list of users.
  1372. *
  1373. * @param $variables
  1374. * An associative array containing:
  1375. * - users: An array with user objects. Should contain at least the name and
  1376. * uid.
  1377. * - title: (optional) Title to pass on to theme_item_list().
  1378. *
  1379. * @ingroup themeable
  1380. */
  1381. function theme_user_list($variables) {
  1382. $users = $variables['users'];
  1383. $title = $variables['title'];
  1384. $items = array();
  1385. if (!empty($users)) {
  1386. foreach ($users as $user) {
  1387. $items[] = theme('username', array('account' => $user));
  1388. }
  1389. }
  1390. return theme('item_list', array('items' => $items, 'title' => $title));
  1391. }
  1392. function user_is_anonymous() {
  1393. // Menu administrators can see items for anonymous when administering.
  1394. return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
  1395. }
  1396. function user_is_logged_in() {
  1397. return (bool) $GLOBALS['user']->uid;
  1398. }
  1399. function user_register_access() {
  1400. return user_is_anonymous() && variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
  1401. }
  1402. /**
  1403. * User view access callback.
  1404. *
  1405. * @param $account
  1406. * Can either be a full user object or a $uid.
  1407. */
  1408. function user_view_access($account) {
  1409. $uid = is_object($account) ? $account->uid : (int) $account;
  1410. // Never allow access to view the anonymous user account.
  1411. if ($uid) {
  1412. // Admins can view all, users can view own profiles at all times.
  1413. if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
  1414. return TRUE;
  1415. }
  1416. elseif (user_access('access user profiles')) {
  1417. // At this point, load the complete account object.
  1418. if (!is_object($account)) {
  1419. $account = user_load($uid);
  1420. }
  1421. return (is_object($account) && $account->status);
  1422. }
  1423. }
  1424. return FALSE;
  1425. }
  1426. /**
  1427. * Access callback for user account editing.
  1428. */
  1429. function user_edit_access($account) {
  1430. return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
  1431. }
  1432. /**
  1433. * Menu access callback; limit access to account cancellation pages.
  1434. *
  1435. * Limit access to users with the 'cancel account' permission or administrative
  1436. * users, and prevent the anonymous user from cancelling the account.
  1437. */
  1438. function user_cancel_access($account) {
  1439. return ((($GLOBALS['user']->uid == $account->uid) && user_access('cancel account')) || user_access('administer users')) && $account->uid > 0;
  1440. }
  1441. /**
  1442. * Implements hook_menu().
  1443. */
  1444. function user_menu() {
  1445. $items['user/autocomplete'] = array(
  1446. 'title' => 'User autocomplete',
  1447. 'page callback' => 'user_autocomplete',
  1448. 'access callback' => 'user_access',
  1449. 'access arguments' => array('access user profiles'),
  1450. 'type' => MENU_CALLBACK,
  1451. 'file' => 'user.pages.inc',
  1452. );
  1453. // Registration and login pages.
  1454. $items['user'] = array(
  1455. 'title' => 'User account',
  1456. 'title callback' => 'user_menu_title',
  1457. 'page callback' => 'user_page',
  1458. 'access callback' => TRUE,
  1459. 'file' => 'user.pages.inc',
  1460. 'weight' => -10,
  1461. 'menu_name' => 'user-menu',
  1462. );
  1463. $items['user/login'] = array(
  1464. 'title' => 'Log in',
  1465. 'access callback' => 'user_is_anonymous',
  1466. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1467. );
  1468. $items['user/register'] = array(
  1469. 'title' => 'Create new account',
  1470. 'page callback' => 'drupal_get_form',
  1471. 'page arguments' => array('user_register_form'),
  1472. 'access callback' => 'user_register_access',
  1473. 'type' => MENU_LOCAL_TASK,
  1474. );
  1475. $items['user/password'] = array(
  1476. 'title' => 'Request new password',
  1477. 'page callback' => 'drupal_get_form',
  1478. 'page arguments' => array('user_pass'),
  1479. 'access callback' => TRUE,
  1480. 'type' => MENU_LOCAL_TASK,
  1481. 'file' => 'user.pages.inc',
  1482. );
  1483. $items['user/reset/%/%/%'] = array(
  1484. 'title' => 'Reset password',
  1485. 'page callback' => 'drupal_get_form',
  1486. 'page arguments' => array('user_pass_reset', 2, 3, 4),
  1487. 'access callback' => TRUE,
  1488. 'type' => MENU_CALLBACK,
  1489. 'file' => 'user.pages.inc',
  1490. );
  1491. $items['user/logout'] = array(
  1492. 'title' => 'Log out',
  1493. 'access callback' => 'user_is_logged_in',
  1494. 'page callback' => 'user_logout',
  1495. 'weight' => 10,
  1496. 'menu_name' => 'user-menu',
  1497. 'file' => 'user.pages.inc',
  1498. );
  1499. // User listing pages.
  1500. $items['admin/people'] = array(
  1501. 'title' => 'People',
  1502. 'description' => 'Manage user accounts, roles, and permissions.',
  1503. 'page callback' => 'user_admin',
  1504. 'page arguments' => array('list'),
  1505. 'access arguments' => array('administer users'),
  1506. 'position' => 'left',
  1507. 'weight' => -4,
  1508. 'file' => 'user.admin.inc',
  1509. );
  1510. $items['admin/people/people'] = array(
  1511. 'title' => 'List',
  1512. 'description' => 'Find and manage people interacting with your site.',
  1513. 'access arguments' => array('administer users'),
  1514. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1515. 'weight' => -10,
  1516. 'file' => 'user.admin.inc',
  1517. );
  1518. // Permissions and role forms.
  1519. $items['admin/people/permissions'] = array(
  1520. 'title' => 'Permissions',
  1521. 'description' => 'Determine access to features by selecting permissions for roles.',
  1522. 'page callback' => 'drupal_get_form',
  1523. 'page arguments' => array('user_admin_permissions'),
  1524. 'access arguments' => array('administer permissions'),
  1525. 'file' => 'user.admin.inc',
  1526. 'type' => MENU_LOCAL_TASK,
  1527. );
  1528. $items['admin/people/permissions/list'] = array(
  1529. 'title' => 'Permissions',
  1530. 'description' => 'Determine access to features by selecting permissions for roles.',
  1531. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1532. 'weight' => -8,
  1533. );
  1534. $items['admin/people/permissions/roles'] = array(
  1535. 'title' => 'Roles',
  1536. 'description' => 'List, edit, or add user roles.',
  1537. 'page callback' => 'drupal_get_form',
  1538. 'page arguments' => array('user_admin_roles'),
  1539. 'access arguments' => array('administer permissions'),
  1540. 'file' => 'user.admin.inc',
  1541. 'type' => MENU_LOCAL_TASK,
  1542. 'weight' => -5,
  1543. );
  1544. $items['admin/people/permissions/roles/edit/%user_role'] = array(
  1545. 'title' => 'Edit role',
  1546. 'page arguments' => array('user_admin_role', 5),
  1547. 'access callback' => 'user_role_edit_access',
  1548. 'access arguments' => array(5),
  1549. );
  1550. $items['admin/people/permissions/roles/delete/%user_role'] = array(
  1551. 'title' => 'Delete role',
  1552. 'page callback' => 'drupal_get_form',
  1553. 'page arguments' => array('user_admin_role_delete_confirm', 5),
  1554. 'access callback' => 'user_role_edit_access',
  1555. 'access arguments' => array(5),
  1556. 'file' => 'user.admin.inc',
  1557. );
  1558. $items['admin/people/create'] = array(
  1559. 'title' => 'Add user',
  1560. 'page arguments' => array('create'),
  1561. 'access arguments' => array('administer users'),
  1562. 'type' => MENU_LOCAL_ACTION,
  1563. );
  1564. // Administration pages.
  1565. $items['admin/config/people'] = array(
  1566. 'title' => 'People',
  1567. 'description' => 'Configure user accounts.',
  1568. 'position' => 'left',
  1569. 'weight' => -20,
  1570. 'page callback' => 'system_admin_menu_block_page',
  1571. 'access arguments' => array('access administration pages'),
  1572. 'file' => 'system.admin.inc',
  1573. 'file path' => drupal_get_path('module', 'system'),
  1574. );
  1575. $items['admin/config/people/accounts'] = array(
  1576. 'title' => 'Account settings',
  1577. 'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.',
  1578. 'page callback' => 'drupal_get_form',
  1579. 'page arguments' => array('user_admin_settings'),
  1580. 'access arguments' => array('administer users'),
  1581. 'file' => 'user.admin.inc',
  1582. 'weight' => -10,
  1583. );
  1584. $items['admin/config/people/accounts/settings'] = array(
  1585. 'title' => 'Settings',
  1586. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1587. 'weight' => -10,
  1588. );
  1589. $items['user/%user'] = array(
  1590. 'title' => 'My account',
  1591. 'title callback' => 'user_page_title',
  1592. 'title arguments' => array(1),
  1593. 'page callback' => 'user_view_page',
  1594. 'page arguments' => array(1),
  1595. 'access callback' => 'user_view_access',
  1596. 'access arguments' => array(1),
  1597. // By assigning a different menu name, this item (and all registered child
  1598. // paths) are no longer considered as children of 'user'. When accessing the
  1599. // user account pages, the preferred menu link that is used to build the
  1600. // active trail (breadcrumb) will be found in this menu (unless there is
  1601. // more specific link), so the link to 'user' will not be in the breadcrumb.
  1602. 'menu_name' => 'navigation',
  1603. );
  1604. $items['user/%user/view'] = array(
  1605. 'title' => 'View',
  1606. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1607. 'weight' => -10,
  1608. );
  1609. $items['user/%user/cancel'] = array(
  1610. 'title' => 'Cancel account',
  1611. 'page callback' => 'drupal_get_form',
  1612. 'page arguments' => array('user_cancel_confirm_form', 1),
  1613. 'access callback' => 'user_cancel_access',
  1614. 'access arguments' => array(1),
  1615. 'file' => 'user.pages.inc',
  1616. );
  1617. $items['user/%user/cancel/confirm/%/%'] = array(
  1618. 'title' => 'Confirm account cancellation',
  1619. 'page callback' => 'user_cancel_confirm',
  1620. 'page arguments' => array(1, 4, 5),
  1621. 'access callback' => 'user_cancel_access',
  1622. 'access arguments' => array(1),
  1623. 'file' => 'user.pages.inc',
  1624. );
  1625. $items['user/%user/edit'] = array(
  1626. 'title' => 'Edit',
  1627. 'page callback' => 'drupal_get_form',
  1628. 'page arguments' => array('user_profile_form', 1),
  1629. 'access callback' => 'user_edit_access',
  1630. 'access arguments' => array(1),
  1631. 'type' => MENU_LOCAL_TASK,
  1632. 'file' => 'user.pages.inc',
  1633. );
  1634. $items['user/%user_category/edit/account'] = array(
  1635. 'title' => 'Account',
  1636. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1637. 'load arguments' => array('%map', '%index'),
  1638. );
  1639. if (($categories = _user_categories()) && (count($categories) > 1)) {
  1640. foreach ($categories as $key => $category) {
  1641. // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
  1642. if ($category['name'] != 'account') {
  1643. $items['user/%user_category/edit/' . $category['name']] = array(
  1644. 'title callback' => 'check_plain',
  1645. 'title arguments' => array($category['title']),
  1646. 'page callback' => 'drupal_get_form',
  1647. 'page arguments' => array('user_profile_form', 1, 3),
  1648. 'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access',
  1649. 'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1),
  1650. 'type' => MENU_LOCAL_TASK,
  1651. 'weight' => $category['weight'],
  1652. 'load arguments' => array('%map', '%index'),
  1653. 'tab_parent' => 'user/%/edit',
  1654. 'file' => 'user.pages.inc',
  1655. );
  1656. }
  1657. }
  1658. }
  1659. return $items;
  1660. }
  1661. /**
  1662. * Implements hook_menu_site_status_alter().
  1663. */
  1664. function user_menu_site_status_alter(&$menu_site_status, $path) {
  1665. if ($menu_site_status == MENU_SITE_OFFLINE) {
  1666. // If the site is offline, log out unprivileged users.
  1667. if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
  1668. module_load_include('pages.inc', 'user', 'user');
  1669. user_logout();
  1670. }
  1671. if (user_is_anonymous()) {
  1672. switch ($path) {
  1673. case 'user':
  1674. // Forward anonymous user to login page.
  1675. drupal_goto('user/login');
  1676. case 'user/login':
  1677. case 'user/password':
  1678. // Disable offline mode.
  1679. $menu_site_status = MENU_SITE_ONLINE;
  1680. break;
  1681. default:
  1682. if (strpos($path, 'user/reset/') === 0) {
  1683. // Disable offline mode.
  1684. $menu_site_status = MENU_SITE_ONLINE;
  1685. }
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. if (user_is_logged_in()) {
  1691. if ($path == 'user/login') {
  1692. // If user is logged in, redirect to 'user' instead of giving 403.
  1693. drupal_goto('user');
  1694. }
  1695. if ($path == 'user/register') {
  1696. // Authenticated user should be redirected to user edit page.
  1697. drupal_goto('user/' . $GLOBALS['user']->uid . '/edit');
  1698. }
  1699. }
  1700. }
  1701. /**
  1702. * Implements hook_menu_link_alter().
  1703. */
  1704. function user_menu_link_alter(&$link) {
  1705. // The path 'user' must be accessible for anonymous users, but only visible
  1706. // for authenticated users. Authenticated users should see "My account", but
  1707. // anonymous users should not see it at all. Therefore, invoke
  1708. // user_translated_menu_link_alter() to conditionally hide the link.
  1709. if ($link['link_path'] == 'user' && $link['module'] == 'system') {
  1710. $link['options']['alter'] = TRUE;
  1711. }
  1712. // Force the Logout link to appear on the top-level of 'user-menu' menu by
  1713. // default (i.e., unless it has been customized).
  1714. if ($link['link_path'] == 'user/logout' && $link['module'] == 'system' && empty($link['customized'])) {
  1715. $link['plid'] = 0;
  1716. }
  1717. }
  1718. /**
  1719. * Implements hook_translated_menu_link_alter().
  1720. */
  1721. function user_translated_menu_link_alter(&$link) {
  1722. // Hide the "User account" link for anonymous users.
  1723. if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->uid) {
  1724. $link['hidden'] = 1;
  1725. }
  1726. }
  1727. /**
  1728. * Implements hook_admin_paths().
  1729. */
  1730. function user_admin_paths() {
  1731. $paths = array(
  1732. 'user/*/cancel' => TRUE,
  1733. 'user/*/edit' => TRUE,
  1734. 'user/*/edit/*' => TRUE,
  1735. );
  1736. return $paths;
  1737. }
  1738. /**
  1739. * Returns $arg or the user ID of the current user if $arg is '%' or empty.
  1740. *
  1741. * Deprecated. Use %user_uid_optional instead.
  1742. *
  1743. * @todo D8: Remove.
  1744. */
  1745. function user_uid_only_optional_to_arg($arg) {
  1746. return user_uid_optional_to_arg($arg);
  1747. }
  1748. /**
  1749. * Load either a specified or the current user account.
  1750. *
  1751. * @param $uid
  1752. * An optional user ID of the user to load. If not provided, the current
  1753. * user's ID will be used.
  1754. * @return
  1755. * A fully-loaded $user object upon successful user load, FALSE if user
  1756. * cannot be loaded.
  1757. *
  1758. * @see user_load()
  1759. * @todo rethink the naming of this in Drupal 8.
  1760. */
  1761. function user_uid_optional_load($uid = NULL) {
  1762. if (!isset($uid)) {
  1763. $uid = $GLOBALS['user']->uid;
  1764. }
  1765. return user_load($uid);
  1766. }
  1767. /**
  1768. * Return a user object after checking if any profile category in the path exists.
  1769. */
  1770. function user_category_load($uid, &$map, $index) {
  1771. static $user_categories, $accounts;
  1772. // Cache $account - this load function will get called for each profile tab.
  1773. if (!isset($accounts[$uid])) {
  1774. $accounts[$uid] = user_load($uid);
  1775. }
  1776. $valid = TRUE;
  1777. if ($account = $accounts[$uid]) {
  1778. // Since the path is like user/%/edit/category_name, the category name will
  1779. // be at a position 2 beyond the index corresponding to the % wildcard.
  1780. $category_index = $index + 2;
  1781. // Valid categories may contain slashes, and hence need to be imploded.
  1782. $category_path = implode('/', array_slice($map, $category_index));
  1783. if ($category_path) {
  1784. // Check that the requested category exists.
  1785. $valid = FALSE;
  1786. if (!isset($user_categories)) {
  1787. $user_categories = _user_categories();
  1788. }
  1789. foreach ($user_categories as $category) {
  1790. if ($category['name'] == $category_path) {
  1791. $valid = TRUE;
  1792. // Truncate the map array in case the category name had slashes.
  1793. $map = array_slice($map, 0, $category_index);
  1794. // Assign the imploded category name to the last map element.
  1795. $map[$category_index] = $category_path;
  1796. break;
  1797. }
  1798. }
  1799. }
  1800. }
  1801. return $valid ? $account : FALSE;
  1802. }
  1803. /**
  1804. * Returns $arg or the user ID of the current user if $arg is '%' or empty.
  1805. *
  1806. * @todo rethink the naming of this in Drupal 8.
  1807. */
  1808. function user_uid_optional_to_arg($arg) {
  1809. // Give back the current user uid when called from eg. tracker, aka.
  1810. // with an empty arg. Also use the current user uid when called from
  1811. // the menu with a % for the current account link.
  1812. return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
  1813. }
  1814. /**
  1815. * Menu item title callback for the 'user' path.
  1816. *
  1817. * Anonymous users should see "User account", but authenticated users are
  1818. * expected to see "My account".
  1819. */
  1820. function user_menu_title() {
  1821. return user_is_logged_in() ? t('My account') : t('User account');
  1822. }
  1823. /**
  1824. * Menu item title callback - use the user name.
  1825. */
  1826. function user_page_title($account) {
  1827. return is_object($account) ? format_username($account) : '';
  1828. }
  1829. /**
  1830. * Discover which external authentication module(s) authenticated a username.
  1831. *
  1832. * @param $authname
  1833. * A username used by an external authentication module.
  1834. * @return
  1835. * An associative array with module as key and username as value.
  1836. */
  1837. function user_get_authmaps($authname = NULL) {
  1838. $authmaps = db_query("SELECT module, authname FROM {authmap} WHERE authname = :authname", array(':authname' => $authname))->fetchAllKeyed();
  1839. return count($authmaps) ? $authmaps : 0;
  1840. }
  1841. /**
  1842. * Save mappings of which external authentication module(s) authenticated
  1843. * a user. Maps external usernames to user ids in the users table.
  1844. *
  1845. * @param $account
  1846. * A user object.
  1847. * @param $authmaps
  1848. * An associative array with a compound key and the username as the value.
  1849. * The key is made up of 'authname_' plus the name of the external authentication
  1850. * module.
  1851. * @see user_external_login_register()
  1852. */
  1853. function user_set_authmaps($account, $authmaps) {
  1854. foreach ($authmaps as $key => $value) {
  1855. $module = explode('_', $key, 2);
  1856. if ($value) {
  1857. db_merge('authmap')
  1858. ->key(array(
  1859. 'uid' => $account->uid,
  1860. 'module' => $module[1],
  1861. ))
  1862. ->fields(array('authname' => $value))
  1863. ->execute();
  1864. }
  1865. else {
  1866. db_delete('authmap')
  1867. ->condition('uid', $account->uid)
  1868. ->condition('module', $module[1])
  1869. ->execute();
  1870. }
  1871. }
  1872. }
  1873. /**
  1874. * Form builder; the main user login form.
  1875. *
  1876. * @ingroup forms
  1877. */
  1878. function user_login($form, &$form_state) {
  1879. global $user;
  1880. // If we are already logged on, go to the user page instead.
  1881. if ($user->uid) {
  1882. drupal_goto('user/' . $user->uid);
  1883. }
  1884. // Display login form:
  1885. $form['name'] = array('#type' => 'textfield',
  1886. '#title' => t('Username'),
  1887. '#size' => 60,
  1888. '#maxlength' => USERNAME_MAX_LENGTH,
  1889. '#required' => TRUE,
  1890. );
  1891. $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  1892. $form['pass'] = array('#type' => 'password',
  1893. '#title' => t('Password'),
  1894. '#description' => t('Enter the password that accompanies your username.'),
  1895. '#required' => TRUE,
  1896. );
  1897. $form['#validate'] = user_login_default_validators();
  1898. $form['actions'] = array('#type' => 'actions');
  1899. $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
  1900. return $form;
  1901. }
  1902. /**
  1903. * Set up a series for validators which check for blocked users,
  1904. * then authenticate against local database, then return an error if
  1905. * authentication fails. Distributed authentication modules are welcome
  1906. * to use hook_form_alter() to change this series in order to
  1907. * authenticate against their user database instead of the local users
  1908. * table. If a distributed authentication module is successful, it
  1909. * should set $form_state['uid'] to a user ID.
  1910. *
  1911. * We use three validators instead of one since external authentication
  1912. * modules usually only need to alter the second validator.
  1913. *
  1914. * @see user_login_name_validate()
  1915. * @see user_login_authenticate_validate()
  1916. * @see user_login_final_validate()
  1917. * @return array
  1918. * A simple list of validate functions.
  1919. */
  1920. function user_login_default_validators() {
  1921. return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
  1922. }
  1923. /**
  1924. * A FAPI validate handler. Sets an error if supplied username has been blocked.
  1925. */
  1926. function user_login_name_validate($form, &$form_state) {
  1927. if (isset($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
  1928. // Blocked in user administration.
  1929. form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
  1930. }
  1931. }
  1932. /**
  1933. * A validate handler on the login form. Check supplied username/password
  1934. * against local users table. If successful, $form_state['uid']
  1935. * is set to the matching user ID.
  1936. */
  1937. function user_login_authenticate_validate($form, &$form_state) {
  1938. $password = trim($form_state['values']['pass']);
  1939. if (!empty($form_state['values']['name']) && !empty($password)) {
  1940. // Do not allow any login from the current user's IP if the limit has been
  1941. // reached. Default is 50 failed attempts allowed in one hour. This is
  1942. // independent of the per-user limit to catch attempts from one IP to log
  1943. // in to many different user accounts. We have a reasonably high limit
  1944. // since there may be only one apparent IP for all users at an institution.
  1945. if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
  1946. $form_state['flood_control_triggered'] = 'ip';
  1947. return;
  1948. }
  1949. $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
  1950. if ($account) {
  1951. if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
  1952. // Register flood events based on the uid only, so they apply for any
  1953. // IP address. This is the most secure option.
  1954. $identifier = $account->uid;
  1955. }
  1956. else {
  1957. // The default identifier is a combination of uid and IP address. This
  1958. // is less secure but more resistant to denial-of-service attacks that
  1959. // could lock out all users with public user names.
  1960. $identifier = $account->uid . '-' . ip_address();
  1961. }
  1962. $form_state['flood_control_user_identifier'] = $identifier;
  1963. // Don't allow login if the limit for this user has been reached.
  1964. // Default is to allow 5 failed attempts every 6 hours.
  1965. if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
  1966. $form_state['flood_control_triggered'] = 'user';
  1967. return;
  1968. }
  1969. }
  1970. // We are not limited by flood control, so try to authenticate.
  1971. // Set $form_state['uid'] as a flag for user_login_final_validate().
  1972. $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
  1973. }
  1974. }
  1975. /**
  1976. * The final validation handler on the login form.
  1977. *
  1978. * Sets a form error if user has not been authenticated, or if too many
  1979. * logins have been attempted. This validation function should always
  1980. * be the last one.
  1981. */
  1982. function user_login_final_validate($form, &$form_state) {
  1983. if (empty($form_state['uid'])) {
  1984. // Always register an IP-based failed login event.
  1985. flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
  1986. // Register a per-user failed login event.
  1987. if (isset($form_state['flood_control_user_identifier'])) {
  1988. flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
  1989. }
  1990. if (isset($form_state['flood_control_triggered'])) {
  1991. if ($form_state['flood_control_triggered'] == 'user') {
  1992. form_set_error('name', format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
  1993. }
  1994. else {
  1995. // We did not find a uid, so the limit is IP-based.
  1996. form_set_error('name', t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
  1997. }
  1998. }
  1999. else {
  2000. form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
  2001. watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
  2002. }
  2003. }
  2004. elseif (isset($form_state['flood_control_user_identifier'])) {
  2005. // Clear past failures for this user so as not to block a user who might
  2006. // log in and out more than once in an hour.
  2007. flood_clear_event('failed_login_attempt_user', $form_state['flood_control_user_identifier']);
  2008. }
  2009. }
  2010. /**
  2011. * Try to validate the user's login credentials locally.
  2012. *
  2013. * @param $name
  2014. * User name to authenticate.
  2015. * @param $password
  2016. * A plain-text password, such as trimmed text from form values.
  2017. * @return
  2018. * The user's uid on success, or FALSE on failure to authenticate.
  2019. */
  2020. function user_authenticate($name, $password) {
  2021. $uid = FALSE;
  2022. if (!empty($name) && !empty($password)) {
  2023. $account = user_load_by_name($name);
  2024. if ($account) {
  2025. // Allow alternate password hashing schemes.
  2026. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  2027. if (user_check_password($password, $account)) {
  2028. // Successful authentication.
  2029. $uid = $account->uid;
  2030. // Update user to new password scheme if needed.
  2031. if (user_needs_new_hash($account)) {
  2032. user_save($account, array('pass' => $password));
  2033. }
  2034. }
  2035. }
  2036. }
  2037. return $uid;
  2038. }
  2039. /**
  2040. * Finalize the login process. Must be called when logging in a user.
  2041. *
  2042. * The function records a watchdog message about the new session, saves the
  2043. * login timestamp, calls hook_user op 'login' and generates a new session. *
  2044. */
  2045. function user_login_finalize(&$edit = array()) {
  2046. global $user;
  2047. watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  2048. // Update the user table timestamp noting user has logged in.
  2049. // This is also used to invalidate one-time login links.
  2050. $user->login = REQUEST_TIME;
  2051. db_update('users')
  2052. ->fields(array('login' => $user->login))
  2053. ->condition('uid', $user->uid)
  2054. ->execute();
  2055. // Regenerate the session ID to prevent against session fixation attacks.
  2056. // This is called before hook_user in case one of those functions fails
  2057. // or incorrectly does a redirect which would leave the old session in place.
  2058. drupal_session_regenerate();
  2059. user_module_invoke('login', $edit, $user);
  2060. }
  2061. /**
  2062. * Submit handler for the login form. Load $user object and perform standard login
  2063. * tasks. The user is then redirected to the My Account page. Setting the
  2064. * destination in the query string overrides the redirect.
  2065. */
  2066. function user_login_submit($form, &$form_state) {
  2067. global $user;
  2068. $user = user_load($form_state['uid']);
  2069. $form_state['redirect'] = 'user/' . $user->uid;
  2070. user_login_finalize($form_state);
  2071. }
  2072. /**
  2073. * Helper function for authentication modules. Either logs in or registers
  2074. * the current user, based on username. Either way, the global $user object is
  2075. * populated and login tasks are performed.
  2076. */
  2077. function user_external_login_register($name, $module) {
  2078. $account = user_external_load($name);
  2079. if (!$account) {
  2080. // Register this new user.
  2081. $userinfo = array(
  2082. 'name' => $name,
  2083. 'pass' => user_password(),
  2084. 'init' => $name,
  2085. 'status' => 1,
  2086. 'access' => REQUEST_TIME
  2087. );
  2088. $account = user_save(drupal_anonymous_user(), $userinfo);
  2089. // Terminate if an error occurred during user_save().
  2090. if (!$account) {
  2091. drupal_set_message(t("Error saving user account."), 'error');
  2092. return;
  2093. }
  2094. user_set_authmaps($account, array("authname_$module" => $name));
  2095. }
  2096. // Log user in.
  2097. $form_state['uid'] = $account->uid;
  2098. user_login_submit(array(), $form_state);
  2099. }
  2100. /**
  2101. * Generates a unique URL for a user to login and reset their password.
  2102. *
  2103. * @param object $account
  2104. * An object containing the user account.
  2105. *
  2106. * @return
  2107. * A unique URL that provides a one-time log in for the user, from which
  2108. * they can change their password.
  2109. */
  2110. function user_pass_reset_url($account) {
  2111. $timestamp = REQUEST_TIME;
  2112. return url("user/reset/$account->uid/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
  2113. }
  2114. /**
  2115. * Generates a URL to confirm an account cancellation request.
  2116. *
  2117. * @param object $account
  2118. * The user account object, which must contain at least the following
  2119. * properties:
  2120. * - uid: The user uid number.
  2121. * - pass: The hashed user password string.
  2122. * - login: The user login name.
  2123. *
  2124. * @return
  2125. * A unique URL that may be used to confirm the cancellation of the user
  2126. * account.
  2127. *
  2128. * @see user_mail_tokens()
  2129. * @see user_cancel_confirm()
  2130. */
  2131. function user_cancel_url($account) {
  2132. $timestamp = REQUEST_TIME;
  2133. return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
  2134. }
  2135. /**
  2136. * Creates a unique hash value for use in time-dependent per-user URLs.
  2137. *
  2138. * This hash is normally used to build a unique and secure URL that is sent to
  2139. * the user by email for purposes such as resetting the user's password. In
  2140. * order to validate the URL, the same hash can be generated again, from the
  2141. * same information, and compared to the hash value from the URL. The URL
  2142. * normally contains both the time stamp and the numeric user ID. The login
  2143. * name and hashed password are retrieved from the database as necessary. For a
  2144. * usage example, see user_cancel_url() and user_cancel_confirm().
  2145. *
  2146. * @param $password
  2147. * The hashed user account password value.
  2148. * @param $timestamp
  2149. * A unix timestamp.
  2150. * @param $login
  2151. * The user account login name.
  2152. *
  2153. * @return
  2154. * A string that is safe for use in URLs and SQL statements.
  2155. */
  2156. function user_pass_rehash($password, $timestamp, $login) {
  2157. return drupal_hmac_base64($timestamp . $login, drupal_get_hash_salt() . $password);
  2158. }
  2159. /**
  2160. * Cancel a user account.
  2161. *
  2162. * Since the user cancellation process needs to be run in a batch, either
  2163. * Form API will invoke it, or batch_process() needs to be invoked after calling
  2164. * this function and should define the path to redirect to.
  2165. *
  2166. * @param $edit
  2167. * An array of submitted form values.
  2168. * @param $uid
  2169. * The user ID of the user account to cancel.
  2170. * @param $method
  2171. * The account cancellation method to use.
  2172. *
  2173. * @see _user_cancel()
  2174. */
  2175. function user_cancel($edit, $uid, $method) {
  2176. global $user;
  2177. $account = user_load($uid);
  2178. if (!$account) {
  2179. drupal_set_message(t('The user account %id does not exist.', array('%id' => $uid)), 'error');
  2180. watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR);
  2181. return;
  2182. }
  2183. // Initialize batch (to set title).
  2184. $batch = array(
  2185. 'title' => t('Cancelling account'),
  2186. 'operations' => array(),
  2187. );
  2188. batch_set($batch);
  2189. // Modules use hook_user_delete() to respond to deletion.
  2190. if ($method != 'user_cancel_delete') {
  2191. // Allow modules to add further sets to this batch.
  2192. module_invoke_all('user_cancel', $edit, $account, $method);
  2193. }
  2194. // Finish the batch and actually cancel the account.
  2195. $batch = array(
  2196. 'title' => t('Cancelling user account'),
  2197. 'operations' => array(
  2198. array('_user_cancel', array($edit, $account, $method)),
  2199. ),
  2200. );
  2201. batch_set($batch);
  2202. // Batch processing is either handled via Form API or has to be invoked
  2203. // manually.
  2204. }
  2205. /**
  2206. * Last batch processing step for cancelling a user account.
  2207. *
  2208. * Since batch and session API require a valid user account, the actual
  2209. * cancellation of a user account needs to happen last.
  2210. *
  2211. * @see user_cancel()
  2212. */
  2213. function _user_cancel($edit, $account, $method) {
  2214. global $user;
  2215. switch ($method) {
  2216. case 'user_cancel_block':
  2217. case 'user_cancel_block_unpublish':
  2218. default:
  2219. // Send account blocked notification if option was checked.
  2220. if (!empty($edit['user_cancel_notify'])) {
  2221. _user_mail_notify('status_blocked', $account);
  2222. }
  2223. user_save($account, array('status' => 0));
  2224. drupal_set_message(t('%name has been disabled.', array('%name' => $account->name)));
  2225. watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
  2226. break;
  2227. case 'user_cancel_reassign':
  2228. case 'user_cancel_delete':
  2229. // Send account canceled notification if option was checked.
  2230. if (!empty($edit['user_cancel_notify'])) {
  2231. _user_mail_notify('status_canceled', $account);
  2232. }
  2233. user_delete($account->uid);
  2234. drupal_set_message(t('%name has been deleted.', array('%name' => $account->name)));
  2235. watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
  2236. break;
  2237. }
  2238. // After cancelling account, ensure that user is logged out.
  2239. if ($account->uid == $user->uid) {
  2240. // Destroy the current session, and reset $user to the anonymous user.
  2241. session_destroy();
  2242. }
  2243. // Clear the cache for anonymous users.
  2244. cache_clear_all();
  2245. }
  2246. /**
  2247. * Delete a user.
  2248. *
  2249. * @param $uid
  2250. * A user ID.
  2251. */
  2252. function user_delete($uid) {
  2253. user_delete_multiple(array($uid));
  2254. }
  2255. /**
  2256. * Delete multiple user accounts.
  2257. *
  2258. * @param $uids
  2259. * An array of user IDs.
  2260. */
  2261. function user_delete_multiple(array $uids) {
  2262. if (!empty($uids)) {
  2263. $accounts = user_load_multiple($uids, array());
  2264. $transaction = db_transaction();
  2265. try {
  2266. foreach ($accounts as $uid => $account) {
  2267. module_invoke_all('user_delete', $account);
  2268. module_invoke_all('entity_delete', $account, 'user');
  2269. field_attach_delete('user', $account);
  2270. drupal_session_destroy_uid($account->uid);
  2271. }
  2272. db_delete('users')
  2273. ->condition('uid', $uids, 'IN')
  2274. ->execute();
  2275. db_delete('users_roles')
  2276. ->condition('uid', $uids, 'IN')
  2277. ->execute();
  2278. db_delete('authmap')
  2279. ->condition('uid', $uids, 'IN')
  2280. ->execute();
  2281. }
  2282. catch (Exception $e) {
  2283. $transaction->rollback();
  2284. watchdog_exception('user', $e);
  2285. throw $e;
  2286. }
  2287. entity_get_controller('user')->resetCache();
  2288. }
  2289. }
  2290. /**
  2291. * Page callback wrapper for user_view().
  2292. */
  2293. function user_view_page($account) {
  2294. // An administrator may try to view a non-existent account,
  2295. // so we give them a 404 (versus a 403 for non-admins).
  2296. return is_object($account) ? user_view($account) : MENU_NOT_FOUND;
  2297. }
  2298. /**
  2299. * Generate an array for rendering the given user.
  2300. *
  2301. * When viewing a user profile, the $page array contains:
  2302. *
  2303. * - $page['content']['Profile Category']:
  2304. * Profile categories keyed by their human-readable names.
  2305. * - $page['content']['Profile Category']['profile_machine_name']:
  2306. * Profile fields keyed by their machine-readable names.
  2307. * - $page['content']['user_picture']:
  2308. * User's rendered picture.
  2309. * - $page['content']['summary']:
  2310. * Contains the default "History" profile data for a user.
  2311. * - $page['content']['#account']:
  2312. * The user account of the profile being viewed.
  2313. *
  2314. * To theme user profiles, copy modules/user/user-profile.tpl.php
  2315. * to your theme directory, and edit it as instructed in that file's comments.
  2316. *
  2317. * @param $account
  2318. * A user object.
  2319. * @param $view_mode
  2320. * View mode, e.g. 'full'.
  2321. * @param $langcode
  2322. * (optional) A language code to use for rendering. Defaults to the global
  2323. * content language of the current request.
  2324. *
  2325. * @return
  2326. * An array as expected by drupal_render().
  2327. */
  2328. function user_view($account, $view_mode = 'full', $langcode = NULL) {
  2329. if (!isset($langcode)) {
  2330. $langcode = $GLOBALS['language_content']->language;
  2331. }
  2332. // Retrieve all profile fields and attach to $account->content.
  2333. user_build_content($account, $view_mode, $langcode);
  2334. $build = $account->content;
  2335. // We don't need duplicate rendering info in account->content.
  2336. unset($account->content);
  2337. $build += array(
  2338. '#theme' => 'user_profile',
  2339. '#account' => $account,
  2340. '#view_mode' => $view_mode,
  2341. '#language' => $langcode,
  2342. );
  2343. // Allow modules to modify the structured user.
  2344. $type = 'user';
  2345. drupal_alter(array('user_view', 'entity_view'), $build, $type);
  2346. return $build;
  2347. }
  2348. /**
  2349. * Builds a structured array representing the profile content.
  2350. *
  2351. * @param $account
  2352. * A user object.
  2353. * @param $view_mode
  2354. * View mode, e.g. 'full'.
  2355. * @param $langcode
  2356. * (optional) A language code to use for rendering. Defaults to the global
  2357. * content language of the current request.
  2358. */
  2359. function user_build_content($account, $view_mode = 'full', $langcode = NULL) {
  2360. if (!isset($langcode)) {
  2361. $langcode = $GLOBALS['language_content']->language;
  2362. }
  2363. // Remove previously built content, if exists.
  2364. $account->content = array();
  2365. // Allow modules to change the view mode.
  2366. $context = array(
  2367. 'entity_type' => 'user',
  2368. 'entity' => $account,
  2369. 'langcode' => $langcode,
  2370. );
  2371. drupal_alter('entity_view_mode', $view_mode, $context);
  2372. // Build fields content.
  2373. field_attach_prepare_view('user', array($account->uid => $account), $view_mode, $langcode);
  2374. entity_prepare_view('user', array($account->uid => $account), $langcode);
  2375. $account->content += field_attach_view('user', $account, $view_mode, $langcode);
  2376. // Populate $account->content with a render() array.
  2377. module_invoke_all('user_view', $account, $view_mode, $langcode);
  2378. module_invoke_all('entity_view', $account, 'user', $view_mode, $langcode);
  2379. // Make sure the current view mode is stored if no module has already
  2380. // populated the related key.
  2381. $account->content += array('#view_mode' => $view_mode);
  2382. }
  2383. /**
  2384. * Implements hook_mail().
  2385. */
  2386. function user_mail($key, &$message, $params) {
  2387. $language = $message['language'];
  2388. $variables = array('user' => $params['account']);
  2389. $message['subject'] .= _user_mail_text($key . '_subject', $language, $variables);
  2390. $message['body'][] = _user_mail_text($key . '_body', $language, $variables);
  2391. }
  2392. /**
  2393. * Returns a mail string for a variable name.
  2394. *
  2395. * Used by user_mail() and the settings forms to retrieve strings.
  2396. */
  2397. function _user_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) {
  2398. $langcode = isset($language) ? $language->language : NULL;
  2399. if ($admin_setting = variable_get('user_mail_' . $key, FALSE)) {
  2400. // An admin setting overrides the default string.
  2401. $text = $admin_setting;
  2402. }
  2403. else {
  2404. // No override, return default string.
  2405. switch ($key) {
  2406. case 'register_no_approval_required_subject':
  2407. $text = t('Account details for [user:name] at [site:name]', array(), array('langcode' => $langcode));
  2408. break;
  2409. case 'register_no_approval_required_body':
  2410. $text = t("[user:name],
  2411. Thank you for registering at [site:name]. You may now log in by clicking this link or copying and pasting it to your browser:
  2412. [user:one-time-login-url]
  2413. This link can only be used once to log in and will lead you to a page where you can set your password.
  2414. After setting your password, you will be able to log in at [site:login-url] in the future using:
  2415. username: [user:name]
  2416. password: Your password
  2417. -- [site:name] team", array(), array('langcode' => $langcode));
  2418. break;
  2419. case 'register_admin_created_subject':
  2420. $text = t('An administrator created an account for you at [site:name]', array(), array('langcode' => $langcode));
  2421. break;
  2422. case 'register_admin_created_body':
  2423. $text = t("[user:name],
  2424. A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:
  2425. [user:one-time-login-url]
  2426. This link can only be used once to log in and will lead you to a page where you can set your password.
  2427. After setting your password, you will be able to log in at [site:login-url] in the future using:
  2428. username: [user:name]
  2429. password: Your password
  2430. -- [site:name] team", array(), array('langcode' => $langcode));
  2431. break;
  2432. case 'register_pending_approval_subject':
  2433. case 'register_pending_approval_admin_subject':
  2434. $text = t('Account details for [user:name] at [site:name] (pending admin approval)', array(), array('langcode' => $langcode));
  2435. break;
  2436. case 'register_pending_approval_body':
  2437. $text = t("[user:name],
  2438. Thank you for registering at [site:name]. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.
  2439. -- [site:name] team", array(), array('langcode' => $langcode));
  2440. break;
  2441. case 'register_pending_approval_admin_body':
  2442. $text = t("[user:name] has applied for an account.
  2443. [user:edit-url]", array(), array('langcode' => $langcode));
  2444. break;
  2445. case 'password_reset_subject':
  2446. $text = t('Replacement login information for [user:name] at [site:name]', array(), array('langcode' => $langcode));
  2447. break;
  2448. case 'password_reset_body':
  2449. $text = t("[user:name],
  2450. A request to reset the password for your account has been made at [site:name].
  2451. You may now log in by clicking this link or copying and pasting it to your browser:
  2452. [user:one-time-login-url]
  2453. This link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.
  2454. -- [site:name] team", array(), array('langcode' => $langcode));
  2455. break;
  2456. case 'status_activated_subject':
  2457. $text = t('Account details for [user:name] at [site:name] (approved)', array(), array('langcode' => $langcode));
  2458. break;
  2459. case 'status_activated_body':
  2460. $text = t("[user:name],
  2461. Your account at [site:name] has been activated.
  2462. You may now log in by clicking this link or copying and pasting it into your browser:
  2463. [user:one-time-login-url]
  2464. This link can only be used once to log in and will lead you to a page where you can set your password.
  2465. After setting your password, you will be able to log in at [site:login-url] in the future using:
  2466. username: [user:name]
  2467. password: Your password
  2468. -- [site:name] team", array(), array('langcode' => $langcode));
  2469. break;
  2470. case 'status_blocked_subject':
  2471. $text = t('Account details for [user:name] at [site:name] (blocked)', array(), array('langcode' => $langcode));
  2472. break;
  2473. case 'status_blocked_body':
  2474. $text = t("[user:name],
  2475. Your account on [site:name] has been blocked.
  2476. -- [site:name] team", array(), array('langcode' => $langcode));
  2477. break;
  2478. case 'cancel_confirm_subject':
  2479. $text = t('Account cancellation request for [user:name] at [site:name]', array(), array('langcode' => $langcode));
  2480. break;
  2481. case 'cancel_confirm_body':
  2482. $text = t("[user:name],
  2483. A request to cancel your account has been made at [site:name].
  2484. You may now cancel your account on [site:url-brief] by clicking this link or copying and pasting it into your browser:
  2485. [user:cancel-url]
  2486. NOTE: The cancellation of your account is not reversible.
  2487. This link expires in one day and nothing will happen if it is not used.
  2488. -- [site:name] team", array(), array('langcode' => $langcode));
  2489. break;
  2490. case 'status_canceled_subject':
  2491. $text = t('Account details for [user:name] at [site:name] (canceled)', array(), array('langcode' => $langcode));
  2492. break;
  2493. case 'status_canceled_body':
  2494. $text = t("[user:name],
  2495. Your account on [site:name] has been canceled.
  2496. -- [site:name] team", array(), array('langcode' => $langcode));
  2497. break;
  2498. }
  2499. }
  2500. if ($replace) {
  2501. // We do not sanitize the token replacement, since the output of this
  2502. // replacement is intended for an e-mail message, not a web browser.
  2503. return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
  2504. }
  2505. return $text;
  2506. }
  2507. /**
  2508. * Token callback to add unsafe tokens for user mails.
  2509. *
  2510. * This function is used by the token_replace() call at the end of
  2511. * _user_mail_text() to set up some additional tokens that can be
  2512. * used in email messages generated by user_mail().
  2513. *
  2514. * @param $replacements
  2515. * An associative array variable containing mappings from token names to
  2516. * values (for use with strtr()).
  2517. * @param $data
  2518. * An associative array of token replacement values. If the 'user' element
  2519. * exists, it must contain a user account object with the following
  2520. * properties:
  2521. * - login: The account login name.
  2522. * - pass: The hashed account login password.
  2523. * @param $options
  2524. * Unused parameter required by the token_replace() function.
  2525. */
  2526. function user_mail_tokens(&$replacements, $data, $options) {
  2527. if (isset($data['user'])) {
  2528. $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
  2529. $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
  2530. }
  2531. }
  2532. /*** Administrative features ***********************************************/
  2533. /**
  2534. * Retrieve an array of roles matching specified conditions.
  2535. *
  2536. * @param $membersonly
  2537. * Set this to TRUE to exclude the 'anonymous' role.
  2538. * @param $permission
  2539. * A string containing a permission. If set, only roles containing that
  2540. * permission are returned.
  2541. *
  2542. * @return
  2543. * An associative array with the role id as the key and the role name as
  2544. * value.
  2545. */
  2546. function user_roles($membersonly = FALSE, $permission = NULL) {
  2547. $query = db_select('role', 'r');
  2548. $query->addTag('translatable');
  2549. $query->fields('r', array('rid', 'name'));
  2550. $query->orderBy('weight');
  2551. $query->orderBy('name');
  2552. if (!empty($permission)) {
  2553. $query->innerJoin('role_permission', 'p', 'r.rid = p.rid');
  2554. $query->condition('p.permission', $permission);
  2555. }
  2556. $result = $query->execute();
  2557. $roles = array();
  2558. foreach ($result as $role) {
  2559. switch ($role->rid) {
  2560. // We only translate the built in role names
  2561. case DRUPAL_ANONYMOUS_RID:
  2562. if (!$membersonly) {
  2563. $roles[$role->rid] = t($role->name);
  2564. }
  2565. break;
  2566. case DRUPAL_AUTHENTICATED_RID:
  2567. $roles[$role->rid] = t($role->name);
  2568. break;
  2569. default:
  2570. $roles[$role->rid] = $role->name;
  2571. }
  2572. }
  2573. return $roles;
  2574. }
  2575. /**
  2576. * Fetches a user role by role ID.
  2577. *
  2578. * @param $rid
  2579. * An integer representing the role ID.
  2580. *
  2581. * @return
  2582. * A fully-loaded role object if a role with the given ID exists, or FALSE
  2583. * otherwise.
  2584. *
  2585. * @see user_role_load_by_name()
  2586. */
  2587. function user_role_load($rid) {
  2588. return db_select('role', 'r')
  2589. ->fields('r')
  2590. ->condition('rid', $rid)
  2591. ->execute()
  2592. ->fetchObject();
  2593. }
  2594. /**
  2595. * Fetches a user role by role name.
  2596. *
  2597. * @param $role_name
  2598. * A string representing the role name.
  2599. *
  2600. * @return
  2601. * A fully-loaded role object if a role with the given name exists, or FALSE
  2602. * otherwise.
  2603. *
  2604. * @see user_role_load()
  2605. */
  2606. function user_role_load_by_name($role_name) {
  2607. return db_select('role', 'r')
  2608. ->fields('r')
  2609. ->condition('name', $role_name)
  2610. ->execute()
  2611. ->fetchObject();
  2612. }
  2613. /**
  2614. * Save a user role to the database.
  2615. *
  2616. * @param $role
  2617. * A role object to modify or add. If $role->rid is not specified, a new
  2618. * role will be created.
  2619. * @return
  2620. * Status constant indicating if role was created or updated.
  2621. * Failure to write the user role record will return FALSE. Otherwise.
  2622. * SAVED_NEW or SAVED_UPDATED is returned depending on the operation
  2623. * performed.
  2624. */
  2625. function user_role_save($role) {
  2626. if ($role->name) {
  2627. // Prevent leading and trailing spaces in role names.
  2628. $role->name = trim($role->name);
  2629. }
  2630. if (!isset($role->weight)) {
  2631. // Set a role weight to make this new role last.
  2632. $query = db_select('role');
  2633. $query->addExpression('MAX(weight)');
  2634. $role->weight = $query->execute()->fetchField() + 1;
  2635. }
  2636. // Let modules modify the user role before it is saved to the database.
  2637. module_invoke_all('user_role_presave', $role);
  2638. if (!empty($role->rid) && $role->name) {
  2639. $status = drupal_write_record('role', $role, 'rid');
  2640. module_invoke_all('user_role_update', $role);
  2641. }
  2642. else {
  2643. $status = drupal_write_record('role', $role);
  2644. module_invoke_all('user_role_insert', $role);
  2645. }
  2646. // Clear the user access cache.
  2647. drupal_static_reset('user_access');
  2648. drupal_static_reset('user_role_permissions');
  2649. return $status;
  2650. }
  2651. /**
  2652. * Delete a user role from database.
  2653. *
  2654. * @param $role
  2655. * A string with the role name, or an integer with the role ID.
  2656. */
  2657. function user_role_delete($role) {
  2658. if (is_int($role)) {
  2659. $role = user_role_load($role);
  2660. }
  2661. else {
  2662. $role = user_role_load_by_name($role);
  2663. }
  2664. db_delete('role')
  2665. ->condition('rid', $role->rid)
  2666. ->execute();
  2667. db_delete('role_permission')
  2668. ->condition('rid', $role->rid)
  2669. ->execute();
  2670. // Update the users who have this role set:
  2671. db_delete('users_roles')
  2672. ->condition('rid', $role->rid)
  2673. ->execute();
  2674. module_invoke_all('user_role_delete', $role);
  2675. // Clear the user access cache.
  2676. drupal_static_reset('user_access');
  2677. drupal_static_reset('user_role_permissions');
  2678. }
  2679. /**
  2680. * Menu access callback for user role editing.
  2681. */
  2682. function user_role_edit_access($role) {
  2683. // Prevent the system-defined roles from being altered or removed.
  2684. if ($role->rid == DRUPAL_ANONYMOUS_RID || $role->rid == DRUPAL_AUTHENTICATED_RID) {
  2685. return FALSE;
  2686. }
  2687. return user_access('administer permissions');
  2688. }
  2689. /**
  2690. * Determine the modules that permissions belong to.
  2691. *
  2692. * @return
  2693. * An associative array in the format $permission => $module.
  2694. */
  2695. function user_permission_get_modules() {
  2696. $permissions = array();
  2697. foreach (module_implements('permission') as $module) {
  2698. $perms = module_invoke($module, 'permission');
  2699. foreach ($perms as $key => $value) {
  2700. $permissions[$key] = $module;
  2701. }
  2702. }
  2703. return $permissions;
  2704. }
  2705. /**
  2706. * Change permissions for a user role.
  2707. *
  2708. * This function may be used to grant and revoke multiple permissions at once.
  2709. * For example, when a form exposes checkboxes to configure permissions for a
  2710. * role, the form submit handler may directly pass the submitted values for the
  2711. * checkboxes form element to this function.
  2712. *
  2713. * @param $rid
  2714. * The ID of a user role to alter.
  2715. * @param $permissions
  2716. * An associative array, where the key holds the permission name and the value
  2717. * determines whether to grant or revoke that permission. Any value that
  2718. * evaluates to TRUE will cause the permission to be granted. Any value that
  2719. * evaluates to FALSE will cause the permission to be revoked.
  2720. * @code
  2721. * array(
  2722. * 'administer nodes' => 0, // Revoke 'administer nodes'
  2723. * 'administer blocks' => FALSE, // Revoke 'administer blocks'
  2724. * 'access user profiles' => 1, // Grant 'access user profiles'
  2725. * 'access content' => TRUE, // Grant 'access content'
  2726. * 'access comments' => 'access comments', // Grant 'access comments'
  2727. * )
  2728. * @endcode
  2729. * Existing permissions are not changed, unless specified in $permissions.
  2730. *
  2731. * @see user_role_grant_permissions()
  2732. * @see user_role_revoke_permissions()
  2733. */
  2734. function user_role_change_permissions($rid, array $permissions = array()) {
  2735. // Grant new permissions for the role.
  2736. $grant = array_filter($permissions);
  2737. if (!empty($grant)) {
  2738. user_role_grant_permissions($rid, array_keys($grant));
  2739. }
  2740. // Revoke permissions for the role.
  2741. $revoke = array_diff_assoc($permissions, $grant);
  2742. if (!empty($revoke)) {
  2743. user_role_revoke_permissions($rid, array_keys($revoke));
  2744. }
  2745. }
  2746. /**
  2747. * Grant permissions to a user role.
  2748. *
  2749. * @param $rid
  2750. * The ID of a user role to alter.
  2751. * @param $permissions
  2752. * A list of permission names to grant.
  2753. *
  2754. * @see user_role_change_permissions()
  2755. * @see user_role_revoke_permissions()
  2756. */
  2757. function user_role_grant_permissions($rid, array $permissions = array()) {
  2758. $modules = user_permission_get_modules();
  2759. // Grant new permissions for the role.
  2760. foreach ($permissions as $name) {
  2761. db_merge('role_permission')
  2762. ->key(array(
  2763. 'rid' => $rid,
  2764. 'permission' => $name,
  2765. ))
  2766. ->fields(array(
  2767. 'module' => $modules[$name],
  2768. ))
  2769. ->execute();
  2770. }
  2771. // Clear the user access cache.
  2772. drupal_static_reset('user_access');
  2773. drupal_static_reset('user_role_permissions');
  2774. }
  2775. /**
  2776. * Revoke permissions from a user role.
  2777. *
  2778. * @param $rid
  2779. * The ID of a user role to alter.
  2780. * @param $permissions
  2781. * A list of permission names to revoke.
  2782. *
  2783. * @see user_role_change_permissions()
  2784. * @see user_role_grant_permissions()
  2785. */
  2786. function user_role_revoke_permissions($rid, array $permissions = array()) {
  2787. // Revoke permissions for the role.
  2788. db_delete('role_permission')
  2789. ->condition('rid', $rid)
  2790. ->condition('permission', $permissions, 'IN')
  2791. ->execute();
  2792. // Clear the user access cache.
  2793. drupal_static_reset('user_access');
  2794. drupal_static_reset('user_role_permissions');
  2795. }
  2796. /**
  2797. * Implements hook_user_operations().
  2798. */
  2799. function user_user_operations($form = array(), $form_state = array()) {
  2800. $operations = array(
  2801. 'unblock' => array(
  2802. 'label' => t('Unblock the selected users'),
  2803. 'callback' => 'user_user_operations_unblock',
  2804. ),
  2805. 'block' => array(
  2806. 'label' => t('Block the selected users'),
  2807. 'callback' => 'user_user_operations_block',
  2808. ),
  2809. 'cancel' => array(
  2810. 'label' => t('Cancel the selected user accounts'),
  2811. ),
  2812. );
  2813. if (user_access('administer permissions')) {
  2814. $roles = user_roles(TRUE);
  2815. unset($roles[DRUPAL_AUTHENTICATED_RID]); // Can't edit authenticated role.
  2816. $add_roles = array();
  2817. foreach ($roles as $key => $value) {
  2818. $add_roles['add_role-' . $key] = $value;
  2819. }
  2820. $remove_roles = array();
  2821. foreach ($roles as $key => $value) {
  2822. $remove_roles['remove_role-' . $key] = $value;
  2823. }
  2824. if (count($roles)) {
  2825. $role_operations = array(
  2826. t('Add a role to the selected users') => array(
  2827. 'label' => $add_roles,
  2828. ),
  2829. t('Remove a role from the selected users') => array(
  2830. 'label' => $remove_roles,
  2831. ),
  2832. );
  2833. $operations += $role_operations;
  2834. }
  2835. }
  2836. // If the form has been posted, we need to insert the proper data for
  2837. // role editing if necessary.
  2838. if (!empty($form_state['submitted'])) {
  2839. $operation_rid = explode('-', $form_state['values']['operation']);
  2840. $operation = $operation_rid[0];
  2841. if ($operation == 'add_role' || $operation == 'remove_role') {
  2842. $rid = $operation_rid[1];
  2843. if (user_access('administer permissions')) {
  2844. $operations[$form_state['values']['operation']] = array(
  2845. 'callback' => 'user_multiple_role_edit',
  2846. 'callback arguments' => array($operation, $rid),
  2847. );
  2848. }
  2849. else {
  2850. watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
  2851. return;
  2852. }
  2853. }
  2854. }
  2855. return $operations;
  2856. }
  2857. /**
  2858. * Callback function for admin mass unblocking users.
  2859. */
  2860. function user_user_operations_unblock($accounts) {
  2861. $accounts = user_load_multiple($accounts);
  2862. foreach ($accounts as $account) {
  2863. // Skip unblocking user if they are already unblocked.
  2864. if ($account !== FALSE && $account->status == 0) {
  2865. user_save($account, array('status' => 1));
  2866. }
  2867. }
  2868. }
  2869. /**
  2870. * Callback function for admin mass blocking users.
  2871. */
  2872. function user_user_operations_block($accounts) {
  2873. $accounts = user_load_multiple($accounts);
  2874. foreach ($accounts as $account) {
  2875. // Skip blocking user if they are already blocked.
  2876. if ($account !== FALSE && $account->status == 1) {
  2877. // For efficiency manually save the original account before applying any
  2878. // changes.
  2879. $account->original = clone $account;
  2880. user_save($account, array('status' => 0));
  2881. }
  2882. }
  2883. }
  2884. /**
  2885. * Callback function for admin mass adding/deleting a user role.
  2886. */
  2887. function user_multiple_role_edit($accounts, $operation, $rid) {
  2888. // The role name is not necessary as user_save() will reload the user
  2889. // object, but some modules' hook_user() may look at this first.
  2890. $role_name = db_query('SELECT name FROM {role} WHERE rid = :rid', array(':rid' => $rid))->fetchField();
  2891. switch ($operation) {
  2892. case 'add_role':
  2893. $accounts = user_load_multiple($accounts);
  2894. foreach ($accounts as $account) {
  2895. // Skip adding the role to the user if they already have it.
  2896. if ($account !== FALSE && !isset($account->roles[$rid])) {
  2897. $roles = $account->roles + array($rid => $role_name);
  2898. // For efficiency manually save the original account before applying
  2899. // any changes.
  2900. $account->original = clone $account;
  2901. user_save($account, array('roles' => $roles));
  2902. }
  2903. }
  2904. break;
  2905. case 'remove_role':
  2906. $accounts = user_load_multiple($accounts);
  2907. foreach ($accounts as $account) {
  2908. // Skip removing the role from the user if they already don't have it.
  2909. if ($account !== FALSE && isset($account->roles[$rid])) {
  2910. $roles = array_diff($account->roles, array($rid => $role_name));
  2911. // For efficiency manually save the original account before applying
  2912. // any changes.
  2913. $account->original = clone $account;
  2914. user_save($account, array('roles' => $roles));
  2915. }
  2916. }
  2917. break;
  2918. }
  2919. }
  2920. function user_multiple_cancel_confirm($form, &$form_state) {
  2921. $edit = $form_state['input'];
  2922. $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  2923. $accounts = user_load_multiple(array_keys(array_filter($edit['accounts'])));
  2924. foreach ($accounts as $uid => $account) {
  2925. // Prevent user 1 from being canceled.
  2926. if ($uid <= 1) {
  2927. continue;
  2928. }
  2929. $form['accounts'][$uid] = array(
  2930. '#type' => 'hidden',
  2931. '#value' => $uid,
  2932. '#prefix' => '<li>',
  2933. '#suffix' => check_plain($account->name) . "</li>\n",
  2934. );
  2935. }
  2936. // Output a notice that user 1 cannot be canceled.
  2937. if (isset($accounts[1])) {
  2938. $redirect = (count($accounts) == 1);
  2939. $message = t('The user account %name cannot be cancelled.', array('%name' => $accounts[1]->name));
  2940. drupal_set_message($message, $redirect ? 'error' : 'warning');
  2941. // If only user 1 was selected, redirect to the overview.
  2942. if ($redirect) {
  2943. drupal_goto('admin/people');
  2944. }
  2945. }
  2946. $form['operation'] = array('#type' => 'hidden', '#value' => 'cancel');
  2947. module_load_include('inc', 'user', 'user.pages');
  2948. $form['user_cancel_method'] = array(
  2949. '#type' => 'item',
  2950. '#title' => t('When cancelling these accounts'),
  2951. );
  2952. $form['user_cancel_method'] += user_cancel_methods();
  2953. // Remove method descriptions.
  2954. foreach (element_children($form['user_cancel_method']) as $element) {
  2955. unset($form['user_cancel_method'][$element]['#description']);
  2956. }
  2957. // Allow to send the account cancellation confirmation mail.
  2958. $form['user_cancel_confirm'] = array(
  2959. '#type' => 'checkbox',
  2960. '#title' => t('Require e-mail confirmation to cancel account.'),
  2961. '#default_value' => FALSE,
  2962. '#description' => t('When enabled, the user must confirm the account cancellation via e-mail.'),
  2963. );
  2964. // Also allow to send account canceled notification mail, if enabled.
  2965. $form['user_cancel_notify'] = array(
  2966. '#type' => 'checkbox',
  2967. '#title' => t('Notify user when account is canceled.'),
  2968. '#default_value' => FALSE,
  2969. '#access' => variable_get('user_mail_status_canceled_notify', FALSE),
  2970. '#description' => t('When enabled, the user will receive an e-mail notification after the account has been cancelled.'),
  2971. );
  2972. return confirm_form($form,
  2973. t('Are you sure you want to cancel these user accounts?'),
  2974. 'admin/people', t('This action cannot be undone.'),
  2975. t('Cancel accounts'), t('Cancel'));
  2976. }
  2977. /**
  2978. * Submit handler for mass-account cancellation form.
  2979. *
  2980. * @see user_multiple_cancel_confirm()
  2981. * @see user_cancel_confirm_form_submit()
  2982. */
  2983. function user_multiple_cancel_confirm_submit($form, &$form_state) {
  2984. global $user;
  2985. if ($form_state['values']['confirm']) {
  2986. foreach ($form_state['values']['accounts'] as $uid => $value) {
  2987. // Prevent programmatic form submissions from cancelling user 1.
  2988. if ($uid <= 1) {
  2989. continue;
  2990. }
  2991. // Prevent user administrators from deleting themselves without confirmation.
  2992. if ($uid == $user->uid) {
  2993. $admin_form_state = $form_state;
  2994. unset($admin_form_state['values']['user_cancel_confirm']);
  2995. $admin_form_state['values']['_account'] = $user;
  2996. user_cancel_confirm_form_submit(array(), $admin_form_state);
  2997. }
  2998. else {
  2999. user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']);
  3000. }
  3001. }
  3002. }
  3003. $form_state['redirect'] = 'admin/people';
  3004. }
  3005. /**
  3006. * Retrieve a list of all user setting/information categories and sort them by weight.
  3007. */
  3008. function _user_categories() {
  3009. $categories = module_invoke_all('user_categories');
  3010. usort($categories, '_user_sort');
  3011. return $categories;
  3012. }
  3013. function _user_sort($a, $b) {
  3014. $a = (array) $a + array('weight' => 0, 'title' => '');
  3015. $b = (array) $b + array('weight' => 0, 'title' => '');
  3016. return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
  3017. }
  3018. /**
  3019. * List user administration filters that can be applied.
  3020. */
  3021. function user_filters() {
  3022. // Regular filters
  3023. $filters = array();
  3024. $roles = user_roles(TRUE);
  3025. unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
  3026. if (count($roles)) {
  3027. $filters['role'] = array(
  3028. 'title' => t('role'),
  3029. 'field' => 'ur.rid',
  3030. 'options' => array(
  3031. '[any]' => t('any'),
  3032. ) + $roles,
  3033. );
  3034. }
  3035. $options = array();
  3036. foreach (module_implements('permission') as $module) {
  3037. $function = $module . '_permission';
  3038. if ($permissions = $function('permission')) {
  3039. asort($permissions);
  3040. foreach ($permissions as $permission => $description) {
  3041. $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
  3042. }
  3043. }
  3044. }
  3045. ksort($options);
  3046. $filters['permission'] = array(
  3047. 'title' => t('permission'),
  3048. 'options' => array(
  3049. '[any]' => t('any'),
  3050. ) + $options,
  3051. );
  3052. $filters['status'] = array(
  3053. 'title' => t('status'),
  3054. 'field' => 'u.status',
  3055. 'options' => array(
  3056. '[any]' => t('any'),
  3057. 1 => t('active'),
  3058. 0 => t('blocked'),
  3059. ),
  3060. );
  3061. return $filters;
  3062. }
  3063. /**
  3064. * Extends a query object for user administration filters based on session.
  3065. *
  3066. * @param $query
  3067. * Query object that should be filtered.
  3068. */
  3069. function user_build_filter_query(SelectQuery $query) {
  3070. $filters = user_filters();
  3071. // Extend Query with filter conditions.
  3072. foreach (isset($_SESSION['user_overview_filter']) ? $_SESSION['user_overview_filter'] : array() as $filter) {
  3073. list($key, $value) = $filter;
  3074. // This checks to see if this permission filter is an enabled permission for
  3075. // the authenticated role. If so, then all users would be listed, and we can
  3076. // skip adding it to the filter query.
  3077. if ($key == 'permission') {
  3078. $account = new stdClass();
  3079. $account->uid = 'user_filter';
  3080. $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
  3081. if (user_access($value, $account)) {
  3082. continue;
  3083. }
  3084. $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
  3085. $permission_alias = $query->join('role_permission', 'p', $users_roles_alias . '.rid = %alias.rid');
  3086. $query->condition($permission_alias . '.permission', $value);
  3087. }
  3088. elseif ($key == 'role') {
  3089. $users_roles_alias = $query->join('users_roles', 'ur', '%alias.uid = u.uid');
  3090. $query->condition($users_roles_alias . '.rid' , $value);
  3091. }
  3092. else {
  3093. $query->condition($filters[$key]['field'], $value);
  3094. }
  3095. }
  3096. }
  3097. /**
  3098. * Implements hook_comment_view().
  3099. */
  3100. function user_comment_view($comment) {
  3101. if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
  3102. // @todo This alters and replaces the original object value, so a
  3103. // hypothetical process of loading, viewing, and saving will hijack the
  3104. // stored data. Consider renaming to $comment->signature_safe or similar
  3105. // here and elsewhere in Drupal 8.
  3106. $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
  3107. }
  3108. else {
  3109. $comment->signature = '';
  3110. }
  3111. }
  3112. /**
  3113. * Returns HTML for a user signature.
  3114. *
  3115. * @param $variables
  3116. * An associative array containing:
  3117. * - signature: The user's signature.
  3118. *
  3119. * @ingroup themeable
  3120. */
  3121. function theme_user_signature($variables) {
  3122. $signature = $variables['signature'];
  3123. $output = '';
  3124. if ($signature) {
  3125. $output .= '<div class="clear">';
  3126. $output .= '<div>—</div>';
  3127. $output .= $signature;
  3128. $output .= '</div>';
  3129. }
  3130. return $output;
  3131. }
  3132. /**
  3133. * Get the language object preferred by the user. This user preference can
  3134. * be set on the user account editing page, and is only available if there
  3135. * are more than one languages enabled on the site. If the user did not
  3136. * choose a preferred language, or is the anonymous user, the $default
  3137. * value, or if it is not set, the site default language will be returned.
  3138. *
  3139. * @param $account
  3140. * User account to look up language for.
  3141. * @param $default
  3142. * Optional default language object to return if the account
  3143. * has no valid language.
  3144. */
  3145. function user_preferred_language($account, $default = NULL) {
  3146. $language_list = language_list();
  3147. if (!empty($account->language) && isset($language_list[$account->language])) {
  3148. return $language_list[$account->language];
  3149. }
  3150. else {
  3151. return $default ? $default : language_default();
  3152. }
  3153. }
  3154. /**
  3155. * Conditionally create and send a notification email when a certain
  3156. * operation happens on the given user account.
  3157. *
  3158. * @see user_mail_tokens()
  3159. * @see drupal_mail()
  3160. *
  3161. * @param $op
  3162. * The operation being performed on the account. Possible values:
  3163. * - 'register_admin_created': Welcome message for user created by the admin.
  3164. * - 'register_no_approval_required': Welcome message when user
  3165. * self-registers.
  3166. * - 'register_pending_approval': Welcome message, user pending admin
  3167. * approval.
  3168. * - 'password_reset': Password recovery request.
  3169. * - 'status_activated': Account activated.
  3170. * - 'status_blocked': Account blocked.
  3171. * - 'cancel_confirm': Account cancellation request.
  3172. * - 'status_canceled': Account canceled.
  3173. *
  3174. * @param $account
  3175. * The user object of the account being notified. Must contain at
  3176. * least the fields 'uid', 'name', and 'mail'.
  3177. * @param $language
  3178. * Optional language to use for the notification, overriding account language.
  3179. *
  3180. * @return
  3181. * The return value from drupal_mail_system()->mail(), if ends up being
  3182. * called.
  3183. */
  3184. function _user_mail_notify($op, $account, $language = NULL) {
  3185. // By default, we always notify except for canceled and blocked.
  3186. $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
  3187. $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
  3188. if ($notify) {
  3189. $params['account'] = $account;
  3190. $language = $language ? $language : user_preferred_language($account);
  3191. $mail = drupal_mail('user', $op, $account->mail, $language, $params);
  3192. if ($op == 'register_pending_approval') {
  3193. // If a user registered requiring admin approval, notify the admin, too.
  3194. // We use the site default language for this.
  3195. drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
  3196. }
  3197. }
  3198. return empty($mail) ? NULL : $mail['result'];
  3199. }
  3200. /**
  3201. * Form element process handler for client-side password validation.
  3202. *
  3203. * This #process handler is automatically invoked for 'password_confirm' form
  3204. * elements to add the JavaScript and string translations for dynamic password
  3205. * validation.
  3206. *
  3207. * @see system_element_info()
  3208. */
  3209. function user_form_process_password_confirm($element) {
  3210. global $user;
  3211. $js_settings = array(
  3212. 'password' => array(
  3213. 'strengthTitle' => t('Password strength:'),
  3214. 'hasWeaknesses' => t('To make your password stronger:'),
  3215. 'tooShort' => t('Make it at least 6 characters'),
  3216. 'addLowerCase' => t('Add lowercase letters'),
  3217. 'addUpperCase' => t('Add uppercase letters'),
  3218. 'addNumbers' => t('Add numbers'),
  3219. 'addPunctuation' => t('Add punctuation'),
  3220. 'sameAsUsername' => t('Make it different from your username'),
  3221. 'confirmSuccess' => t('yes'),
  3222. 'confirmFailure' => t('no'),
  3223. 'weak' => t('Weak'),
  3224. 'fair' => t('Fair'),
  3225. 'good' => t('Good'),
  3226. 'strong' => t('Strong'),
  3227. 'confirmTitle' => t('Passwords match:'),
  3228. 'username' => (isset($user->name) ? $user->name : ''),
  3229. ),
  3230. );
  3231. $element['#attached']['js'][] = drupal_get_path('module', 'user') . '/user.js';
  3232. // Ensure settings are only added once per page.
  3233. static $already_added = FALSE;
  3234. if (!$already_added) {
  3235. $already_added = TRUE;
  3236. $element['#attached']['js'][] = array('data' => $js_settings, 'type' => 'setting');
  3237. }
  3238. return $element;
  3239. }
  3240. /**
  3241. * Implements hook_node_load().
  3242. */
  3243. function user_node_load($nodes, $types) {
  3244. // Build an array of all uids for node authors, keyed by nid.
  3245. $uids = array();
  3246. foreach ($nodes as $nid => $node) {
  3247. $uids[$nid] = $node->uid;
  3248. }
  3249. // Fetch name, picture, and data for these users.
  3250. $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');
  3251. // Add these values back into the node objects.
  3252. foreach ($uids as $nid => $uid) {
  3253. $nodes[$nid]->name = $user_fields[$uid]->name;
  3254. $nodes[$nid]->picture = $user_fields[$uid]->picture;
  3255. $nodes[$nid]->data = $user_fields[$uid]->data;
  3256. }
  3257. }
  3258. /**
  3259. * Implements hook_image_style_delete().
  3260. */
  3261. function user_image_style_delete($style) {
  3262. // If a style is deleted, update the variables.
  3263. // Administrators choose a replacement style when deleting.
  3264. user_image_style_save($style);
  3265. }
  3266. /**
  3267. * Implements hook_image_style_save().
  3268. */
  3269. function user_image_style_save($style) {
  3270. // If a style is renamed, update the variables that use it.
  3271. if (isset($style['old_name']) && $style['old_name'] == variable_get('user_picture_style', '')) {
  3272. variable_set('user_picture_style', $style['name']);
  3273. }
  3274. }
  3275. /**
  3276. * Implements hook_action_info().
  3277. */
  3278. function user_action_info() {
  3279. return array(
  3280. 'user_block_user_action' => array(
  3281. 'label' => t('Block current user'),
  3282. 'type' => 'user',
  3283. 'configurable' => FALSE,
  3284. 'triggers' => array('any'),
  3285. ),
  3286. );
  3287. }
  3288. /**
  3289. * Blocks the current user.
  3290. *
  3291. * @ingroup actions
  3292. */
  3293. function user_block_user_action(&$entity, $context = array()) {
  3294. // First priority: If there is a $entity->uid, block that user.
  3295. // This is most likely a user object or the author if a node or comment.
  3296. if (isset($entity->uid)) {
  3297. $uid = $entity->uid;
  3298. }
  3299. elseif (isset($context['uid'])) {
  3300. $uid = $context['uid'];
  3301. }
  3302. // If neither of those are valid, then block the current user.
  3303. else {
  3304. $uid = $GLOBALS['user']->uid;
  3305. }
  3306. $account = user_load($uid);
  3307. $account = user_save($account, array('status' => 0));
  3308. watchdog('action', 'Blocked user %name.', array('%name' => $account->name));
  3309. }
  3310. /**
  3311. * Implements hook_form_FORM_ID_alter().
  3312. *
  3313. * Add a checkbox for the 'user_register_form' instance settings on the 'Edit
  3314. * field instance' form.
  3315. */
  3316. function user_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  3317. $instance = $form['#instance'];
  3318. if ($instance['entity_type'] == 'user') {
  3319. $form['instance']['settings']['user_register_form'] = array(
  3320. '#type' => 'checkbox',
  3321. '#title' => t('Display on user registration form.'),
  3322. '#description' => t("This is compulsory for 'required' fields."),
  3323. // Field instances created in D7 beta releases before the setting was
  3324. // introduced might be set as 'required' and 'not shown on user_register
  3325. // form'. We make sure the checkbox comes as 'checked' for those.
  3326. '#default_value' => $instance['settings']['user_register_form'] || $instance['required'],
  3327. // Display just below the 'required' checkbox.
  3328. '#weight' => $form['instance']['required']['#weight'] + .1,
  3329. // Disabled when the 'required' checkbox is checked.
  3330. '#states' => array(
  3331. 'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)),
  3332. ),
  3333. // Checked when the 'required' checkbox is checked. This is done through
  3334. // a custom behavior, since the #states system would also synchronize on
  3335. // uncheck.
  3336. '#attached' => array(
  3337. 'js' => array(drupal_get_path('module', 'user') . '/user.js'),
  3338. ),
  3339. );
  3340. array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
  3341. }
  3342. }
  3343. /**
  3344. * Additional submit handler for the 'Edit field instance' form.
  3345. *
  3346. * Make sure the 'user_register_form' setting is set for required fields.
  3347. */
  3348. function user_form_field_ui_field_edit_form_submit($form, &$form_state) {
  3349. $instance = $form_state['values']['instance'];
  3350. if (!empty($instance['required'])) {
  3351. form_set_value($form['instance']['settings']['user_register_form'], 1, $form_state);
  3352. }
  3353. }
  3354. /**
  3355. * Form builder; the user registration form.
  3356. *
  3357. * @ingroup forms
  3358. * @see user_account_form()
  3359. * @see user_account_form_validate()
  3360. * @see user_register_submit()
  3361. */
  3362. function user_register_form($form, &$form_state) {
  3363. global $user;
  3364. $admin = user_access('administer users');
  3365. // Pass access information to the submit handler. Running an access check
  3366. // inside the submit function interferes with form processing and breaks
  3367. // hook_form_alter().
  3368. $form['administer_users'] = array(
  3369. '#type' => 'value',
  3370. '#value' => $admin,
  3371. );
  3372. // If we aren't admin but already logged on, go to the user page instead.
  3373. if (!$admin && $user->uid) {
  3374. drupal_goto('user/' . $user->uid);
  3375. }
  3376. $form['#user'] = drupal_anonymous_user();
  3377. $form['#user_category'] = 'register';
  3378. $form['#attached']['library'][] = array('system', 'jquery.cookie');
  3379. $form['#attributes']['class'][] = 'user-info-from-cookie';
  3380. // Start with the default user account fields.
  3381. user_account_form($form, $form_state);
  3382. // Attach field widgets, and hide the ones where the 'user_register_form'
  3383. // setting is not on.
  3384. $langcode = entity_language('user', $form['#user']);
  3385. field_attach_form('user', $form['#user'], $form, $form_state, $langcode);
  3386. foreach (field_info_instances('user', 'user') as $field_name => $instance) {
  3387. if (empty($instance['settings']['user_register_form'])) {
  3388. $form[$field_name]['#access'] = FALSE;
  3389. }
  3390. }
  3391. if ($admin) {
  3392. // Redirect back to page which initiated the create request;
  3393. // usually admin/people/create.
  3394. $form_state['redirect'] = $_GET['q'];
  3395. }
  3396. $form['actions'] = array('#type' => 'actions');
  3397. $form['actions']['submit'] = array(
  3398. '#type' => 'submit',
  3399. '#value' => t('Create new account'),
  3400. );
  3401. $form['#validate'][] = 'user_register_validate';
  3402. // Add the final user registration form submit handler.
  3403. $form['#submit'][] = 'user_register_submit';
  3404. return $form;
  3405. }
  3406. /**
  3407. * Validation function for the user registration form.
  3408. */
  3409. function user_register_validate($form, &$form_state) {
  3410. entity_form_field_validate('user', $form, $form_state);
  3411. }
  3412. /**
  3413. * Submit handler for the user registration form.
  3414. *
  3415. * This function is shared by the installation form and the normal registration form,
  3416. * which is why it can't be in the user.pages.inc file.
  3417. *
  3418. * @see user_register_form()
  3419. */
  3420. function user_register_submit($form, &$form_state) {
  3421. $admin = $form_state['values']['administer_users'];
  3422. if (!variable_get('user_email_verification', TRUE) || $admin) {
  3423. $pass = $form_state['values']['pass'];
  3424. }
  3425. else {
  3426. $pass = user_password();
  3427. }
  3428. $notify = !empty($form_state['values']['notify']);
  3429. // Remove unneeded values.
  3430. form_state_values_clean($form_state);
  3431. $form_state['values']['pass'] = $pass;
  3432. $form_state['values']['init'] = $form_state['values']['mail'];
  3433. $account = $form['#user'];
  3434. entity_form_submit_build_entity('user', $account, $form, $form_state);
  3435. // Populate $edit with the properties of $account, which have been edited on
  3436. // this form by taking over all values, which appear in the form values too.
  3437. $edit = array_intersect_key((array) $account, $form_state['values']);
  3438. $account = user_save($account, $edit);
  3439. // Terminate if an error occurred during user_save().
  3440. if (!$account) {
  3441. drupal_set_message(t("Error saving user account."), 'error');
  3442. $form_state['redirect'] = '';
  3443. return;
  3444. }
  3445. $form_state['user'] = $account;
  3446. $form_state['values']['uid'] = $account->uid;
  3447. watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));
  3448. // Add plain text password into user account to generate mail tokens.
  3449. $account->password = $pass;
  3450. // New administrative account without notification.
  3451. $uri = entity_uri('user', $account);
  3452. if ($admin && !$notify) {
  3453. drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
  3454. }
  3455. // No e-mail verification required; log in user immediately.
  3456. elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
  3457. _user_mail_notify('register_no_approval_required', $account);
  3458. $form_state['uid'] = $account->uid;
  3459. user_login_submit(array(), $form_state);
  3460. drupal_set_message(t('Registration successful. You are now logged in.'));
  3461. $form_state['redirect'] = '';
  3462. }
  3463. // No administrator approval required.
  3464. elseif ($account->status || $notify) {
  3465. $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
  3466. _user_mail_notify($op, $account);
  3467. if ($notify) {
  3468. drupal_set_message(t('A welcome message with further instructions has been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url($uri['path'], $uri['options']), '%name' => $account->name)));
  3469. }
  3470. else {
  3471. drupal_set_message(t('A welcome message with further instructions has been sent to your e-mail address.'));
  3472. $form_state['redirect'] = '';
  3473. }
  3474. }
  3475. // Administrator approval required.
  3476. else {
  3477. _user_mail_notify('register_pending_approval', $account);
  3478. drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.'));
  3479. $form_state['redirect'] = '';
  3480. }
  3481. }
  3482. /**
  3483. * Implements hook_modules_installed().
  3484. */
  3485. function user_modules_installed($modules) {
  3486. // Assign all available permissions to the administrator role.
  3487. $rid = variable_get('user_admin_role', 0);
  3488. if ($rid) {
  3489. $permissions = array();
  3490. foreach ($modules as $module) {
  3491. if ($module_permissions = module_invoke($module, 'permission')) {
  3492. $permissions = array_merge($permissions, array_keys($module_permissions));
  3493. }
  3494. }
  3495. if (!empty($permissions)) {
  3496. user_role_grant_permissions($rid, $permissions);
  3497. }
  3498. }
  3499. }
  3500. /**
  3501. * Implements hook_modules_uninstalled().
  3502. */
  3503. function user_modules_uninstalled($modules) {
  3504. db_delete('role_permission')
  3505. ->condition('module', $modules, 'IN')
  3506. ->execute();
  3507. }
  3508. /**
  3509. * Helper function to rewrite the destination to avoid redirecting to login page after login.
  3510. *
  3511. * Third-party authentication modules may use this function to determine the
  3512. * proper destination after a user has been properly logged in.
  3513. */
  3514. function user_login_destination() {
  3515. $destination = drupal_get_destination();
  3516. if ($destination['destination'] == 'user/login') {
  3517. $destination['destination'] = 'user';
  3518. }
  3519. return $destination;
  3520. }
  3521. /**
  3522. * Saves visitor information as a cookie so it can be reused.
  3523. *
  3524. * @param $values
  3525. * An array of key/value pairs to be saved into a cookie.
  3526. */
  3527. function user_cookie_save(array $values) {
  3528. foreach ($values as $field => $value) {
  3529. // Set cookie for 365 days.
  3530. setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  3531. }
  3532. }
  3533. /**
  3534. * Delete a visitor information cookie.
  3535. *
  3536. * @param $cookie_name
  3537. * A cookie name such as 'homepage'.
  3538. */
  3539. function user_cookie_delete($cookie_name) {
  3540. setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
  3541. }
  3542. /**
  3543. * Implements hook_rdf_mapping().
  3544. */
  3545. function user_rdf_mapping() {
  3546. return array(
  3547. array(
  3548. 'type' => 'user',
  3549. 'bundle' => RDF_DEFAULT_BUNDLE,
  3550. 'mapping' => array(
  3551. 'rdftype' => array('sioc:UserAccount'),
  3552. 'name' => array(
  3553. 'predicates' => array('foaf:name'),
  3554. ),
  3555. 'homepage' => array(
  3556. 'predicates' => array('foaf:page'),
  3557. 'type' => 'rel',
  3558. ),
  3559. ),
  3560. ),
  3561. );
  3562. }
  3563. /**
  3564. * Implements hook_file_download_access().
  3565. */
  3566. function user_file_download_access($field, $entity_type, $entity) {
  3567. if ($entity_type == 'user') {
  3568. return user_view_access($entity);
  3569. }
  3570. }
  3571. /**
  3572. * Implements hook_system_info_alter().
  3573. *
  3574. * Drupal 7 ships with two methods to add additional fields to users: Profile
  3575. * module, a legacy module dating back from 2002, and Field API integration
  3576. * with users. While Field API support for users currently provides less end
  3577. * user features, the inefficient data storage mechanism of Profile module, as
  3578. * well as its lack of consistency with the rest of the entity / field based
  3579. * systems in Drupal 7, make this a sub-optimal solution to those who were not
  3580. * using it in previous releases of Drupal.
  3581. *
  3582. * To prevent new Drupal 7 sites from installing Profile module, and
  3583. * unwittingly ending up with two completely different and incompatible methods
  3584. * of extending users, only make the Profile module available if the profile_*
  3585. * tables are present.
  3586. *
  3587. * @todo: Remove in D8, pending upgrade path.
  3588. */
  3589. function user_system_info_alter(&$info, $file, $type) {
  3590. if ($type == 'module' && $file->name == 'profile' && db_table_exists('profile_field')) {
  3591. $info['hidden'] = FALSE;
  3592. }
  3593. }