user.module 139 KB

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