user.module 142 KB

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