Profile-Modify.php 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834
  1. <?php
  2. /**
  3. * This file has the primary job of showing and editing people's profiles.
  4. * It also allows the user to change some of their or another's preferences,
  5. * and such things
  6. *
  7. * Simple Machines Forum (SMF)
  8. *
  9. * @package SMF
  10. * @author Simple Machines http://www.simplemachines.org
  11. * @copyright 2014 Simple Machines and individual contributors
  12. * @license http://www.simplemachines.org/about/smf/license.php BSD
  13. *
  14. * @version 2.1 Alpha 1
  15. */
  16. if (!defined('SMF'))
  17. die('No direct access...');
  18. /**
  19. * This defines every profile field known to man.
  20. *
  21. * @param bool $force_reload = false
  22. */
  23. function loadProfileFields($force_reload = false)
  24. {
  25. global $context, $profile_fields, $txt, $scripturl, $modSettings, $user_info, $old_profile, $smcFunc, $cur_profile, $language;
  26. // Don't load this twice!
  27. if (!empty($profile_fields) && !$force_reload)
  28. return;
  29. /* This horrific array defines all the profile fields in the whole world!
  30. In general each "field" has one array - the key of which is the database column name associated with said field. Each item
  31. can have the following attributes:
  32. string $type: The type of field this is - valid types are:
  33. - callback: This is a field which has its own callback mechanism for templating.
  34. - check: A simple checkbox.
  35. - hidden: This doesn't have any visual aspects but may have some validity.
  36. - password: A password box.
  37. - select: A select box.
  38. - text: A string of some description.
  39. string $label: The label for this item - default will be $txt[$key] if this isn't set.
  40. string $subtext: The subtext (Small label) for this item.
  41. int $size: Optional size for a text area.
  42. array $input_attr: An array of text strings to be added to the input box for this item.
  43. string $value: The value of the item. If not set $cur_profile[$key] is assumed.
  44. string $permission: Permission required for this item (Excluded _any/_own subfix which is applied automatically).
  45. function $input_validate: A runtime function which validates the element before going to the database. It is passed
  46. the relevant $_POST element if it exists and should be treated like a reference.
  47. Return types:
  48. - true: Element can be stored.
  49. - false: Skip this element.
  50. - a text string: An error occured - this is the error message.
  51. function $preload: A function that is used to load data required for this element to be displayed. Must return
  52. true to be displayed at all.
  53. string $cast_type: If set casts the element to a certain type. Valid types (bool, int, float).
  54. string $save_key: If the index of this element isn't the database column name it can be overriden
  55. with this string.
  56. bool $is_dummy: If set then nothing is acted upon for this element.
  57. bool $enabled: A test to determine whether this is even available - if not is unset.
  58. string $link_with: Key which links this field to an overall set.
  59. Note that all elements that have a custom input_validate must ensure they set the value of $cur_profile correct to enable
  60. the changes to be displayed correctly on submit of the form.
  61. */
  62. $profile_fields = array(
  63. 'aim' => array(
  64. 'type' => 'text',
  65. 'label' => $txt['aim'],
  66. 'subtext' => $txt['your_aim'],
  67. 'size' => 24,
  68. 'value' => strtr(empty($cur_profile['aim']) ? '' : $cur_profile['aim'], '+', ' '),
  69. 'permission' => 'profile_extra',
  70. 'input_validate' => create_function('&$value', '
  71. $value = strtr($value, \' \', \'+\');
  72. if (strlen($value) > 32)
  73. return \'aim_too_long\';
  74. return true;
  75. '),
  76. ),
  77. 'avatar_choice' => array(
  78. 'type' => 'callback',
  79. 'callback_func' => 'avatar_select',
  80. // This handles the permissions too.
  81. 'preload' => 'profileLoadAvatarData',
  82. 'input_validate' => 'profileSaveAvatarData',
  83. 'save_key' => 'avatar',
  84. ),
  85. 'bday1' => array(
  86. 'type' => 'callback',
  87. 'callback_func' => 'birthdate',
  88. 'permission' => 'profile_extra',
  89. 'preload' => create_function('', '
  90. global $cur_profile, $context;
  91. // Split up the birthdate....
  92. list ($uyear, $umonth, $uday) = explode(\'-\', empty($cur_profile[\'birthdate\']) || $cur_profile[\'birthdate\'] == \'0001-01-01\' ? \'0000-00-00\' : $cur_profile[\'birthdate\']);
  93. $context[\'member\'][\'birth_date\'] = array(
  94. \'year\' => $uyear == \'0004\' ? \'0000\' : $uyear,
  95. \'month\' => $umonth,
  96. \'day\' => $uday,
  97. );
  98. return true;
  99. '),
  100. 'input_validate' => create_function('&$value', '
  101. global $profile_vars, $cur_profile;
  102. if (isset($_POST[\'bday2\'], $_POST[\'bday3\']) && $value > 0 && $_POST[\'bday2\'] > 0)
  103. {
  104. // Set to blank?
  105. if ((int) $_POST[\'bday3\'] == 1 && (int) $_POST[\'bday2\'] == 1 && (int) $value == 1)
  106. $value = \'0001-01-01\';
  107. else
  108. $value = checkdate($value, $_POST[\'bday2\'], $_POST[\'bday3\'] < 4 ? 4 : $_POST[\'bday3\']) ? sprintf(\'%04d-%02d-%02d\', $_POST[\'bday3\'] < 4 ? 4 : $_POST[\'bday3\'], $_POST[\'bday1\'], $_POST[\'bday2\']) : \'0001-01-01\';
  109. }
  110. else
  111. $value = \'0001-01-01\';
  112. $profile_vars[\'birthdate\'] = $value;
  113. $cur_profile[\'birthdate\'] = $value;
  114. return false;
  115. '),
  116. ),
  117. // Setting the birthdate the old style way?
  118. 'birthdate' => array(
  119. 'type' => 'hidden',
  120. 'permission' => 'profile_extra',
  121. 'input_validate' => create_function('&$value', '
  122. global $cur_profile;
  123. // @todo Should we check for this year and tell them they made a mistake :P? (based on coppa at least?)
  124. if (preg_match(\'/(\d{4})[\-\., ](\d{2})[\-\., ](\d{2})/\', $value, $dates) === 1)
  125. {
  126. $value = checkdate($dates[2], $dates[3], $dates[1] < 4 ? 4 : $dates[1]) ? sprintf(\'%04d-%02d-%02d\', $dates[1] < 4 ? 4 : $dates[1], $dates[2], $dates[3]) : \'0001-01-01\';
  127. return true;
  128. }
  129. else
  130. {
  131. $value = empty($cur_profile[\'birthdate\']) ? \'0001-01-01\' : $cur_profile[\'birthdate\'];
  132. return false;
  133. }
  134. '),
  135. ),
  136. 'date_registered' => array(
  137. 'type' => 'date',
  138. 'value' => empty($cur_profile['date_registered']) ? $txt['not_applicable'] : strftime('%Y-%m-%d', $cur_profile['date_registered'] + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600),
  139. 'label' => $txt['date_registered'],
  140. 'log_change' => true,
  141. 'permission' => 'moderate_forum',
  142. 'input_validate' => create_function('&$value', '
  143. global $txt, $user_info, $modSettings, $cur_profile, $context;
  144. // Bad date! Go try again - please?
  145. if (($value = strtotime($value)) === -1)
  146. {
  147. $value = $cur_profile[\'date_registered\'];
  148. return $txt[\'invalid_registration\'] . \' \' . strftime(\'%d %b %Y \' . (strpos($user_info[\'time_format\'], \'%H\') !== false ? \'%I:%M:%S %p\' : \'%H:%M:%S\'), forum_time(false));
  149. }
  150. // As long as it doesn\'t equal "N/A"...
  151. elseif ($value != $txt[\'not_applicable\'] && $value != strtotime(strftime(\'%Y-%m-%d\', $cur_profile[\'date_registered\'] + ($user_info[\'time_offset\'] + $modSettings[\'time_offset\']) * 3600)))
  152. $value = $value - ($user_info[\'time_offset\'] + $modSettings[\'time_offset\']) * 3600;
  153. else
  154. $value = $cur_profile[\'date_registered\'];
  155. return true;
  156. '),
  157. ),
  158. 'email_address' => array(
  159. 'type' => 'email',
  160. 'label' => $txt['user_email_address'],
  161. 'subtext' => $txt['valid_email'],
  162. 'log_change' => true,
  163. 'permission' => 'profile_password',
  164. 'js_submit' => !empty($modSettings['send_validation_onChange']) ? '
  165. form_handle.addEventListener(\'submit\', function(event)
  166. {
  167. if (this.email_address.value != "'. $cur_profile['email_address'] .'")
  168. {
  169. alert('. JavaScriptEscape($txt['email_change_logout']) .');
  170. return true;
  171. }
  172. }, false);' : '',
  173. 'input_validate' => create_function('&$value', '
  174. global $context, $old_profile, $profile_vars, $sourcedir, $modSettings;
  175. if (strtolower($value) == strtolower($old_profile[\'email_address\']))
  176. return false;
  177. $isValid = profileValidateEmail($value, $context[\'id_member\']);
  178. // Do they need to revalidate? If so schedule the function!
  179. if ($isValid === true && !empty($modSettings[\'send_validation_onChange\']) && !allowedTo(\'moderate_forum\'))
  180. {
  181. require_once($sourcedir . \'/Subs-Members.php\');
  182. $profile_vars[\'validation_code\'] = generateValidationCode();
  183. $profile_vars[\'is_activated\'] = 2;
  184. $context[\'profile_execute_on_save\'][] = \'profileSendActivation\';
  185. unset($context[\'profile_execute_on_save\'][\'reload_user\']);
  186. }
  187. return $isValid;
  188. '),
  189. ),
  190. 'gender' => array(
  191. 'type' => 'select',
  192. 'cast_type' => 'int',
  193. 'options' => 'return array(0 => \'\', 1 => $txt[\'male\'], 2 => $txt[\'female\']);',
  194. 'label' => $txt['gender'],
  195. 'permission' => 'profile_extra',
  196. ),
  197. 'hide_email' => array(
  198. 'type' => 'check',
  199. 'value' => empty($cur_profile['hide_email']) ? true : false,
  200. 'label' => $txt['allow_user_email'],
  201. 'permission' => 'profile_identity',
  202. 'input_validate' => create_function('&$value', '
  203. $value = $value == 0 ? 1 : 0;
  204. return true;
  205. '),
  206. ),
  207. 'icq' => array(
  208. 'type' => 'text',
  209. 'label' => $txt['icq'],
  210. 'subtext' => $txt['your_icq'],
  211. 'size' => 24,
  212. 'permission' => 'profile_extra',
  213. // Need to make sure ICQ doesn't equal 0.
  214. 'input_validate' => create_function('&$value', '
  215. if (empty($value))
  216. $value = \'\';
  217. else
  218. $value = (int) $value;
  219. return true;
  220. '),
  221. ),
  222. // Selecting group membership is a complicated one so we treat it separate!
  223. 'id_group' => array(
  224. 'type' => 'callback',
  225. 'callback_func' => 'group_manage',
  226. 'permission' => 'manage_membergroups',
  227. 'preload' => 'profileLoadGroups',
  228. 'log_change' => true,
  229. 'input_validate' => 'profileSaveGroups',
  230. ),
  231. 'id_theme' => array(
  232. 'type' => 'callback',
  233. 'callback_func' => 'theme_pick',
  234. 'permission' => 'profile_extra',
  235. 'enabled' => $modSettings['theme_allow'] || allowedTo('admin_forum'),
  236. 'preload' => create_function('', '
  237. global $smcFunc, $context, $cur_profile, $txt;
  238. $request = $smcFunc[\'db_query\'](\'\', \'
  239. SELECT value
  240. FROM {db_prefix}themes
  241. WHERE id_theme = {int:id_theme}
  242. AND variable = {string:variable}
  243. LIMIT 1\', array(
  244. \'id_theme\' => $cur_profile[\'id_theme\'],
  245. \'variable\' => \'name\',
  246. )
  247. );
  248. list ($name) = $smcFunc[\'db_fetch_row\']($request);
  249. $smcFunc[\'db_free_result\']($request);
  250. $context[\'member\'][\'theme\'] = array(
  251. \'id\' => $cur_profile[\'id_theme\'],
  252. \'name\' => empty($cur_profile[\'id_theme\']) ? $txt[\'theme_forum_default\'] : $name
  253. );
  254. return true;
  255. '),
  256. 'input_validate' => create_function('&$value', '
  257. $value = (int) $value;
  258. return true;
  259. '),
  260. ),
  261. 'karma_good' => array(
  262. 'type' => 'callback',
  263. 'callback_func' => 'karma_modify',
  264. 'permission' => 'admin_forum',
  265. // Set karma_bad too!
  266. 'input_validate' => create_function('&$value', '
  267. global $profile_vars, $cur_profile;
  268. $value = (int) $value;
  269. if (isset($_POST[\'karma_bad\']))
  270. {
  271. $profile_vars[\'karma_bad\'] = $_POST[\'karma_bad\'] != \'\' ? (int) $_POST[\'karma_bad\'] : 0;
  272. $cur_profile[\'karma_bad\'] = $_POST[\'karma_bad\'] != \'\' ? (int) $_POST[\'karma_bad\'] : 0;
  273. }
  274. return true;
  275. '),
  276. 'preload' => create_function('', '
  277. global $context, $cur_profile;
  278. $context[\'member\'][\'karma\'][\'good\'] = $cur_profile[\'karma_good\'];
  279. $context[\'member\'][\'karma\'][\'bad\'] = $cur_profile[\'karma_bad\'];
  280. return true;
  281. '),
  282. 'enabled' => !empty($modSettings['karmaMode']),
  283. ),
  284. 'lngfile' => array(
  285. 'type' => 'select',
  286. 'options' => 'return $context[\'profile_languages\'];',
  287. 'label' => $txt['preferred_language'],
  288. 'permission' => 'profile_identity',
  289. 'preload' => 'profileLoadLanguages',
  290. 'enabled' => !empty($modSettings['userLanguage']),
  291. 'value' => empty($cur_profile['lngfile']) ? $language : $cur_profile['lngfile'],
  292. 'input_validate' => create_function('&$value', '
  293. global $context, $cur_profile;
  294. // Load the languages.
  295. profileLoadLanguages();
  296. if (isset($context[\'profile_languages\'][$value]))
  297. {
  298. if ($context[\'user\'][\'is_owner\'] && empty($context[\'password_auth_failed\']))
  299. $_SESSION[\'language\'] = $value;
  300. return true;
  301. }
  302. else
  303. {
  304. $value = $cur_profile[\'lngfile\'];
  305. return false;
  306. }
  307. '),
  308. ),
  309. 'location' => array(
  310. 'type' => 'text',
  311. 'label' => $txt['location'],
  312. 'log_change' => true,
  313. 'size' => 50,
  314. 'permission' => 'profile_other',
  315. ),
  316. // The username is not always editable - so adjust it as such.
  317. 'member_name' => array(
  318. 'type' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? 'text' : 'label',
  319. 'label' => $txt['username'],
  320. 'subtext' => allowedTo('admin_forum') && !isset($_GET['changeusername']) ? '[<a href="' . $scripturl . '?action=profile;u=' . $context['id_member'] . ';area=account;changeusername" style="font-style: italic;">' . $txt['username_change'] . '</a>]' : '',
  321. 'log_change' => true,
  322. 'permission' => 'profile_identity',
  323. 'prehtml' => allowedTo('admin_forum') && isset($_GET['changeusername']) ? '<div class="alert">' . $txt['username_warning'] . '</div>' : '',
  324. 'input_validate' => create_function('&$value', '
  325. global $sourcedir, $context, $user_info, $cur_profile;
  326. if (allowedTo(\'admin_forum\'))
  327. {
  328. // We\'ll need this...
  329. require_once($sourcedir . \'/Subs-Auth.php\');
  330. // Maybe they are trying to change their password as well?
  331. $resetPassword = true;
  332. if (isset($_POST[\'passwrd1\']) && $_POST[\'passwrd1\'] != \'\' && isset($_POST[\'passwrd2\']) && $_POST[\'passwrd1\'] == $_POST[\'passwrd2\'] && validatePassword($_POST[\'passwrd1\'], $value, array($cur_profile[\'real_name\'], $user_info[\'username\'], $user_info[\'name\'], $user_info[\'email\'])) == null)
  333. $resetPassword = false;
  334. // Do the reset... this will send them an email too.
  335. if ($resetPassword)
  336. resetPassword($context[\'id_member\'], $value);
  337. elseif ($value !== null)
  338. {
  339. validateUsername($context[\'id_member\'], trim(preg_replace(\'~[\t\n\r \x0B\0\' . ($context[\'utf8\'] ? \'\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}\' : \'\x00-\x08\x0B\x0C\x0E-\x19\xA0\') . \']+~\' . ($context[\'utf8\'] ? \'u\' : \'\'), \' \', $value)));
  340. updateMemberData($context[\'id_member\'], array(\'member_name\' => $value));
  341. }
  342. }
  343. return false;
  344. '),
  345. ),
  346. 'skype' => array(
  347. 'type' => 'text',
  348. 'label' => $txt['skype'],
  349. 'subtext' => $txt['skype_username'],
  350. 'size' => 24,
  351. 'permission' => 'profile_extra',
  352. ),
  353. 'passwrd1' => array(
  354. 'type' => 'password',
  355. 'label' => ucwords($txt['choose_pass']),
  356. 'subtext' => $txt['password_strength'],
  357. 'size' => 20,
  358. 'value' => '',
  359. 'enabled' => empty($cur_profile['openid_uri']),
  360. 'permission' => 'profile_password',
  361. 'save_key' => 'passwd',
  362. // Note this will only work if passwrd2 also exists!
  363. 'input_validate' => create_function('&$value', '
  364. global $sourcedir, $user_info, $smcFunc, $cur_profile;
  365. // If we didn\'t try it then ignore it!
  366. if ($value == \'\')
  367. return false;
  368. // Do the two entries for the password even match?
  369. if (!isset($_POST[\'passwrd2\']) || $value != $_POST[\'passwrd2\'])
  370. return \'bad_new_password\';
  371. // Let\'s get the validation function into play...
  372. require_once($sourcedir . \'/Subs-Auth.php\');
  373. $passwordErrors = validatePassword($value, $cur_profile[\'member_name\'], array($cur_profile[\'real_name\'], $user_info[\'username\'], $user_info[\'name\'], $user_info[\'email\']));
  374. // Were there errors?
  375. if ($passwordErrors != null)
  376. return \'password_\' . $passwordErrors;
  377. // Set up the new password variable... ready for storage.
  378. $value = sha1(strtolower($cur_profile[\'member_name\']) . un_htmlspecialchars($value));
  379. return true;
  380. '),
  381. ),
  382. 'passwrd2' => array(
  383. 'type' => 'password',
  384. 'label' => ucwords($txt['verify_pass']),
  385. 'enabled' => empty($cur_profile['openid_uri']),
  386. 'size' => 20,
  387. 'value' => '',
  388. 'permission' => 'profile_password',
  389. 'is_dummy' => true,
  390. ),
  391. 'personal_text' => array(
  392. 'type' => 'text',
  393. 'label' => $txt['personal_text'],
  394. 'log_change' => true,
  395. 'input_attr' => array('maxlength="50"'),
  396. 'size' => 50,
  397. 'permission' => 'profile_blurb',
  398. 'input_validate' => create_function('&$value', '
  399. global $smcFunc;
  400. if ($smcFunc[\'strlen\']($value) > 50)
  401. return \'personal_text_too_long\';
  402. return true;
  403. '),
  404. ),
  405. // This does ALL the pm settings
  406. 'pm_prefs' => array(
  407. 'type' => 'callback',
  408. 'callback_func' => 'pm_settings',
  409. 'permission' => 'pm_read',
  410. 'preload' => create_function('', '
  411. global $context, $cur_profile;
  412. $context[\'display_mode\'] = $cur_profile[\'pm_prefs\'] & 3;
  413. $context[\'send_email\'] = $cur_profile[\'pm_email_notify\'];
  414. $context[\'receive_from\'] = !empty($cur_profile[\'pm_receive_from\']) ? $cur_profile[\'pm_receive_from\'] : 0;
  415. return true;
  416. '),
  417. 'input_validate' => create_function('&$value', '
  418. global $cur_profile, $profile_vars;
  419. // Simple validate and apply the two "sub settings"
  420. $value = max(min($value, 2), 0);
  421. $cur_profile[\'pm_email_notify\'] = $profile_vars[\'pm_email_notify\'] = max(min((int) $_POST[\'pm_email_notify\'], 2), 0);
  422. $cur_profile[\'pm_receive_from\'] = $profile_vars[\'pm_receive_from\'] = max(min((int) $_POST[\'pm_receive_from\'], 4), 0);
  423. return true;
  424. '),
  425. ),
  426. 'posts' => array(
  427. 'type' => 'int',
  428. 'label' => $txt['profile_posts'],
  429. 'log_change' => true,
  430. 'size' => 7,
  431. 'permission' => 'moderate_forum',
  432. 'input_validate' => create_function('&$value', '
  433. if (!is_numeric($value))
  434. return \'digits_only\';
  435. else
  436. $value = $value != \'\' ? strtr($value, array(\',\' => \'\', \'.\' => \'\', \' \' => \'\')) : 0;
  437. return true;
  438. '),
  439. ),
  440. 'real_name' => array(
  441. 'type' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum') ? 'text' : 'label',
  442. 'label' => $txt['name'],
  443. 'subtext' => $txt['display_name_desc'],
  444. 'log_change' => true,
  445. 'input_attr' => array('maxlength="60"'),
  446. 'permission' => 'profile_displayed_name',
  447. 'enabled' => allowedTo('profile_displayed_name_own') || allowedTo('profile_displayed_name_any') || allowedTo('moderate_forum'),
  448. 'input_validate' => create_function('&$value', '
  449. global $context, $smcFunc, $sourcedir, $cur_profile;
  450. $value = trim(preg_replace(\'~[\t\n\r \x0B\0\' . ($context[\'utf8\'] ? \'\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}\' : \'\x00-\x08\x0B\x0C\x0E-\x19\xA0\') . \']+~\' . ($context[\'utf8\'] ? \'u\' : \'\'), \' \', $value));
  451. if (trim($value) == \'\')
  452. return \'no_name\';
  453. elseif ($smcFunc[\'strlen\']($value) > 60)
  454. return \'name_too_long\';
  455. elseif ($cur_profile[\'real_name\'] != $value)
  456. {
  457. require_once($sourcedir . \'/Subs-Members.php\');
  458. if (isReservedName($value, $context[\'id_member\']))
  459. return \'name_taken\';
  460. }
  461. return true;
  462. '),
  463. ),
  464. 'secret_question' => array(
  465. 'type' => 'text',
  466. 'label' => $txt['secret_question'],
  467. 'subtext' => $txt['secret_desc'],
  468. 'size' => 50,
  469. 'permission' => 'profile_password',
  470. ),
  471. 'secret_answer' => array(
  472. 'type' => 'text',
  473. 'label' => $txt['secret_answer'],
  474. 'subtext' => $txt['secret_desc2'],
  475. 'size' => 20,
  476. 'postinput' => '<span class="smalltext" style="margin-left: 4ex;">[<a href="' . $scripturl . '?action=helpadmin;help=secret_why_blank" onclick="return reqOverlayDiv(this.href);">' . $txt['secret_why_blank'] . '</a>]</span>',
  477. 'value' => '',
  478. 'permission' => 'profile_password',
  479. 'input_validate' => create_function('&$value', '
  480. $value = $value != \'\' ? md5($value) : \'\';
  481. return true;
  482. '),
  483. ),
  484. 'signature' => array(
  485. 'type' => 'callback',
  486. 'callback_func' => 'signature_modify',
  487. 'permission' => 'profile_signature',
  488. 'enabled' => substr($modSettings['signature_settings'], 0, 1) == 1,
  489. 'preload' => 'profileLoadSignatureData',
  490. 'input_validate' => 'profileValidateSignature',
  491. ),
  492. 'show_online' => array(
  493. 'type' => 'check',
  494. 'label' => $txt['show_online'],
  495. 'permission' => 'profile_identity',
  496. 'enabled' => !empty($modSettings['allow_hideOnline']) || allowedTo('moderate_forum'),
  497. ),
  498. 'smiley_set' => array(
  499. 'type' => 'callback',
  500. 'callback_func' => 'smiley_pick',
  501. 'enabled' => !empty($modSettings['smiley_sets_enable']),
  502. 'permission' => 'profile_extra',
  503. 'preload' => create_function('', '
  504. global $modSettings, $context, $txt, $cur_profile, $smcFunc;
  505. $context[\'member\'][\'smiley_set\'][\'id\'] = empty($cur_profile[\'smiley_set\']) ? \'\' : $cur_profile[\'smiley_set\'];
  506. $context[\'smiley_sets\'] = explode(\',\', \'none,,\' . $modSettings[\'smiley_sets_known\']);
  507. $set_names = explode("\n", $txt[\'smileys_none\'] . "\n" . $txt[\'smileys_forum_board_default\'] . "\n" . $modSettings[\'smiley_sets_names\']);
  508. foreach ($context[\'smiley_sets\'] as $i => $set)
  509. {
  510. $context[\'smiley_sets\'][$i] = array(
  511. \'id\' => $smcFunc[\'htmlspecialchars\']($set),
  512. \'name\' => $smcFunc[\'htmlspecialchars\']($set_names[$i]),
  513. \'selected\' => $set == $context[\'member\'][\'smiley_set\'][\'id\']
  514. );
  515. if ($context[\'smiley_sets\'][$i][\'selected\'])
  516. $context[\'member\'][\'smiley_set\'][\'name\'] = $set_names[$i];
  517. }
  518. return true;
  519. '),
  520. 'input_validate' => create_function('&$value', '
  521. global $modSettings;
  522. $smiley_sets = explode(\',\', $modSettings[\'smiley_sets_known\']);
  523. if (!in_array($value, $smiley_sets) && $value != \'none\')
  524. $value = \'\';
  525. return true;
  526. '),
  527. ),
  528. // Pretty much a dummy entry - it populates all the theme settings.
  529. 'theme_settings' => array(
  530. 'type' => 'callback',
  531. 'callback_func' => 'theme_settings',
  532. 'permission' => 'profile_extra',
  533. 'is_dummy' => true,
  534. 'preload' => create_function('', '
  535. global $context, $user_info, $modSettings;
  536. loadLanguage(\'Settings\');
  537. $context[\'allow_no_censored\'] = false;
  538. if ($user_info[\'is_admin\'] || $context[\'user\'][\'is_owner\'])
  539. $context[\'allow_no_censored\'] = !empty($modSettings[\'allow_no_censored\']);
  540. return true;
  541. '),
  542. ),
  543. 'time_format' => array(
  544. 'type' => 'callback',
  545. 'callback_func' => 'timeformat_modify',
  546. 'permission' => 'profile_extra',
  547. 'preload' => create_function('', '
  548. global $context, $user_info, $txt, $cur_profile, $modSettings;
  549. $context[\'easy_timeformats\'] = array(
  550. array(\'format\' => \'\', \'title\' => $txt[\'timeformat_default\']),
  551. array(\'format\' => \'%B %d, %Y, %I:%M:%S %p\', \'title\' => $txt[\'timeformat_easy1\']),
  552. array(\'format\' => \'%B %d, %Y, %H:%M:%S\', \'title\' => $txt[\'timeformat_easy2\']),
  553. array(\'format\' => \'%Y-%m-%d, %H:%M:%S\', \'title\' => $txt[\'timeformat_easy3\']),
  554. array(\'format\' => \'%d %B %Y, %H:%M:%S\', \'title\' => $txt[\'timeformat_easy4\']),
  555. array(\'format\' => \'%d-%m-%Y, %H:%M:%S\', \'title\' => $txt[\'timeformat_easy5\'])
  556. );
  557. $context[\'member\'][\'time_format\'] = $cur_profile[\'time_format\'];
  558. $context[\'current_forum_time\'] = timeformat(time() - $user_info[\'time_offset\'] * 3600, false);
  559. $context[\'current_forum_time_js\'] = strftime(\'%Y,\' . ((int) strftime(\'%m\', time() + $modSettings[\'time_offset\'] * 3600) - 1) . \',%d,%H,%M,%S\', time() + $modSettings[\'time_offset\'] * 3600);
  560. $context[\'current_forum_time_hour\'] = (int) strftime(\'%H\', forum_time(false));
  561. return true;
  562. '),
  563. ),
  564. 'time_offset' => array(
  565. 'type' => 'callback',
  566. 'callback_func' => 'timeoffset_modify',
  567. 'permission' => 'profile_extra',
  568. 'preload' => create_function('', '
  569. global $context, $cur_profile;
  570. $context[\'member\'][\'time_offset\'] = $cur_profile[\'time_offset\'];
  571. return true;
  572. '),
  573. 'input_validate' => create_function('&$value', '
  574. // Validate the time_offset...
  575. $value = (float) strtr($value, \',\', \'.\');
  576. if ($value < -23.5 || $value > 23.5)
  577. return \'bad_offset\';
  578. return true;
  579. '),
  580. ),
  581. 'usertitle' => array(
  582. 'type' => 'text',
  583. 'label' => $txt['custom_title'],
  584. 'log_change' => true,
  585. 'input_attr' => array('maxlength="50"'),
  586. 'size' => 50,
  587. 'permission' => 'profile_other',
  588. 'enabled' => !empty($modSettings['titlesEnable']),
  589. 'input_validate' => create_function('&$value', '
  590. global $smcFunc;
  591. if ($smcFunc[\'strlen\']($value) > 50)
  592. return \'user_title_too_long\';
  593. return true;
  594. '),
  595. ),
  596. 'website_title' => array(
  597. 'type' => 'text',
  598. 'label' => $txt['website_title'],
  599. 'subtext' => $txt['include_website_url'],
  600. 'size' => 50,
  601. 'permission' => 'profile_other',
  602. 'link_with' => 'website',
  603. ),
  604. 'website_url' => array(
  605. 'type' => 'url',
  606. 'label' => $txt['website_url'],
  607. 'subtext' => $txt['complete_url'],
  608. 'size' => 50,
  609. 'permission' => 'profile_other',
  610. // Fix the URL...
  611. 'input_validate' => create_function('&$value', '
  612. if (strlen(trim($value)) > 0 && strpos($value, \'://\') === false)
  613. $value = \'http://\' . $value;
  614. if (strlen($value) < 8 || (substr($value, 0, 7) !== \'http://\' && substr($value, 0, 8) !== \'https://\'))
  615. $value = \'\';
  616. return true;
  617. '),
  618. 'link_with' => 'website',
  619. ),
  620. 'yim' => array(
  621. 'type' => 'text',
  622. 'label' => $txt['yim'],
  623. 'subtext' => $txt['your_yim'],
  624. 'size' => 24,
  625. 'input_attr' => array('maxlength="32"'),
  626. 'permission' => 'profile_extra',
  627. ),
  628. );
  629. call_integration_hook('integrate_load_profile_fields', array(&$profile_fields));
  630. $disabled_fields = !empty($modSettings['disabled_profile_fields']) ? explode(',', $modSettings['disabled_profile_fields']) : array();
  631. // For each of the above let's take out the bits which don't apply - to save memory and security!
  632. foreach ($profile_fields as $key => $field)
  633. {
  634. // Do we have permission to do this?
  635. if (isset($field['permission']) && !allowedTo(($context['user']['is_owner'] ? array($field['permission'] . '_own', $field['permission'] . '_any') : $field['permission'] . '_any')) && !allowedTo($field['permission']))
  636. unset($profile_fields[$key]);
  637. // Is it enabled?
  638. if (isset($field['enabled']) && !$field['enabled'])
  639. unset($profile_fields[$key]);
  640. // Is it specifically disabled?
  641. if (in_array($key, $disabled_fields) || (isset($field['link_with']) && in_array($field['link_with'], $disabled_fields)))
  642. unset($profile_fields[$key]);
  643. }
  644. }
  645. /**
  646. * Setup the context for a page load!
  647. *
  648. * @param array $fields
  649. */
  650. function setupProfileContext($fields)
  651. {
  652. global $profile_fields, $context, $cur_profile, $smcFunc, $txt;
  653. // Make sure we have this!
  654. loadProfileFields(true);
  655. // First check for any linked sets.
  656. foreach ($profile_fields as $key => $field)
  657. if (isset($field['link_with']) && in_array($field['link_with'], $fields))
  658. $fields[] = $key;
  659. // Some default bits.
  660. $context['profile_prehtml'] = '';
  661. $context['profile_posthtml'] = '';
  662. $context['profile_javascript'] = '';
  663. $context['profile_onsubmit_javascript'] = '';
  664. $i = 0;
  665. $last_type = '';
  666. foreach ($fields as $key => $field)
  667. {
  668. if (isset($profile_fields[$field]))
  669. {
  670. // Shortcut.
  671. $cur_field = &$profile_fields[$field];
  672. // Does it have a preload and does that preload succeed?
  673. if (isset($cur_field['preload']) && !$cur_field['preload']())
  674. continue;
  675. // If this is anything but complex we need to do more cleaning!
  676. if ($cur_field['type'] != 'callback' && $cur_field['type'] != 'hidden')
  677. {
  678. if (!isset($cur_field['label']))
  679. $cur_field['label'] = isset($txt[$field]) ? $txt[$field] : $field;
  680. // Everything has a value!
  681. if (!isset($cur_field['value']))
  682. {
  683. $cur_field['value'] = isset($cur_profile[$field]) ? $cur_profile[$field] : '';
  684. }
  685. // Any input attributes?
  686. $cur_field['input_attr'] = !empty($cur_field['input_attr']) ? implode(',', $cur_field['input_attr']) : '';
  687. }
  688. // Was there an error with this field on posting?
  689. if (isset($context['profile_errors'][$field]))
  690. $cur_field['is_error'] = true;
  691. // Any javascript stuff?
  692. if (!empty($cur_field['js_submit']))
  693. $context['profile_onsubmit_javascript'] .= $cur_field['js_submit'];
  694. if (!empty($cur_field['js']))
  695. $context['profile_javascript'] .= $cur_field['js'];
  696. // Any template stuff?
  697. if (!empty($cur_field['prehtml']))
  698. $context['profile_prehtml'] .= $cur_field['prehtml'];
  699. if (!empty($cur_field['posthtml']))
  700. $context['profile_posthtml'] .= $cur_field['posthtml'];
  701. // Finally put it into context?
  702. if ($cur_field['type'] != 'hidden')
  703. {
  704. $last_type = $cur_field['type'];
  705. $context['profile_fields'][$field] = &$profile_fields[$field];
  706. }
  707. }
  708. // Bodge in a line break - without doing two in a row ;)
  709. elseif ($field == 'hr' && $last_type != 'hr' && $last_type != '')
  710. {
  711. $last_type = 'hr';
  712. $context['profile_fields'][$i++]['type'] = 'hr';
  713. }
  714. }
  715. // Some spicy JS.
  716. addInlineJavascript('
  717. var form_handle = document.forms.creator;
  718. createEventListener(form_handle);
  719. '. (!empty($context['require_password']) ? '
  720. form_handle.addEventListener(\'submit\', function(event)
  721. {
  722. if (this.oldpasswrd.value == "")
  723. {
  724. event.preventDefault();
  725. alert('. (JavaScriptEscape($txt['required_security_reasons'])) .');
  726. return false;
  727. }
  728. }, false);' : ''), true);
  729. // Any onsubmit javascript?
  730. if (!empty($context['profile_onsubmit_javascript']))
  731. addInlineJavascript($context['profile_onsubmit_javascript'], true);
  732. // Any totally custom stuff?
  733. if (!empty($context['profile_javascript']))
  734. addInlineJavascript($context['profile_javascript'], true);
  735. // Free up some memory.
  736. unset($profile_fields);
  737. }
  738. /**
  739. * Save the profile changes.
  740. */
  741. function saveProfileFields()
  742. {
  743. global $profile_fields, $profile_vars, $context, $old_profile, $post_errors, $sourcedir, $cur_profile, $smcFunc;
  744. // Load them up.
  745. loadProfileFields();
  746. // This makes things easier...
  747. $old_profile = $cur_profile;
  748. // This allows variables to call activities when they save - by default just to reload their settings
  749. $context['profile_execute_on_save'] = array();
  750. if ($context['user']['is_owner'])
  751. $context['profile_execute_on_save']['reload_user'] = 'profileReloadUser';
  752. // Assume we log nothing.
  753. $context['log_changes'] = array();
  754. // Cycle through the profile fields working out what to do!
  755. foreach ($profile_fields as $key => $field)
  756. {
  757. if (!isset($_POST[$key]) || !empty($field['is_dummy']) || (isset($_POST['preview_signature']) && $key == 'signature'))
  758. continue;
  759. // What gets updated?
  760. $db_key = isset($field['save_key']) ? $field['save_key'] : $key;
  761. // Right - we have something that is enabled, we can act upon and has a value posted to it. Does it have a validation function?
  762. if (isset($field['input_validate']))
  763. {
  764. $is_valid = $field['input_validate']($_POST[$key]);
  765. // An error occured - set it as such!
  766. if ($is_valid !== true)
  767. {
  768. // Is this an actual error?
  769. if ($is_valid !== false)
  770. {
  771. $post_errors[$key] = $is_valid;
  772. $profile_fields[$key]['is_error'] = $is_valid;
  773. }
  774. // Retain the old value.
  775. $cur_profile[$key] = $_POST[$key];
  776. continue;
  777. }
  778. }
  779. // Are we doing a cast?
  780. $field['cast_type'] = empty($field['cast_type']) ? $field['type'] : $field['cast_type'];
  781. // Finally, clean up certain types.
  782. if ($field['cast_type'] == 'int')
  783. $_POST[$key] = (int) $_POST[$key];
  784. elseif ($field['cast_type'] == 'float')
  785. $_POST[$key] = (float) $_POST[$key];
  786. elseif ($field['cast_type'] == 'check')
  787. $_POST[$key] = !empty($_POST[$key]) ? 1 : 0;
  788. // If we got here we're doing OK.
  789. if ($field['type'] != 'hidden' && (!isset($old_profile[$key]) || $_POST[$key] != $old_profile[$key]))
  790. {
  791. // Set the save variable.
  792. $profile_vars[$db_key] = $_POST[$key];
  793. // And update the user profile.
  794. $cur_profile[$key] = $_POST[$key];
  795. // Are we logging it?
  796. if (!empty($field['log_change']) && isset($old_profile[$key]))
  797. $context['log_changes'][$key] = array(
  798. 'previous' => $old_profile[$key],
  799. 'new' => $_POST[$key],
  800. );
  801. }
  802. // Logging group changes are a bit different...
  803. if ($key == 'id_group' && $field['log_change'])
  804. {
  805. profileLoadGroups();
  806. // Any changes to primary group?
  807. if ($_POST['id_group'] != $old_profile['id_group'])
  808. {
  809. $context['log_changes']['id_group'] = array(
  810. 'previous' => !empty($old_profile[$key]) && isset($context['member_groups'][$old_profile[$key]]) ? $context['member_groups'][$old_profile[$key]]['name'] : '',
  811. 'new' => !empty($_POST[$key]) && isset($context['member_groups'][$_POST[$key]]) ? $context['member_groups'][$_POST[$key]]['name'] : '',
  812. );
  813. }
  814. // Prepare additional groups for comparison.
  815. $additional_groups = array(
  816. 'previous' => !empty($old_profile['additional_groups']) ? explode(',', $old_profile['additional_groups']) : array(),
  817. 'new' => !empty($_POST['additional_groups']) ? array_diff($_POST['additional_groups'], array(0)) : array(),
  818. );
  819. sort($additional_groups['previous']);
  820. sort($additional_groups['new']);
  821. // What about additional groups?
  822. if ($additional_groups['previous'] != $additional_groups['new'])
  823. {
  824. foreach ($additional_groups as $type => $groups)
  825. {
  826. foreach ($groups as $id => $group)
  827. {
  828. if (isset($context['member_groups'][$group]))
  829. $additional_groups[$type][$id] = $context['member_groups'][$group]['name'];
  830. else
  831. unset($additional_groups[$type][$id]);
  832. }
  833. $additional_groups[$type] = implode(', ', $additional_groups[$type]);
  834. }
  835. $context['log_changes']['additional_groups'] = $additional_groups;
  836. }
  837. }
  838. }
  839. // @todo Temporary
  840. if ($context['user']['is_owner'])
  841. $changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own'));
  842. else
  843. $changeOther = allowedTo('profile_extra_any');
  844. if ($changeOther && empty($post_errors))
  845. {
  846. makeThemeChanges($context['id_member'], isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
  847. if (!empty($_REQUEST['sa']))
  848. makeCustomFieldChanges($context['id_member'], $_REQUEST['sa'], false);
  849. }
  850. // Free memory!
  851. unset($profile_fields);
  852. }
  853. /**
  854. * Save the profile changes
  855. *
  856. * @param array &$profile_variables
  857. * @param array &$post_errors
  858. * @param int $memID id_member
  859. */
  860. function saveProfileChanges(&$profile_vars, &$post_errors, $memID)
  861. {
  862. global $txt, $user_profile;
  863. global $context, $sourcedir;
  864. global $smcFunc;
  865. // These make life easier....
  866. $old_profile = &$user_profile[$memID];
  867. // Permissions...
  868. if ($context['user']['is_owner'])
  869. {
  870. $changeIdentity = allowedTo(array('profile_identity_any', 'profile_identity_own', 'profile_password_any', 'profile_password_own'));
  871. $changeOther = allowedTo(array('profile_extra_any', 'profile_extra_own', 'profile_other_any', 'profile_other_own', 'profile_signature_any', 'profile_signature_own'));
  872. }
  873. else
  874. {
  875. $changeIdentity = allowedTo('profile_identity_any', 'profile_signature_any');
  876. $changeOther = allowedTo('profile_extra_any', 'profile_other_any', 'profile_signature_any');
  877. }
  878. // Arrays of all the changes - makes things easier.
  879. $profile_bools = array(
  880. 'notify_announcements', 'notify_send_body',
  881. );
  882. $profile_ints = array(
  883. 'notify_regularity',
  884. 'notify_types',
  885. );
  886. $profile_floats = array(
  887. );
  888. $profile_strings = array(
  889. 'buddy_list',
  890. 'ignore_boards',
  891. );
  892. if (isset($_POST['sa']) && $_POST['sa'] == 'ignoreboards' && empty($_POST['ignore_brd']))
  893. $_POST['ignore_brd'] = array();
  894. unset($_POST['ignore_boards']); // Whatever it is set to is a dirty fithy thing. Kinda like our minds.
  895. if (isset($_POST['ignore_brd']))
  896. {
  897. if (!is_array($_POST['ignore_brd']))
  898. $_POST['ignore_brd'] = array ($_POST['ignore_brd']);
  899. foreach ($_POST['ignore_brd'] as $k => $d)
  900. {
  901. $d = (int) $d;
  902. if ($d != 0)
  903. $_POST['ignore_brd'][$k] = $d;
  904. else
  905. unset($_POST['ignore_brd'][$k]);
  906. }
  907. $_POST['ignore_boards'] = implode(',', $_POST['ignore_brd']);
  908. unset($_POST['ignore_brd']);
  909. }
  910. // Here's where we sort out all the 'other' values...
  911. if ($changeOther)
  912. {
  913. makeThemeChanges($memID, isset($_POST['id_theme']) ? (int) $_POST['id_theme'] : $old_profile['id_theme']);
  914. //makeAvatarChanges($memID, $post_errors);
  915. if (!empty($_REQUEST['sa']))
  916. makeCustomFieldChanges($memID, $_REQUEST['sa'], false);
  917. foreach ($profile_bools as $var)
  918. if (isset($_POST[$var]))
  919. $profile_vars[$var] = empty($_POST[$var]) ? '0' : '1';
  920. foreach ($profile_ints as $var)
  921. if (isset($_POST[$var]))
  922. $profile_vars[$var] = $_POST[$var] != '' ? (int) $_POST[$var] : '';
  923. foreach ($profile_floats as $var)
  924. if (isset($_POST[$var]))
  925. $profile_vars[$var] = (float) $_POST[$var];
  926. foreach ($profile_strings as $var)
  927. if (isset($_POST[$var]))
  928. $profile_vars[$var] = $_POST[$var];
  929. }
  930. }
  931. /**
  932. * Make any theme changes that are sent with the profile.
  933. *
  934. * @param int $memID
  935. * @param int $id_theme
  936. */
  937. function makeThemeChanges($memID, $id_theme)
  938. {
  939. global $modSettings, $smcFunc, $context, $user_info;
  940. $reservedVars = array(
  941. 'actual_theme_url',
  942. 'actual_images_url',
  943. 'base_theme_dir',
  944. 'base_theme_url',
  945. 'default_images_url',
  946. 'default_theme_dir',
  947. 'default_theme_url',
  948. 'default_template',
  949. 'images_url',
  950. 'number_recent_posts',
  951. 'smiley_sets_default',
  952. 'theme_dir',
  953. 'theme_id',
  954. 'theme_layers',
  955. 'theme_templates',
  956. 'theme_url',
  957. );
  958. // Can't change reserved vars.
  959. if ((isset($_POST['options']) && count(array_intersect(array_keys($_POST['options']), $reservedVars)) != 0) || (isset($_POST['default_options']) && count(array_intersect(array_keys($_POST['default_options']), $reservedVars)) != 0))
  960. fatal_lang_error('no_access', false);
  961. // Don't allow any overriding of custom fields with default or non-default options.
  962. $request = $smcFunc['db_query']('', '
  963. SELECT col_name
  964. FROM {db_prefix}custom_fields
  965. WHERE active = {int:is_active}',
  966. array(
  967. 'is_active' => 1,
  968. )
  969. );
  970. $custom_fields = array();
  971. while ($row = $smcFunc['db_fetch_assoc']($request))
  972. $custom_fields[] = $row['col_name'];
  973. $smcFunc['db_free_result']($request);
  974. // These are the theme changes...
  975. $themeSetArray = array();
  976. if (isset($_POST['options']) && is_array($_POST['options']))
  977. {
  978. foreach ($_POST['options'] as $opt => $val)
  979. {
  980. if (in_array($opt, $custom_fields))
  981. continue;
  982. // These need to be controlled.
  983. if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
  984. $val = max(0, min($val, 50));
  985. // We don't set this per theme anymore.
  986. elseif ($opt == 'allow_no_censored')
  987. continue;
  988. $themeSetArray[] = array($memID, $id_theme, $opt, is_array($val) ? implode(',', $val) : $val);
  989. }
  990. }
  991. $erase_options = array();
  992. if (isset($_POST['default_options']) && is_array($_POST['default_options']))
  993. foreach ($_POST['default_options'] as $opt => $val)
  994. {
  995. if (in_array($opt, $custom_fields))
  996. continue;
  997. // These need to be controlled.
  998. if ($opt == 'topics_per_page' || $opt == 'messages_per_page')
  999. $val = max(0, min($val, 50));
  1000. // Only let admins and owners change the censor.
  1001. elseif ($opt == 'allow_no_censored' && !$user_info['is_admin'] && !$context['user']['is_owner'])
  1002. continue;
  1003. $themeSetArray[] = array($memID, 1, $opt, is_array($val) ? implode(',', $val) : $val);
  1004. $erase_options[] = $opt;
  1005. }
  1006. // If themeSetArray isn't still empty, send it to the database.
  1007. if (empty($context['password_auth_failed']))
  1008. {
  1009. if (!empty($themeSetArray))
  1010. {
  1011. $smcFunc['db_insert']('replace',
  1012. '{db_prefix}themes',
  1013. array('id_member' => 'int', 'id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  1014. $themeSetArray,
  1015. array('id_member', 'id_theme', 'variable')
  1016. );
  1017. }
  1018. if (!empty($erase_options))
  1019. {
  1020. $smcFunc['db_query']('', '
  1021. DELETE FROM {db_prefix}themes
  1022. WHERE id_theme != {int:id_theme}
  1023. AND variable IN ({array_string:erase_variables})
  1024. AND id_member = {int:id_member}',
  1025. array(
  1026. 'id_theme' => 1,
  1027. 'id_member' => $memID,
  1028. 'erase_variables' => $erase_options
  1029. )
  1030. );
  1031. }
  1032. // Admins can choose any theme, even if it's not enabled...
  1033. $themes = allowedTo('admin_forum') ? explode(',', $modSettings['knownThemes']) : explode(',', $modSettings['enableThemes']);
  1034. foreach ($themes as $t)
  1035. cache_put_data('theme_settings-' . $t . ':' . $memID, null, 60);
  1036. }
  1037. }
  1038. /**
  1039. * Make any notification changes that need to be made.
  1040. *
  1041. * @param int $memID id_member
  1042. */
  1043. function makeNotificationChanges($memID)
  1044. {
  1045. global $smcFunc;
  1046. // Update the boards they are being notified on.
  1047. if (isset($_POST['edit_notify_boards']) && !empty($_POST['notify_boards']))
  1048. {
  1049. // Make sure only integers are deleted.
  1050. foreach ($_POST['notify_boards'] as $index => $id)
  1051. $_POST['notify_boards'][$index] = (int) $id;
  1052. // id_board = 0 is reserved for topic notifications.
  1053. $_POST['notify_boards'] = array_diff($_POST['notify_boards'], array(0));
  1054. $smcFunc['db_query']('', '
  1055. DELETE FROM {db_prefix}log_notify
  1056. WHERE id_board IN ({array_int:board_list})
  1057. AND id_member = {int:selected_member}',
  1058. array(
  1059. 'board_list' => $_POST['notify_boards'],
  1060. 'selected_member' => $memID,
  1061. )
  1062. );
  1063. }
  1064. // We are editing topic notifications......
  1065. elseif (isset($_POST['edit_notify_topics']) && !empty($_POST['notify_topics']))
  1066. {
  1067. foreach ($_POST['notify_topics'] as $index => $id)
  1068. $_POST['notify_topics'][$index] = (int) $id;
  1069. // Make sure there are no zeros left.
  1070. $_POST['notify_topics'] = array_diff($_POST['notify_topics'], array(0));
  1071. $smcFunc['db_query']('', '
  1072. DELETE FROM {db_prefix}log_notify
  1073. WHERE id_topic IN ({array_int:topic_list})
  1074. AND id_member = {int:selected_member}',
  1075. array(
  1076. 'topic_list' => $_POST['notify_topics'],
  1077. 'selected_member' => $memID,
  1078. )
  1079. );
  1080. }
  1081. }
  1082. /**
  1083. * Save any changes to the custom profile fields
  1084. *
  1085. * @param int $memID
  1086. * @param string $area
  1087. * @param bool $sanitize = true
  1088. */
  1089. function makeCustomFieldChanges($memID, $area, $sanitize = true)
  1090. {
  1091. global $context, $smcFunc, $user_profile, $user_info, $modSettings, $sourcedir;
  1092. if ($sanitize && isset($_POST['customfield']))
  1093. $_POST['customfield'] = htmlspecialchars__recursive($_POST['customfield']);
  1094. $where = $area == 'register' ? 'show_reg != 0' : 'show_profile = {string:area}';
  1095. // Load the fields we are saving too - make sure we save valid data (etc).
  1096. $request = $smcFunc['db_query']('', '
  1097. SELECT col_name, field_name, field_desc, field_type, field_length, field_options, default_value, show_reg, mask, private
  1098. FROM {db_prefix}custom_fields
  1099. WHERE ' . $where . '
  1100. AND active = {int:is_active}',
  1101. array(
  1102. 'is_active' => 1,
  1103. 'area' => $area,
  1104. )
  1105. );
  1106. $changes = array();
  1107. $log_changes = array();
  1108. while ($row = $smcFunc['db_fetch_assoc']($request))
  1109. {
  1110. /* This means don't save if:
  1111. - The user is NOT an admin.
  1112. - The data is not freely viewable and editable by users.
  1113. - The data is not invisible to users but editable by the owner (or if it is the user is not the owner)
  1114. - The area isn't registration, and if it is that the field is not suppossed to be shown there.
  1115. */
  1116. if ($row['private'] != 0 && !allowedTo('admin_forum') && ($memID != $user_info['id'] || $row['private'] != 2) && ($area != 'register' || $row['show_reg'] == 0))
  1117. continue;
  1118. // Validate the user data.
  1119. if ($row['field_type'] == 'check')
  1120. $value = isset($_POST['customfield'][$row['col_name']]) ? 1 : 0;
  1121. elseif ($row['field_type'] == 'select' || $row['field_type'] == 'radio')
  1122. {
  1123. $value = $row['default_value'];
  1124. foreach (explode(',', $row['field_options']) as $k => $v)
  1125. if (isset($_POST['customfield'][$row['col_name']]) && $_POST['customfield'][$row['col_name']] == $k)
  1126. $value = $v;
  1127. }
  1128. // Otherwise some form of text!
  1129. else
  1130. {
  1131. $value = isset($_POST['customfield'][$row['col_name']]) ? $_POST['customfield'][$row['col_name']] : '';
  1132. if ($row['field_length'])
  1133. $value = $smcFunc['substr']($value, 0, $row['field_length']);
  1134. // Any masks?
  1135. if ($row['field_type'] == 'text' && !empty($row['mask']) && $row['mask'] != 'none')
  1136. {
  1137. // @todo We never error on this - just ignore it at the moment...
  1138. if ($row['mask'] == 'email' && (preg_match('~^[0-9A-Za-z=_+\-/][0-9A-Za-z=_\'+\-/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$~', $value) === 0 || strlen($value) > 255))
  1139. $value = '';
  1140. elseif ($row['mask'] == 'number')
  1141. {
  1142. $value = (int) $value;
  1143. }
  1144. elseif (substr($row['mask'], 0, 5) == 'regex' && trim($value) != '' && preg_match(substr($row['mask'], 5), $value) === 0)
  1145. $value = '';
  1146. }
  1147. }
  1148. // Did it change?
  1149. if (!isset($user_profile[$memID]['options'][$row['col_name']]) || $user_profile[$memID]['options'][$row['col_name']] != $value)
  1150. {
  1151. $log_changes[] = array(
  1152. 'action' => 'customfield_' . $row['col_name'],
  1153. 'log_type' => 'user',
  1154. 'extra' => array(
  1155. 'previous' => !empty($user_profile[$memID]['options'][$row['col_name']]) ? $user_profile[$memID]['options'][$row['col_name']] : '',
  1156. 'new' => $value,
  1157. 'applicator' => $user_info['id'],
  1158. 'member_affected' => $memID,
  1159. ),
  1160. );
  1161. $changes[] = array(1, $row['col_name'], $value, $memID);
  1162. $user_profile[$memID]['options'][$row['col_name']] = $value;
  1163. }
  1164. }
  1165. $smcFunc['db_free_result']($request);
  1166. call_integration_hook('integrate_save_custom_profile_fields', array(&$changes, &$log_changes, $memID, $area, $sanitize));
  1167. // Make those changes!
  1168. if (!empty($changes) && empty($context['password_auth_failed']))
  1169. {
  1170. $smcFunc['db_insert']('replace',
  1171. '{db_prefix}themes',
  1172. array('id_theme' => 'int', 'variable' => 'string-255', 'value' => 'string-65534', 'id_member' => 'int'),
  1173. $changes,
  1174. array('id_theme', 'variable', 'id_member')
  1175. );
  1176. if (!empty($log_changes) && !empty($modSettings['modlog_enabled']))
  1177. {
  1178. require_once($sourcedir . '/Logging.php');
  1179. logActions($log_changes);
  1180. }
  1181. }
  1182. }
  1183. /**
  1184. * Show all the users buddies, as well as a add/delete interface.
  1185. *
  1186. * @param int $memID id_member
  1187. */
  1188. function editBuddyIgnoreLists($memID)
  1189. {
  1190. global $sourcedir, $context, $txt, $scripturl, $modSettings, $user_profile;
  1191. // Do a quick check to ensure people aren't getting here illegally!
  1192. if (!$context['user']['is_owner'] || empty($modSettings['enable_buddylist']))
  1193. fatal_lang_error('no_access', false);
  1194. // Can we email the user direct?
  1195. $context['can_moderate_forum'] = allowedTo('moderate_forum');
  1196. $context['can_send_email'] = allowedTo('send_email_to_members');
  1197. $subActions = array(
  1198. 'buddies' => array('editBuddies', $txt['editBuddies']),
  1199. 'ignore' => array('editIgnoreList', $txt['editIgnoreList']),
  1200. );
  1201. $context['list_area'] = isset($_GET['sa']) && isset($subActions[$_GET['sa']]) ? $_GET['sa'] : 'buddies';
  1202. // Create the tabs for the template.
  1203. $context[$context['profile_menu_name']]['tab_data'] = array(
  1204. 'title' => $txt['editBuddyIgnoreLists'],
  1205. 'description' => $txt['buddy_ignore_desc'],
  1206. 'icon' => 'profile_hd.png',
  1207. 'tabs' => array(
  1208. 'buddies' => array(),
  1209. 'ignore' => array(),
  1210. ),
  1211. );
  1212. // Pass on to the actual function.
  1213. $context['sub_template'] = $subActions[$context['list_area']][0];
  1214. $subActions[$context['list_area']][0]($memID);
  1215. }
  1216. /**
  1217. * Show all the users buddies, as well as a add/delete interface.
  1218. *
  1219. * @param int $memID id_member
  1220. */
  1221. function editBuddies($memID)
  1222. {
  1223. global $txt, $scripturl;
  1224. global $context, $user_profile, $memberContext, $smcFunc;
  1225. // For making changes!
  1226. $buddiesArray = explode(',', $user_profile[$memID]['buddy_list']);
  1227. foreach ($buddiesArray as $k => $dummy)
  1228. if ($dummy == '')
  1229. unset($buddiesArray[$k]);
  1230. // Removing a buddy?
  1231. if (isset($_GET['remove']))
  1232. {
  1233. checkSession('get');
  1234. call_integration_hook('integrate_remove_buddy', array($memID));
  1235. $_SESSION['prf-save'] = $txt['could_not_remove_person'];
  1236. // Heh, I'm lazy, do it the easy way...
  1237. foreach ($buddiesArray as $key => $buddy)
  1238. if ($buddy == (int) $_GET['remove'])
  1239. {
  1240. unset($buddiesArray[$key]);
  1241. $_SESSION['prf-save'] = true;
  1242. }
  1243. // Make the changes.
  1244. $user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
  1245. updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
  1246. // Redirect off the page because we don't like all this ugly query stuff to stick in the history.
  1247. redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
  1248. }
  1249. elseif (isset($_POST['new_buddy']))
  1250. {
  1251. checkSession();
  1252. // Prepare the string for extraction...
  1253. $_POST['new_buddy'] = strtr($smcFunc['htmlspecialchars']($_POST['new_buddy'], ENT_QUOTES), array('&quot;' => '"'));
  1254. preg_match_all('~"([^"]+)"~', $_POST['new_buddy'], $matches);
  1255. $new_buddies = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_buddy']))));
  1256. foreach ($new_buddies as $k => $dummy)
  1257. {
  1258. $new_buddies[$k] = strtr(trim($new_buddies[$k]), array('\'' => '&#039;'));
  1259. if (strlen($new_buddies[$k]) == 0 || in_array($new_buddies[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
  1260. unset($new_buddies[$k]);
  1261. }
  1262. call_integration_hook('integrate_add_buddies', array($memID, &$new_buddies));
  1263. $_SESSION['prf-save'] = $txt['could_not_add_person'];
  1264. if (!empty($new_buddies))
  1265. {
  1266. // Now find out the id_member of the buddy.
  1267. $request = $smcFunc['db_query']('', '
  1268. SELECT id_member
  1269. FROM {db_prefix}members
  1270. WHERE member_name IN ({array_string:new_buddies}) OR real_name IN ({array_string:new_buddies})
  1271. LIMIT {int:count_new_buddies}',
  1272. array(
  1273. 'new_buddies' => $new_buddies,
  1274. 'count_new_buddies' => count($new_buddies),
  1275. )
  1276. );
  1277. if ($smcFunc['db_num_rows']($request) != 0)
  1278. $_SESSION['prf-save'] = true;
  1279. // Add the new member to the buddies array.
  1280. while ($row = $smcFunc['db_fetch_assoc']($request))
  1281. $buddiesArray[] = (int) $row['id_member'];
  1282. $smcFunc['db_free_result']($request);
  1283. // Now update the current users buddy list.
  1284. $user_profile[$memID]['buddy_list'] = implode(',', $buddiesArray);
  1285. updateMemberData($memID, array('buddy_list' => $user_profile[$memID]['buddy_list']));
  1286. }
  1287. // Back to the buddy list!
  1288. redirectexit('action=profile;area=lists;sa=buddies;u=' . $memID);
  1289. }
  1290. // Get all the users "buddies"...
  1291. $buddies = array();
  1292. if (!empty($buddiesArray))
  1293. {
  1294. $result = $smcFunc['db_query']('', '
  1295. SELECT id_member
  1296. FROM {db_prefix}members
  1297. WHERE id_member IN ({array_int:buddy_list})
  1298. ORDER BY real_name
  1299. LIMIT {int:buddy_list_count}',
  1300. array(
  1301. 'buddy_list' => $buddiesArray,
  1302. 'buddy_list_count' => substr_count($user_profile[$memID]['buddy_list'], ',') + 1,
  1303. )
  1304. );
  1305. while ($row = $smcFunc['db_fetch_assoc']($result))
  1306. $buddies[] = $row['id_member'];
  1307. $smcFunc['db_free_result']($result);
  1308. }
  1309. $context['buddy_count'] = count($buddies);
  1310. // Load all the members up.
  1311. loadMemberData($buddies, false, 'profile');
  1312. // Setup the context for each buddy.
  1313. $context['buddies'] = array();
  1314. foreach ($buddies as $buddy)
  1315. {
  1316. loadMemberContext($buddy);
  1317. $context['buddies'][$buddy] = $memberContext[$buddy];
  1318. }
  1319. if (isset($_SESSION['prf-save']))
  1320. {
  1321. if ($_SESSION['prf-save'] === true)
  1322. $context['saved_successful'] = true;
  1323. else
  1324. $context['saved_failed'] = $_SESSION['prf-save'];
  1325. unset($_SESSION['prf-save']);
  1326. }
  1327. call_integration_hook('integrate_view_buddies', array($memID));
  1328. }
  1329. /**
  1330. * Allows the user to view their ignore list, as well as the option to manage members on it.
  1331. *
  1332. * @param int $memID id_member
  1333. */
  1334. function editIgnoreList($memID)
  1335. {
  1336. global $txt, $scripturl;
  1337. global $context, $user_profile, $memberContext, $smcFunc;
  1338. // For making changes!
  1339. $ignoreArray = explode(',', $user_profile[$memID]['pm_ignore_list']);
  1340. foreach ($ignoreArray as $k => $dummy)
  1341. if ($dummy == '')
  1342. unset($ignoreArray[$k]);
  1343. // Removing a member from the ignore list?
  1344. if (isset($_GET['remove']))
  1345. {
  1346. checkSession('get');
  1347. $_SESSION['prf-save'] = $txt['could_not_remove_person'];
  1348. // Heh, I'm lazy, do it the easy way...
  1349. foreach ($ignoreArray as $key => $id_remove)
  1350. if ($id_remove == (int) $_GET['remove'])
  1351. {
  1352. unset($ignoreArray[$key]);
  1353. $_SESSION['prf-save'] = true;
  1354. }
  1355. // Make the changes.
  1356. $user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
  1357. updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
  1358. // Redirect off the page because we don't like all this ugly query stuff to stick in the history.
  1359. redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
  1360. }
  1361. elseif (isset($_POST['new_ignore']))
  1362. {
  1363. checkSession();
  1364. // Prepare the string for extraction...
  1365. $_POST['new_ignore'] = strtr($smcFunc['htmlspecialchars']($_POST['new_ignore'], ENT_QUOTES), array('&quot;' => '"'));
  1366. preg_match_all('~"([^"]+)"~', $_POST['new_ignore'], $matches);
  1367. $new_entries = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $_POST['new_ignore']))));
  1368. foreach ($new_entries as $k => $dummy)
  1369. {
  1370. $new_entries[$k] = strtr(trim($new_entries[$k]), array('\'' => '&#039;'));
  1371. if (strlen($new_entries[$k]) == 0 || in_array($new_entries[$k], array($user_profile[$memID]['member_name'], $user_profile[$memID]['real_name'])))
  1372. unset($new_entries[$k]);
  1373. }
  1374. $_SESSION['prf-save'] = $txt['could_not_add_person'];
  1375. if (!empty($new_entries))
  1376. {
  1377. // Now find out the id_member for the members in question.
  1378. $request = $smcFunc['db_query']('', '
  1379. SELECT id_member
  1380. FROM {db_prefix}members
  1381. WHERE member_name IN ({array_string:new_entries}) OR real_name IN ({array_string:new_entries})
  1382. LIMIT {int:count_new_entries}',
  1383. array(
  1384. 'new_entries' => $new_entries,
  1385. 'count_new_entries' => count($new_entries),
  1386. )
  1387. );
  1388. if ($smcFunc['db_num_rows']($request) != 0)
  1389. $_SESSION['prf-save'] = true;
  1390. // Add the new member to the buddies array.
  1391. while ($row = $smcFunc['db_fetch_assoc']($request))
  1392. $ignoreArray[] = (int) $row['id_member'];
  1393. $smcFunc['db_free_result']($request);
  1394. // Now update the current users buddy list.
  1395. $user_profile[$memID]['pm_ignore_list'] = implode(',', $ignoreArray);
  1396. updateMemberData($memID, array('pm_ignore_list' => $user_profile[$memID]['pm_ignore_list']));
  1397. }
  1398. // Back to the list of pityful people!
  1399. redirectexit('action=profile;area=lists;sa=ignore;u=' . $memID);
  1400. }
  1401. // Initialise the list of members we're ignoring.
  1402. $ignored = array();
  1403. if (!empty($ignoreArray))
  1404. {
  1405. $result = $smcFunc['db_query']('', '
  1406. SELECT id_member
  1407. FROM {db_prefix}members
  1408. WHERE id_member IN ({array_int:ignore_list})
  1409. ORDER BY real_name
  1410. LIMIT {int:ignore_list_count}',
  1411. array(
  1412. 'ignore_list' => $ignoreArray,
  1413. 'ignore_list_count' => substr_count($user_profile[$memID]['pm_ignore_list'], ',') + 1,
  1414. )
  1415. );
  1416. while ($row = $smcFunc['db_fetch_assoc']($result))
  1417. $ignored[] = $row['id_member'];
  1418. $smcFunc['db_free_result']($result);
  1419. }
  1420. $context['ignore_count'] = count($ignored);
  1421. // Load all the members up.
  1422. loadMemberData($ignored, false, 'profile');
  1423. // Setup the context for each buddy.
  1424. $context['ignore_list'] = array();
  1425. foreach ($ignored as $ignore_member)
  1426. {
  1427. loadMemberContext($ignore_member);
  1428. $context['ignore_list'][$ignore_member] = $memberContext[$ignore_member];
  1429. }
  1430. if (isset($_SESSION['prf-save']))
  1431. {
  1432. if ($_SESSION['prf-save'] === true)
  1433. $context['saved_successful'] = true;
  1434. else
  1435. $context['saved_failed'] = $_SESSION['prf-save'];
  1436. unset($_SESSION['prf-save']);
  1437. }
  1438. }
  1439. /**
  1440. * @todo Needs a description
  1441. *
  1442. * @param int $memID id_member
  1443. */
  1444. function account($memID)
  1445. {
  1446. global $context, $txt;
  1447. loadThemeOptions($memID);
  1448. if (allowedTo(array('profile_identity_own', 'profile_identity_any', 'profile_password_own', 'profile_password_any')))
  1449. loadCustomFields($memID, 'account');
  1450. $context['sub_template'] = 'edit_options';
  1451. $context['page_desc'] = $txt['account_info'];
  1452. setupProfileContext(
  1453. array(
  1454. 'member_name', 'real_name', 'date_registered', 'posts', 'lngfile', 'hr',
  1455. 'id_group', 'hr',
  1456. 'email_address', 'hide_email', 'show_online', 'hr',
  1457. 'passwrd1', 'passwrd2', 'hr',
  1458. 'secret_question', 'secret_answer',
  1459. )
  1460. );
  1461. }
  1462. /**
  1463. * @todo Needs a description
  1464. *
  1465. * @param int $memID id_member
  1466. */
  1467. function forumProfile($memID)
  1468. {
  1469. global $context, $txt;
  1470. loadThemeOptions($memID);
  1471. if (allowedTo(array('profile_forum_own', 'profile_forum_any')))
  1472. loadCustomFields($memID, 'forumprofile');
  1473. $context['sub_template'] = 'edit_options';
  1474. $context['page_desc'] = $txt['forumProfile_info'];
  1475. $context['show_preview_button'] = true;
  1476. setupProfileContext(
  1477. array(
  1478. 'avatar_choice', 'hr', 'personal_text', 'hr',
  1479. 'bday1', 'location', 'gender', 'hr',
  1480. 'icq', 'aim', 'yim', 'skype', 'hr',
  1481. 'usertitle', 'signature', 'hr',
  1482. 'karma_good', 'hr',
  1483. 'website_title', 'website_url',
  1484. )
  1485. );
  1486. }
  1487. /**
  1488. * Recursive function to retrieve server-stored avatar files
  1489. *
  1490. * @param string $directory
  1491. * @param int $level
  1492. * @return array
  1493. */
  1494. function getAvatars($directory, $level)
  1495. {
  1496. global $context, $txt, $modSettings, $smcFunc;
  1497. $result = array();
  1498. // Open the directory..
  1499. $dir = dir($modSettings['avatar_directory'] . (!empty($directory) ? '/' : '') . $directory);
  1500. $dirs = array();
  1501. $files = array();
  1502. if (!$dir)
  1503. return array();
  1504. while ($line = $dir->read())
  1505. {
  1506. if (in_array($line, array('.', '..', 'blank.png', 'index.php')))
  1507. continue;
  1508. if (is_dir($modSettings['avatar_directory'] . '/' . $directory . (!empty($directory) ? '/' : '') . $line))
  1509. $dirs[] = $line;
  1510. else
  1511. $files[] = $line;
  1512. }
  1513. $dir->close();
  1514. // Sort the results...
  1515. natcasesort($dirs);
  1516. natcasesort($files);
  1517. if ($level == 0)
  1518. {
  1519. $result[] = array(
  1520. 'filename' => 'blank.png',
  1521. 'checked' => in_array($context['member']['avatar']['server_pic'], array('', 'blank.png')),
  1522. 'name' => $txt['no_pic'],
  1523. 'is_dir' => false
  1524. );
  1525. }
  1526. foreach ($dirs as $line)
  1527. {
  1528. $tmp = getAvatars($directory . (!empty($directory) ? '/' : '') . $line, $level + 1);
  1529. if (!empty($tmp))
  1530. $result[] = array(
  1531. 'filename' => $smcFunc['htmlspecialchars']($line),
  1532. 'checked' => strpos($context['member']['avatar']['server_pic'], $line . '/') !== false,
  1533. 'name' => '[' . $smcFunc['htmlspecialchars'](str_replace('_', ' ', $line)) . ']',
  1534. 'is_dir' => true,
  1535. 'files' => $tmp
  1536. );
  1537. unset($tmp);
  1538. }
  1539. foreach ($files as $line)
  1540. {
  1541. $filename = substr($line, 0, (strlen($line) - strlen(strrchr($line, '.'))));
  1542. $extension = substr(strrchr($line, '.'), 1);
  1543. // Make sure it is an image.
  1544. if (strcasecmp($extension, 'gif') != 0 && strcasecmp($extension, 'jpg') != 0 && strcasecmp($extension, 'jpeg') != 0 && strcasecmp($extension, 'png') != 0 && strcasecmp($extension, 'bmp') != 0)
  1545. continue;
  1546. $result[] = array(
  1547. 'filename' => $smcFunc['htmlspecialchars']($line),
  1548. 'checked' => $line == $context['member']['avatar']['server_pic'],
  1549. 'name' => $smcFunc['htmlspecialchars'](str_replace('_', ' ', $filename)),
  1550. 'is_dir' => false
  1551. );
  1552. if ($level == 1)
  1553. $context['avatar_list'][] = $directory . '/' . $line;
  1554. }
  1555. return $result;
  1556. }
  1557. /**
  1558. * @todo needs a description
  1559. *
  1560. * @param int $memID id_member
  1561. */
  1562. function theme($memID)
  1563. {
  1564. global $txt, $context, $user_profile, $smcFunc;
  1565. loadThemeOptions($memID);
  1566. if (allowedTo(array('profile_extra_own', 'profile_extra_any')))
  1567. loadCustomFields($memID, 'theme');
  1568. $context['sub_template'] = 'edit_options';
  1569. $context['page_desc'] = $txt['theme_info'];
  1570. setupProfileContext(
  1571. array(
  1572. 'id_theme', 'smiley_set', 'hr',
  1573. 'time_format', 'time_offset', 'hr',
  1574. 'theme_settings',
  1575. )
  1576. );
  1577. }
  1578. /**
  1579. * Changing authentication method? Only appropriate for people using OpenID.
  1580. *
  1581. * @param int $memID id_member
  1582. * @param bool $saving = false
  1583. */
  1584. function authentication($memID, $saving = false)
  1585. {
  1586. global $context, $cur_profile, $sourcedir, $txt, $post_errors, $modSettings;
  1587. loadLanguage('Login');
  1588. // We are saving?
  1589. if ($saving)
  1590. {
  1591. // Moving to password passed authentication?
  1592. if ($_POST['authenticate'] == 'passwd')
  1593. {
  1594. // Didn't enter anything?
  1595. if ($_POST['passwrd1'] == '')
  1596. $post_errors[] = 'no_password';
  1597. // Do the two entries for the password even match?
  1598. elseif (!isset($_POST['passwrd2']) || $_POST['passwrd1'] != $_POST['passwrd2'])
  1599. $post_errors[] = 'bad_new_password';
  1600. // Is it valid?
  1601. else
  1602. {
  1603. require_once($sourcedir . '/Subs-Auth.php');
  1604. $passwordErrors = validatePassword($_POST['passwrd1'], $cur_profile['member_name'], array($cur_profile['real_name'], $cur_profile['email_address']));
  1605. // Were there errors?
  1606. if ($passwordErrors != null)
  1607. $post_errors[] = 'password_' . $passwordErrors;
  1608. }
  1609. if (empty($post_errors))
  1610. {
  1611. // Integration?
  1612. call_integration_hook('integrate_reset_pass', array($cur_profile['member_name'], $cur_profile['member_name'], $_POST['passwrd1']));
  1613. // Go then.
  1614. $passwd = sha1(strtolower($cur_profile['member_name']) . un_htmlspecialchars($_POST['passwrd1']));
  1615. // Do the important bits.
  1616. updateMemberData($memID, array('openid_uri' => '', 'passwd' => $passwd));
  1617. if ($context['user']['is_owner'])
  1618. {
  1619. setLoginCookie(60 * $modSettings['cookieTime'], $memID, sha1(sha1(strtolower($cur_profile['member_name']) . un_htmlspecialchars($_POST['passwrd2'])) . $cur_profile['password_salt']));
  1620. redirectexit('action=profile;area=authentication;updated');
  1621. }
  1622. else
  1623. redirectexit('action=profile;u=' . $memID);
  1624. }
  1625. return true;
  1626. }
  1627. // Not right yet!
  1628. elseif ($_POST['authenticate'] == 'openid' && !empty($_POST['openid_identifier']))
  1629. {
  1630. require_once($sourcedir . '/Subs-OpenID.php');
  1631. $_POST['openid_identifier'] = smf_openID_canonize($_POST['openid_identifier']);
  1632. if (smf_openid_member_exists($_POST['openid_identifier']))
  1633. $post_errors[] = 'openid_in_use';
  1634. elseif (empty($post_errors))
  1635. {
  1636. // Authenticate using the new OpenID URI first to make sure they didn't make a mistake.
  1637. if ($context['user']['is_owner'])
  1638. {
  1639. $_SESSION['new_openid_uri'] = $_POST['openid_identifier'];
  1640. smf_openID_validate($_POST['openid_identifier'], false, null, 'change_uri');
  1641. }
  1642. else
  1643. updateMemberData($memID, array('openid_uri' => $_POST['openid_identifier']));
  1644. }
  1645. }
  1646. }
  1647. // Some stuff.
  1648. $context['member']['openid_uri'] = $cur_profile['openid_uri'];
  1649. $context['auth_method'] = empty($cur_profile['openid_uri']) ? 'password' : 'openid';
  1650. $context['sub_template'] = 'authentication_method';
  1651. }
  1652. /**
  1653. * Display the notifications and settings for changes.
  1654. *
  1655. * @param int $memID id_member
  1656. */
  1657. function notification($memID)
  1658. {
  1659. global $txt, $scripturl, $user_profile, $context, $smcFunc, $sourcedir;
  1660. // Going to want this for consistency.
  1661. loadCSSFile('admin.css', array(), 'admin');
  1662. // This is just a bootstrap for everything else.
  1663. $sa = array(
  1664. 'alerts' => 'alert_configuration',
  1665. 'markread' => 'alert_markread',
  1666. 'topics' => 'alert_notifications_topics',
  1667. 'boards' => 'alert_notifications_boards',
  1668. );
  1669. $subAction = !empty($_GET['sa']) && isset($sa[$_GET['sa']]) ? $_GET['sa'] : 'alerts';
  1670. $context['sub_template'] = $sa[$subAction];
  1671. $context[$context['profile_menu_name']]['tab_data'] = array(
  1672. 'title' => $txt['notification'],
  1673. 'help' => '',
  1674. 'description' => $txt['notification_info'],
  1675. );
  1676. $sa[$subAction]($memID);
  1677. }
  1678. function alert_configuration($memID)
  1679. {
  1680. global $txt, $scripturl, $user_profile, $context, $modSettings, $smcFunc, $sourcedir;
  1681. $context['token_check'] = 'profile-nt' . $memID;
  1682. is_not_guest();
  1683. if (!$context['user']['is_owner'])
  1684. isAllowedTo('profile_extra_any');
  1685. // What options are set?
  1686. $context['member'] += array(
  1687. 'notify_announcements' => $user_profile[$memID]['notify_announcements'],
  1688. 'notify_send_body' => $user_profile[$memID]['notify_send_body'],
  1689. 'notify_types' => $user_profile[$memID]['notify_types'],
  1690. 'notify_regularity' => $user_profile[$memID]['notify_regularity'],
  1691. );
  1692. loadThemeOptions($memID);
  1693. // Now load all the values for this user.
  1694. require_once($sourcedir . '/Subs-Notify.php');
  1695. $prefs = getNotifyPrefs($memID);
  1696. // And we might as well now perform the splicing of default values.
  1697. if (!empty($prefs[0]))
  1698. foreach ($prefs[0] as $this_pref => $value)
  1699. if (!isset($prefs[$memID][$this_pref]))
  1700. $prefs[$memID][$this_pref] = $value;
  1701. $context['alert_prefs'] = !empty($prefs[$memID]) ? $prefs[$memID] : array();
  1702. // Now for the exciting stuff.
  1703. // We have groups of items, each item has both an alert and an email key as well as an optional help string.
  1704. // Valid values for these keys are 'always', 'yes', 'never'; if using always or never you should add a help string.
  1705. $alert_types = array(
  1706. 'msg' => array(
  1707. 'topic_notify' => array('alert' => 'yes', 'email' => 'yes'),
  1708. 'board_notify' => array('alert' => 'yes', 'email' => 'yes'),
  1709. 'msg_mention' => array('alert' => 'yes', 'email' => 'yes'),
  1710. 'msg_quote' => array('alert' => 'yes', 'email' => 'yes'),
  1711. 'msg_like' => array('alert' => 'yes', 'email' => 'never'),
  1712. ),
  1713. 'pm' => array(
  1714. 'pm_new' => array('alert' => 'always', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_read', 'is_board' => false)),
  1715. 'pm_reply' => array('alert' => 'always', 'email' => 'yes', 'help' => 'alert_pm_new', 'permission' => array('name' => 'pm_send', 'is_board' => false)),
  1716. ),
  1717. 'moderation' => array(
  1718. 'msg_report' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
  1719. 'msg_report_reply' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_board', 'is_board' => true)),
  1720. ),
  1721. 'members' => array(
  1722. 'member_register' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'moderate_forum', 'is_board' => false)),
  1723. 'request_group' => array('alert' => 'yes', 'email' => 'yes'),
  1724. 'warn_any' => array('alert' => 'yes', 'email' => 'yes', 'permission' => array('name' => 'issue_warning', 'is_board' => false)),
  1725. ),
  1726. 'calendar' => array(
  1727. 'event_new' => array('alert' => 'yes', 'email' => 'yes', 'help' => 'alert_event_new'),
  1728. ),
  1729. );
  1730. $group_options = array(
  1731. 'msg' => array(
  1732. array('check', 'msg_auto_notify', 'label' => 'after'),
  1733. array('select', 'msg_notify_pref', 'label' => 'before', 'opts' => array(
  1734. 0 => $txt['alert_opt_msg_notify_pref_nothing'],
  1735. 1 => $txt['alert_opt_msg_notify_pref_instant'],
  1736. 2 => $txt['alert_opt_msg_notify_pref_first'],
  1737. 3 => $txt['alert_opt_msg_notify_pref_daily'],
  1738. 4 => $txt['alert_opt_msg_notify_pref_weekly'],
  1739. )),
  1740. ),
  1741. );
  1742. $disabled_options = array();
  1743. // There are certain things that are disabled at the group level.
  1744. if (empty($modSettings['cal_enabled']))
  1745. {
  1746. foreach ($alert_types['calendar'] as $k => $v)
  1747. $disabled_options[] = $k;
  1748. unset ($alert_types['calendar']);
  1749. }
  1750. // Now, now, we could pass this through global but we should really get into the habit of
  1751. // passing content to hooks, not expecting hooks to splatter everything everywhere.
  1752. call_integration_hook('integrate_alert_types', array(&$alert_types, &$group_options, &$disabled_options));
  1753. // Now we have to do some permissions testing.
  1754. require_once($sourcedir . '/Subs-Members.php');
  1755. $perms_cache = array();
  1756. foreach ($alert_types as $group => $items)
  1757. {
  1758. foreach ($items as $alert_key => $alert_value)
  1759. {
  1760. if (!isset($alert_value['permission']))
  1761. continue;
  1762. if (!isset($perms_cache[$alert_value['permission']['name']]))
  1763. {
  1764. $in_board = !empty($alert_value['permission']['is_board']) ? 0 : null;
  1765. $members = membersAllowedTo($alert_value['permission']['name'], $in_board);
  1766. $perms_cache[$alert_value['permission']['name']] = in_array($memID, $members);
  1767. }
  1768. if (!$perms_cache[$alert_value['permission']['name']])
  1769. {
  1770. $disabled_options[] = $alert_key;
  1771. unset ($alert_types[$group][$alert_key]);
  1772. }
  1773. }
  1774. if (empty($alert_types[$group]))
  1775. unset ($alert_types[$group]);
  1776. }
  1777. // Slightly different for group requests
  1778. $request = $smcFunc['db_query']('', '
  1779. SELECT COUNT(*)
  1780. FROM {db_prefix}group_moderators
  1781. WHERE id_member = {int:memID}',
  1782. array(
  1783. 'memID' => $memID,
  1784. )
  1785. );
  1786. list($can_mod) = $smcFunc['db_fetch_row']($request);
  1787. if (!isset($perms_cache['manage_membergroups']))
  1788. {
  1789. $members = membersAllowedTo('manage_membergroups');
  1790. $perms_cache['manage_membergroups'] = in_array($memID, $members);
  1791. }
  1792. if (!($perms_cache['manage_membergroups'] || $can_mod != 0))
  1793. unset($alert_types['members']['request_group']);
  1794. // And finally, exporting it to be useful later.
  1795. $context['alert_types'] = $alert_types;
  1796. $context['alert_group_options'] = $group_options;
  1797. $context['disabled_alerts'] = $disabled_options;
  1798. $context['alert_bits'] = array(
  1799. 'alert' => 0x01,
  1800. 'email' => 0x02,
  1801. );
  1802. if (isset($_POST['notify_submit']))
  1803. {
  1804. checkSession();
  1805. validateToken($context['token_check'], 'post');
  1806. // We need to step through the list of valid settings and figure out what the user has set.
  1807. $update_prefs = array();
  1808. // Now the group level options
  1809. foreach ($context['alert_group_options'] as $opt_group => $group)
  1810. {
  1811. foreach ($group as $this_option)
  1812. {
  1813. switch ($this_option[0])
  1814. {
  1815. case 'check':
  1816. $update_prefs[$this_option[1]] = !empty($_POST['opt_' . $this_option[1]]) ? 1 : 0;
  1817. break;
  1818. case 'select':
  1819. if (isset($_POST['opt_' . $this_option[1]], $this_option['opts'][$_POST['opt_' . $this_option[1]]]))
  1820. $update_prefs[$this_option[1]] = $_POST['opt_' . $this_option[1]];
  1821. else
  1822. {
  1823. // We didn't have a sane value. Let's grab the first item from the possibles.
  1824. $keys = array_keys($this_option['opts']);
  1825. $first = array_shift($keys);
  1826. $update_prefs[$this_option[1]] = $first;
  1827. }
  1828. break;
  1829. }
  1830. }
  1831. }
  1832. // Now the individual options
  1833. foreach ($context['alert_types'] as $alert_group => $items)
  1834. {
  1835. foreach ($items as $item_key => $this_options)
  1836. {
  1837. $this_value = 0;
  1838. foreach ($context['alert_bits'] as $type => $bitvalue)
  1839. {
  1840. if ($this_options[$type] == 'yes' && !empty($_POST[$type . '_' . $item_key]))
  1841. $this_value |= $bitvalue;
  1842. }
  1843. $update_prefs[$item_key] = $this_value;
  1844. }
  1845. }
  1846. setNotifyPrefs($memID, $update_prefs);
  1847. foreach ($update_prefs as $pref => $value)
  1848. $context['alert_prefs'][$pref] = $value;
  1849. makeNotificationChanges($memID);
  1850. $context['profile_updated'] = $txt['profile_updated_own'];
  1851. }
  1852. createToken($context['token_check'], 'post');
  1853. }
  1854. function alert_markread($memID)
  1855. {
  1856. global $context, $db_show_debug, $smcFunc;
  1857. // We do not want to output debug information here.
  1858. $db_show_debug = false;
  1859. // We only want to output our little layer here.
  1860. $context['template_layers'] = array();
  1861. $context['sub_template'] = 'alerts_all_read';
  1862. loadLanguage('Alerts');
  1863. // Now we're all set up.
  1864. is_not_guest();
  1865. if (!$context['user']['is_owner'])
  1866. fatal_error('no_access');
  1867. checkSession('get');
  1868. // Assuming we're here, mark everything as read and head back.
  1869. // We only spit back the little layer because this should be called AJAXively.
  1870. $smcFunc['db_query']('', '
  1871. UPDATE {db_prefix}user_alerts
  1872. SET is_read = {int:now}
  1873. WHERE id_member = {int:current_member}
  1874. AND is_read = 0',
  1875. array(
  1876. 'now' => time(),
  1877. 'current_member' => $memID,
  1878. )
  1879. );
  1880. updateMemberData($memID, array('alerts' => 0));
  1881. }
  1882. function alert_notifications_topics($memID)
  1883. {
  1884. global $txt, $scripturl, $user_profile, $context, $modSettings, $smcFunc, $sourcedir;
  1885. // Because of the way this stuff works, we want to do this ourselves.
  1886. if (isset($_POST['edit_notify_topics']))
  1887. {
  1888. checkSession();
  1889. validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
  1890. makeNotificationChanges($memID);
  1891. $context['profile_updated'] = $txt['profile_updated_own'];
  1892. }
  1893. // Now set up for the token check.
  1894. $context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
  1895. createToken($context['token_check'], 'post');
  1896. // Gonna want this for the list.
  1897. require_once($sourcedir . '/Subs-List.php');
  1898. // Do the topic notifications.
  1899. $listOptions = array(
  1900. 'id' => 'topic_notification_list',
  1901. 'width' => '100%',
  1902. 'items_per_page' => $modSettings['defaultMaxMessages'],
  1903. 'no_items_label' => $txt['notifications_topics_none'] . '<br><br>' . $txt['notifications_topics_howto'],
  1904. 'no_items_align' => 'left',
  1905. 'base_href' => $scripturl . '?action=profile;u=' . $memID . ';area=notification;sa=topics',
  1906. 'default_sort_col' => 'last_post',
  1907. 'get_items' => array(
  1908. 'function' => 'list_getTopicNotifications',
  1909. 'params' => array(
  1910. $memID,
  1911. ),
  1912. ),
  1913. 'get_count' => array(
  1914. 'function' => 'list_getTopicNotificationCount',
  1915. 'params' => array(
  1916. $memID,
  1917. ),
  1918. ),
  1919. 'columns' => array(
  1920. 'subject' => array(
  1921. 'header' => array(
  1922. 'value' => $txt['notifications_topics'],
  1923. 'class' => 'lefttext first_th',
  1924. ),
  1925. 'data' => array(
  1926. 'function' => create_function('$topic', '
  1927. global $txt;
  1928. $link = $topic[\'link\'];
  1929. if ($topic[\'new\'])
  1930. $link .= \' <a href="\' . $topic[\'new_href\'] . \'"><span class="new_posts">\' . $txt[\'new\'] . \'</span></a>\';
  1931. $link .= \'<br><span class="smalltext"><em>\' . $txt[\'in\'] . \' \' . $topic[\'board_link\'] . \'</em></span>\';
  1932. return $link;
  1933. '),
  1934. ),
  1935. 'sort' => array(
  1936. 'default' => 'ms.subject',
  1937. 'reverse' => 'ms.subject DESC',
  1938. ),
  1939. ),
  1940. 'started_by' => array(
  1941. 'header' => array(
  1942. 'value' => $txt['started_by'],
  1943. 'class' => 'lefttext',
  1944. ),
  1945. 'data' => array(
  1946. 'db' => 'poster_link',
  1947. ),
  1948. 'sort' => array(
  1949. 'default' => 'real_name_col',
  1950. 'reverse' => 'real_name_col DESC',
  1951. ),
  1952. ),
  1953. 'last_post' => array(
  1954. 'header' => array(
  1955. 'value' => $txt['last_post'],
  1956. 'class' => 'lefttext',
  1957. ),
  1958. 'data' => array(
  1959. 'sprintf' => array(
  1960. 'format' => '<span class="smalltext">%1$s<br>' . $txt['by'] . ' %2$s</span>',
  1961. 'params' => array(
  1962. 'updated' => false,
  1963. 'poster_updated_link' => false,
  1964. ),
  1965. ),
  1966. ),
  1967. 'sort' => array(
  1968. 'default' => 'ml.id_msg DESC',
  1969. 'reverse' => 'ml.id_msg',
  1970. ),
  1971. ),
  1972. 'delete' => array(
  1973. 'header' => array(
  1974. 'value' => '<input type="checkbox" class="input_check" onclick="invertAll(this, this.form);">',
  1975. 'style' => 'width: 4%;',
  1976. 'class' => 'centercol',
  1977. ),
  1978. 'data' => array(
  1979. 'sprintf' => array(
  1980. 'format' => '<input type="checkbox" name="notify_topics[]" value="%1$d" class="input_check">',
  1981. 'params' => array(
  1982. 'id' => false,
  1983. ),
  1984. ),
  1985. 'class' => 'centercol',
  1986. ),
  1987. ),
  1988. ),
  1989. 'form' => array(
  1990. 'href' => $scripturl . '?action=profile;area=notification;sa=topics',
  1991. 'include_sort' => true,
  1992. 'include_start' => true,
  1993. 'hidden_fields' => array(
  1994. 'u' => $memID,
  1995. 'sa' => $context['menu_item_selected'],
  1996. $context['session_var'] => $context['session_id'],
  1997. ),
  1998. 'token' => $context['token_check'],
  1999. ),
  2000. 'additional_rows' => array(
  2001. array(
  2002. 'position' => 'bottom_of_list',
  2003. 'value' => '<input type="submit" name="edit_notify_topics" value="' . $txt['notifications_update'] . '" class="button_submit">',
  2004. 'align' => 'right',
  2005. ),
  2006. ),
  2007. );
  2008. // Create the notification list.
  2009. createList($listOptions);
  2010. }
  2011. function alert_notifications_boards($memID)
  2012. {
  2013. global $txt, $scripturl, $user_profile, $context, $smcFunc, $sourcedir;
  2014. // Because of the way this stuff works, we want to do this ourselves.
  2015. if (isset($_POST['edit_notify_boards']))
  2016. {
  2017. checkSession();
  2018. validateToken(str_replace('%u', $memID, 'profile-nt%u'), 'post');
  2019. makeNotificationChanges($memID);
  2020. $context['profile_updated'] = $txt['profile_updated_own'];
  2021. }
  2022. // Now set up for the token check.
  2023. $context['token_check'] = str_replace('%u', $memID, 'profile-nt%u');
  2024. createToken($context['token_check'], 'post');
  2025. // Gonna want this for the list.
  2026. require_once($sourcedir . '/Subs-List.php');
  2027. // Fine, start with the board list.
  2028. $listOptions = array(
  2029. 'id' => 'board_notification_list',
  2030. 'width' => '100%',
  2031. 'no_items_label' => $txt['notifications_boards_none'] . '<br><br>' . $txt['notifications_boards_howto'],
  2032. 'no_items_align' => 'left',
  2033. 'base_href' => $scripturl . '?action=profile;u=' . $memID . ';area=notification;sa=boards',
  2034. 'default_sort_col' => 'board_name',
  2035. 'get_items' => array(
  2036. 'function' => 'list_getBoardNotifications',
  2037. 'params' => array(
  2038. $memID,
  2039. ),
  2040. ),
  2041. 'columns' => array(
  2042. 'board_name' => array(
  2043. 'header' => array(
  2044. 'value' => $txt['notifications_boards'],
  2045. 'class' => 'lefttext first_th',
  2046. ),
  2047. 'data' => array(
  2048. 'function' => create_function('$board', '
  2049. global $txt;
  2050. $link = $board[\'link\'];
  2051. if ($board[\'new\'])
  2052. $link .= \' <a href="\' . $board[\'href\'] . \'"><span class="new_posts">' . $txt['new'] . '</span></a>\';
  2053. return $link;
  2054. '),
  2055. ),
  2056. 'sort' => array(
  2057. 'default' => 'name',
  2058. 'reverse' => 'name DESC',
  2059. ),
  2060. ),
  2061. 'delete' => array(
  2062. 'header' => array(
  2063. 'value' => '<input type="checkbox" class="input_check" onclick="invertAll(this, this.form);">',
  2064. 'style' => 'width: 4%;',
  2065. 'class' => 'centercol',
  2066. ),
  2067. 'data' => array(
  2068. 'sprintf' => array(
  2069. 'format' => '<input type="checkbox" name="notify_boards[]" value="%1$d" class="input_check">',
  2070. 'params' => array(
  2071. 'id' => false,
  2072. ),
  2073. ),
  2074. 'class' => 'centercol',
  2075. ),
  2076. ),
  2077. ),
  2078. 'form' => array(
  2079. 'href' => $scripturl . '?action=profile;area=notification;sa=boards',
  2080. 'include_sort' => true,
  2081. 'include_start' => true,
  2082. 'hidden_fields' => array(
  2083. 'u' => $memID,
  2084. 'sa' => $context['menu_item_selected'],
  2085. $context['session_var'] => $context['session_id'],
  2086. ),
  2087. 'token' => $context['token_check'],
  2088. ),
  2089. 'additional_rows' => array(
  2090. array(
  2091. 'position' => 'bottom_of_list',
  2092. 'value' => '<input type="submit" name="edit_notify_boards" value="' . $txt['notifications_update'] . '" class="button_submit">',
  2093. 'align' => 'right',
  2094. ),
  2095. ),
  2096. );
  2097. // Create the board notification list.
  2098. createList($listOptions);
  2099. }
  2100. /**
  2101. * @todo needs a description
  2102. *
  2103. * @param int $memID id_member
  2104. * @return string
  2105. */
  2106. function list_getTopicNotificationCount($memID)
  2107. {
  2108. global $smcFunc, $user_info, $context, $modSettings;
  2109. $request = $smcFunc['db_query']('', '
  2110. SELECT COUNT(*)
  2111. FROM {db_prefix}log_notify AS ln' . (!$modSettings['postmod_active'] && $user_info['query_see_board'] === '1=1' ? '' : '
  2112. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)') . ($user_info['query_see_board'] === '1=1' ? '' : '
  2113. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)') . '
  2114. WHERE ln.id_member = {int:selected_member}' . ($user_info['query_see_board'] === '1=1' ? '' : '
  2115. AND {query_see_board}') . ($modSettings['postmod_active'] ? '
  2116. AND t.approved = {int:is_approved}' : ''),
  2117. array(
  2118. 'selected_member' => $memID,
  2119. 'is_approved' => 1,
  2120. )
  2121. );
  2122. list ($totalNotifications) = $smcFunc['db_fetch_row']($request);
  2123. $smcFunc['db_free_result']($request);
  2124. // @todo make this an integer before it gets returned
  2125. return $totalNotifications;
  2126. }
  2127. /**
  2128. * @todo Needs a description
  2129. *
  2130. * @param int $start
  2131. * @param int $items_per_page
  2132. * @param string $sort
  2133. * @param int $memID id_member
  2134. * @return array $notification_topics
  2135. */
  2136. function list_getTopicNotifications($start, $items_per_page, $sort, $memID)
  2137. {
  2138. global $smcFunc, $txt, $scripturl, $user_info, $context, $modSettings;
  2139. // All the topics with notification on...
  2140. $request = $smcFunc['db_query']('', '
  2141. SELECT
  2142. IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from, b.id_board, b.name,
  2143. t.id_topic, ms.subject, ms.id_member, IFNULL(mem.real_name, ms.poster_name) AS real_name_col,
  2144. ml.id_msg_modified, ml.poster_time, ml.id_member AS id_member_updated,
  2145. IFNULL(mem2.real_name, ml.poster_name) AS last_real_name
  2146. FROM {db_prefix}log_notify AS ln
  2147. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
  2148. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board AND {query_see_board})
  2149. INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
  2150. INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
  2151. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ms.id_member)
  2152. LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = ml.id_member)
  2153. LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
  2154. LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = b.id_board AND lmr.id_member = {int:current_member})
  2155. WHERE ln.id_member = {int:selected_member}
  2156. ORDER BY {raw:sort}
  2157. LIMIT {int:offset}, {int:items_per_page}',
  2158. array(
  2159. 'current_member' => $user_info['id'],
  2160. 'is_approved' => 1,
  2161. 'selected_member' => $memID,
  2162. 'sort' => $sort,
  2163. 'offset' => $start,
  2164. 'items_per_page' => $items_per_page,
  2165. )
  2166. );
  2167. $notification_topics = array();
  2168. while ($row = $smcFunc['db_fetch_assoc']($request))
  2169. {
  2170. censorText($row['subject']);
  2171. $notification_topics[] = array(
  2172. 'id' => $row['id_topic'],
  2173. 'poster_link' => empty($row['id_member']) ? $row['real_name_col'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name_col'] . '</a>',
  2174. 'poster_updated_link' => empty($row['id_member_updated']) ? $row['last_real_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['last_real_name'] . '</a>',
  2175. 'subject' => $row['subject'],
  2176. 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
  2177. 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
  2178. 'new' => $row['new_from'] <= $row['id_msg_modified'],
  2179. 'new_from' => $row['new_from'],
  2180. 'updated' => timeformat($row['poster_time']),
  2181. 'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new',
  2182. 'new_link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new">' . $row['subject'] . '</a>',
  2183. 'board_link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>',
  2184. );
  2185. }
  2186. $smcFunc['db_free_result']($request);
  2187. return $notification_topics;
  2188. }
  2189. /**
  2190. * @todo needs a description
  2191. *
  2192. * @param int $start
  2193. * @param int $items_per_page
  2194. * @param string $sort
  2195. * @param int $memID id_member
  2196. * @return array
  2197. */
  2198. function list_getBoardNotifications($start, $items_per_page, $sort, $memID)
  2199. {
  2200. global $smcFunc, $txt, $scripturl, $user_info;
  2201. $request = $smcFunc['db_query']('', '
  2202. SELECT b.id_board, b.name, IFNULL(lb.id_msg, 0) AS board_read, b.id_msg_updated
  2203. FROM {db_prefix}log_notify AS ln
  2204. INNER JOIN {db_prefix}boards AS b ON (b.id_board = ln.id_board)
  2205. LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
  2206. WHERE ln.id_member = {int:selected_member}
  2207. AND {query_see_board}
  2208. ORDER BY ' . $sort,
  2209. array(
  2210. 'current_member' => $user_info['id'],
  2211. 'selected_member' => $memID,
  2212. )
  2213. );
  2214. $notification_boards = array();
  2215. while ($row = $smcFunc['db_fetch_assoc']($request))
  2216. $notification_boards[] = array(
  2217. 'id' => $row['id_board'],
  2218. 'name' => $row['name'],
  2219. 'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
  2220. 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>',
  2221. 'new' => $row['board_read'] < $row['id_msg_updated']
  2222. );
  2223. $smcFunc['db_free_result']($request);
  2224. return $notification_boards;
  2225. }
  2226. /**
  2227. * @todo needs a description
  2228. *
  2229. * @param int $memID id_member
  2230. */
  2231. function loadThemeOptions($memID)
  2232. {
  2233. global $context, $options, $cur_profile, $smcFunc;
  2234. if (isset($_POST['default_options']))
  2235. $_POST['options'] = isset($_POST['options']) ? $_POST['options'] + $_POST['default_options'] : $_POST['default_options'];
  2236. if ($context['user']['is_owner'])
  2237. {
  2238. $context['member']['options'] = $options;
  2239. if (isset($_POST['options']) && is_array($_POST['options']))
  2240. foreach ($_POST['options'] as $k => $v)
  2241. $context['member']['options'][$k] = $v;
  2242. }
  2243. else
  2244. {
  2245. $request = $smcFunc['db_query']('', '
  2246. SELECT id_member, variable, value
  2247. FROM {db_prefix}themes
  2248. WHERE id_theme IN (1, {int:member_theme})
  2249. AND id_member IN (-1, {int:selected_member})',
  2250. array(
  2251. 'member_theme' => (int) $cur_profile['id_theme'],
  2252. 'selected_member' => $memID,
  2253. )
  2254. );
  2255. $temp = array();
  2256. while ($row = $smcFunc['db_fetch_assoc']($request))
  2257. {
  2258. if ($row['id_member'] == -1)
  2259. {
  2260. $temp[$row['variable']] = $row['value'];
  2261. continue;
  2262. }
  2263. if (isset($_POST['options'][$row['variable']]))
  2264. $row['value'] = $_POST['options'][$row['variable']];
  2265. $context['member']['options'][$row['variable']] = $row['value'];
  2266. }
  2267. $smcFunc['db_free_result']($request);
  2268. // Load up the default theme options for any missing.
  2269. foreach ($temp as $k => $v)
  2270. {
  2271. if (!isset($context['member']['options'][$k]))
  2272. $context['member']['options'][$k] = $v;
  2273. }
  2274. }
  2275. }
  2276. /**
  2277. * @todo needs a description
  2278. *
  2279. * @param int $memID id_member
  2280. */
  2281. function ignoreboards($memID)
  2282. {
  2283. global $txt, $context, $modSettings, $smcFunc, $cur_profile;
  2284. // Have the admins enabled this option?
  2285. if (empty($modSettings['allow_ignore_boards']))
  2286. fatal_lang_error('ignoreboards_disallowed', 'user');
  2287. // Find all the boards this user is allowed to see.
  2288. $request = $smcFunc['db_query']('order_by_board_order', '
  2289. SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level,
  2290. '. (!empty($cur_profile['ignore_boards']) ? 'b.id_board IN ({array_int:ignore_boards})' : '0') . ' AS is_ignored
  2291. FROM {db_prefix}boards AS b
  2292. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  2293. WHERE {query_see_board}
  2294. AND redirect = {string:empty_string}',
  2295. array(
  2296. 'ignore_boards' => !empty($cur_profile['ignore_boards']) ? explode(',', $cur_profile['ignore_boards']) : array(),
  2297. 'empty_string' => '',
  2298. )
  2299. );
  2300. $context['num_boards'] = $smcFunc['db_num_rows']($request);
  2301. $context['categories'] = array();
  2302. while ($row = $smcFunc['db_fetch_assoc']($request))
  2303. {
  2304. // This category hasn't been set up yet..
  2305. if (!isset($context['categories'][$row['id_cat']]))
  2306. $context['categories'][$row['id_cat']] = array(
  2307. 'id' => $row['id_cat'],
  2308. 'name' => $row['cat_name'],
  2309. 'boards' => array()
  2310. );
  2311. // Set this board up, and let the template know when it's a child. (indent them..)
  2312. $context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
  2313. 'id' => $row['id_board'],
  2314. 'name' => $row['name'],
  2315. 'child_level' => $row['child_level'],
  2316. 'selected' => $row['is_ignored'],
  2317. );
  2318. }
  2319. $smcFunc['db_free_result']($request);
  2320. // Now, let's sort the list of categories into the boards for templates that like that.
  2321. $temp_boards = array();
  2322. foreach ($context['categories'] as $category)
  2323. {
  2324. // Include a list of boards per category for easy toggling.
  2325. $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
  2326. $temp_boards[] = array(
  2327. 'name' => $category['name'],
  2328. 'child_ids' => array_keys($category['boards'])
  2329. );
  2330. $temp_boards = array_merge($temp_boards, array_values($category['boards']));
  2331. }
  2332. $max_boards = ceil(count($temp_boards) / 2);
  2333. if ($max_boards == 1)
  2334. $max_boards = 2;
  2335. // Now, alternate them so they can be shown left and right ;).
  2336. $context['board_columns'] = array();
  2337. for ($i = 0; $i < $max_boards; $i++)
  2338. {
  2339. $context['board_columns'][] = $temp_boards[$i];
  2340. if (isset($temp_boards[$i + $max_boards]))
  2341. $context['board_columns'][] = $temp_boards[$i + $max_boards];
  2342. else
  2343. $context['board_columns'][] = array();
  2344. }
  2345. loadThemeOptions($memID);
  2346. }
  2347. /**
  2348. * Load all the languages for the profile.
  2349. * @return boolean
  2350. */
  2351. function profileLoadLanguages()
  2352. {
  2353. global $context, $cur_profile, $language, $smcFunc;
  2354. $context['profile_languages'] = array();
  2355. // Get our languages!
  2356. getLanguages(true, true);
  2357. // Setup our languages.
  2358. foreach ($context['languages'] as $lang)
  2359. {
  2360. $context['profile_languages'][$lang['filename']] = strtr($lang['name'], array('-utf8' => ''));
  2361. }
  2362. ksort($context['profile_languages']);
  2363. // Return whether we should proceed with this.
  2364. return count($context['profile_languages']) > 1 ? true : false;
  2365. }
  2366. /**
  2367. * @todo needs description
  2368. *
  2369. * @return true
  2370. */
  2371. function profileLoadGroups()
  2372. {
  2373. global $cur_profile, $txt, $context, $smcFunc, $user_settings;
  2374. $context['member_groups'] = array(
  2375. 0 => array(
  2376. 'id' => 0,
  2377. 'name' => $txt['no_primary_membergroup'],
  2378. 'is_primary' => $cur_profile['id_group'] == 0,
  2379. 'can_be_additional' => false,
  2380. 'can_be_primary' => true,
  2381. )
  2382. );
  2383. $curGroups = explode(',', $cur_profile['additional_groups']);
  2384. // Load membergroups, but only those groups the user can assign.
  2385. $request = $smcFunc['db_query']('', '
  2386. SELECT group_name, id_group, hidden
  2387. FROM {db_prefix}membergroups
  2388. WHERE id_group != {int:moderator_group}
  2389. AND min_posts = {int:min_posts}' . (allowedTo('admin_forum') ? '' : '
  2390. AND group_type != {int:is_protected}') . '
  2391. ORDER BY min_posts, CASE WHEN id_group < {int:newbie_group} THEN id_group ELSE 4 END, group_name',
  2392. array(
  2393. 'moderator_group' => 3,
  2394. 'min_posts' => -1,
  2395. 'is_protected' => 1,
  2396. 'newbie_group' => 4,
  2397. )
  2398. );
  2399. while ($row = $smcFunc['db_fetch_assoc']($request))
  2400. {
  2401. // We should skip the administrator group if they don't have the admin_forum permission!
  2402. if ($row['id_group'] == 1 && !allowedTo('admin_forum'))
  2403. continue;
  2404. $context['member_groups'][$row['id_group']] = array(
  2405. 'id' => $row['id_group'],
  2406. 'name' => $row['group_name'],
  2407. 'is_primary' => $cur_profile['id_group'] == $row['id_group'],
  2408. 'is_additional' => in_array($row['id_group'], $curGroups),
  2409. 'can_be_additional' => true,
  2410. 'can_be_primary' => $row['hidden'] != 2,
  2411. );
  2412. }
  2413. $smcFunc['db_free_result']($request);
  2414. $context['member']['group_id'] = $user_settings['id_group'];
  2415. return true;
  2416. }
  2417. /**
  2418. * Load key signature context data.
  2419. *
  2420. * @return true
  2421. */
  2422. function profileLoadSignatureData()
  2423. {
  2424. global $modSettings, $context, $txt, $cur_profile, $smcFunc, $memberContext;
  2425. // Signature limits.
  2426. list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
  2427. $sig_limits = explode(',', $sig_limits);
  2428. $context['signature_enabled'] = isset($sig_limits[0]) ? $sig_limits[0] : 0;
  2429. $context['signature_limits'] = array(
  2430. 'max_length' => isset($sig_limits[1]) ? $sig_limits[1] : 0,
  2431. 'max_lines' => isset($sig_limits[2]) ? $sig_limits[2] : 0,
  2432. 'max_images' => isset($sig_limits[3]) ? $sig_limits[3] : 0,
  2433. 'max_smileys' => isset($sig_limits[4]) ? $sig_limits[4] : 0,
  2434. 'max_image_width' => isset($sig_limits[5]) ? $sig_limits[5] : 0,
  2435. 'max_image_height' => isset($sig_limits[6]) ? $sig_limits[6] : 0,
  2436. 'max_font_size' => isset($sig_limits[7]) ? $sig_limits[7] : 0,
  2437. 'bbc' => !empty($sig_bbc) ? explode(',', $sig_bbc) : array(),
  2438. );
  2439. // Kept this line in for backwards compatibility!
  2440. $context['max_signature_length'] = $context['signature_limits']['max_length'];
  2441. // Warning message for signature image limits?
  2442. $context['signature_warning'] = '';
  2443. if ($context['signature_limits']['max_image_width'] && $context['signature_limits']['max_image_height'])
  2444. $context['signature_warning'] = sprintf($txt['profile_error_signature_max_image_size'], $context['signature_limits']['max_image_width'], $context['signature_limits']['max_image_height']);
  2445. elseif ($context['signature_limits']['max_image_width'] || $context['signature_limits']['max_image_height'])
  2446. $context['signature_warning'] = sprintf($txt['profile_error_signature_max_image_' . ($context['signature_limits']['max_image_width'] ? 'width' : 'height')], $context['signature_limits'][$context['signature_limits']['max_image_width'] ? 'max_image_width' : 'max_image_height']);
  2447. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  2448. if (empty($context['do_preview']))
  2449. $context['member']['signature'] = empty($cur_profile['signature']) ? '' : str_replace(array('<br>', '<', '>', '"', '\''), array("\n", '&lt;', '&gt;', '&quot;', '&#039;'), $cur_profile['signature']);
  2450. else
  2451. {
  2452. $signature = !empty($_POST['signature']) ? $_POST['signature'] : '';
  2453. $validation = profileValidateSignature($signature);
  2454. if (empty($context['post_errors']))
  2455. {
  2456. loadLanguage('Errors');
  2457. $context['post_errors'] = array();
  2458. }
  2459. $context['post_errors'][] = 'signature_not_yet_saved';
  2460. if ($validation !== true && $validation !== false)
  2461. $context['post_errors'][] = $validation;
  2462. censorText($context['member']['signature']);
  2463. $context['member']['current_signature'] = $context['member']['signature'];
  2464. censorText($signature);
  2465. $context['member']['signature_preview'] = parse_bbc($signature, true, 'sig' . $memberContext[$context['id_member']]);
  2466. $context['member']['signature'] = $_POST['signature'];
  2467. }
  2468. return true;
  2469. }
  2470. /**
  2471. * Load avatar context data.
  2472. *
  2473. * @return true
  2474. */
  2475. function profileLoadAvatarData()
  2476. {
  2477. global $context, $cur_profile, $modSettings, $scripturl;
  2478. $context['avatar_url'] = $modSettings['avatar_url'];
  2479. // Default context.
  2480. $context['member']['avatar'] += array(
  2481. 'custom' => stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://') ? $cur_profile['avatar'] : 'http://',
  2482. 'selection' => $cur_profile['avatar'] == '' || (stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://')) ? '' : $cur_profile['avatar'],
  2483. 'id_attach' => $cur_profile['id_attach'],
  2484. 'filename' => $cur_profile['filename'],
  2485. 'allow_server_stored' => allowedTo('profile_server_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any')),
  2486. 'allow_upload' => allowedTo('profile_upload_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any')),
  2487. 'allow_external' => allowedTo('profile_remote_avatar') || (!$context['user']['is_owner'] && allowedTo('profile_extra_any')),
  2488. );
  2489. if ($cur_profile['avatar'] == '' && $cur_profile['id_attach'] > 0 && $context['member']['avatar']['allow_upload'])
  2490. {
  2491. $context['member']['avatar'] += array(
  2492. 'choice' => 'upload',
  2493. 'server_pic' => 'blank.png',
  2494. 'external' => 'http://'
  2495. );
  2496. $context['member']['avatar']['href'] = empty($cur_profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $cur_profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $cur_profile['filename'];
  2497. }
  2498. elseif ((stristr($cur_profile['avatar'], 'http://') || stristr($cur_profile['avatar'], 'https://')) && $context['member']['avatar']['allow_external'])
  2499. $context['member']['avatar'] += array(
  2500. 'choice' => 'external',
  2501. 'server_pic' => 'blank.png',
  2502. 'external' => $cur_profile['avatar']
  2503. );
  2504. elseif ($cur_profile['avatar'] != '' && file_exists($modSettings['avatar_directory'] . '/' . $cur_profile['avatar']) && $context['member']['avatar']['allow_server_stored'])
  2505. $context['member']['avatar'] += array(
  2506. 'choice' => 'server_stored',
  2507. 'server_pic' => $cur_profile['avatar'] == '' ? 'blank.png' : $cur_profile['avatar'],
  2508. 'external' => 'http://'
  2509. );
  2510. else
  2511. $context['member']['avatar'] += array(
  2512. 'choice' => 'none',
  2513. 'server_pic' => 'blank.png',
  2514. 'external' => 'http://'
  2515. );
  2516. // Get a list of all the avatars.
  2517. if ($context['member']['avatar']['allow_server_stored'])
  2518. {
  2519. $context['avatar_list'] = array();
  2520. $context['avatars'] = is_dir($modSettings['avatar_directory']) ? getAvatars('', 0) : array();
  2521. }
  2522. else
  2523. $context['avatars'] = array();
  2524. // Second level selected avatar...
  2525. $context['avatar_selected'] = substr(strrchr($context['member']['avatar']['server_pic'], '/'), 1);
  2526. return !empty($context['member']['avatar']['allow_server_stored']) || !empty($context['member']['avatar']['allow_external']) || !empty($context['member']['avatar']['allow_upload']);
  2527. }
  2528. /**
  2529. * Save a members group.
  2530. *
  2531. * @param int &$value
  2532. * @return true
  2533. */
  2534. function profileSaveGroups(&$value)
  2535. {
  2536. global $profile_vars, $old_profile, $context, $smcFunc, $cur_profile;
  2537. // Do we need to protect some groups?
  2538. if (!allowedTo('admin_forum'))
  2539. {
  2540. $request = $smcFunc['db_query']('', '
  2541. SELECT id_group
  2542. FROM {db_prefix}membergroups
  2543. WHERE group_type = {int:is_protected}',
  2544. array(
  2545. 'is_protected' => 1,
  2546. )
  2547. );
  2548. $protected_groups = array(1);
  2549. while ($row = $smcFunc['db_fetch_assoc']($request))
  2550. $protected_groups[] = $row['id_group'];
  2551. $smcFunc['db_free_result']($request);
  2552. $protected_groups = array_unique($protected_groups);
  2553. }
  2554. // The account page allows the change of your id_group - but not to a protected group!
  2555. if (empty($protected_groups) || count(array_intersect(array((int) $value, $old_profile['id_group']), $protected_groups)) == 0)
  2556. $value = (int) $value;
  2557. // ... otherwise it's the old group sir.
  2558. else
  2559. $value = $old_profile['id_group'];
  2560. // Find the additional membergroups (if any)
  2561. if (isset($_POST['additional_groups']) && is_array($_POST['additional_groups']))
  2562. {
  2563. $additional_groups = array();
  2564. foreach ($_POST['additional_groups'] as $group_id)
  2565. {
  2566. $group_id = (int) $group_id;
  2567. if (!empty($group_id) && (empty($protected_groups) || !in_array($group_id, $protected_groups)))
  2568. $additional_groups[] = $group_id;
  2569. }
  2570. // Put the protected groups back in there if you don't have permission to take them away.
  2571. $old_additional_groups = explode(',', $old_profile['additional_groups']);
  2572. foreach ($old_additional_groups as $group_id)
  2573. {
  2574. if (!empty($protected_groups) && in_array($group_id, $protected_groups))
  2575. $additional_groups[] = $group_id;
  2576. }
  2577. if (implode(',', $additional_groups) !== $old_profile['additional_groups'])
  2578. {
  2579. $profile_vars['additional_groups'] = implode(',', $additional_groups);
  2580. $cur_profile['additional_groups'] = implode(',', $additional_groups);
  2581. }
  2582. }
  2583. // Too often, people remove delete their own account, or something.
  2584. if (in_array(1, explode(',', $old_profile['additional_groups'])) || $old_profile['id_group'] == 1)
  2585. {
  2586. $stillAdmin = $value == 1 || (isset($additional_groups) && in_array(1, $additional_groups));
  2587. // If they would no longer be an admin, look for any other...
  2588. if (!$stillAdmin)
  2589. {
  2590. $request = $smcFunc['db_query']('', '
  2591. SELECT id_member
  2592. FROM {db_prefix}members
  2593. WHERE (id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0)
  2594. AND id_member != {int:selected_member}
  2595. LIMIT 1',
  2596. array(
  2597. 'admin_group' => 1,
  2598. 'selected_member' => $context['id_member'],
  2599. )
  2600. );
  2601. list ($another) = $smcFunc['db_fetch_row']($request);
  2602. $smcFunc['db_free_result']($request);
  2603. if (empty($another))
  2604. fatal_lang_error('at_least_one_admin', 'critical');
  2605. }
  2606. }
  2607. // If we are changing group status, update permission cache as necessary.
  2608. if ($value != $old_profile['id_group'] || isset($profile_vars['additional_groups']))
  2609. {
  2610. if ($context['user']['is_owner'])
  2611. $_SESSION['mc']['time'] = 0;
  2612. else
  2613. updateSettings(array('settings_updated' => time()));
  2614. }
  2615. return true;
  2616. }
  2617. /**
  2618. * The avatar is incredibly complicated, what with the options... and what not.
  2619. * @todo argh, the avatar here. Take this out of here!
  2620. *
  2621. * @param array &$value
  2622. * @return mixed
  2623. */
  2624. function profileSaveAvatarData(&$value)
  2625. {
  2626. global $modSettings, $sourcedir, $smcFunc, $profile_vars, $cur_profile, $context;
  2627. $memID = $context['id_member'];
  2628. if (empty($memID) && !empty($context['password_auth_failed']))
  2629. return false;
  2630. require_once($sourcedir . '/ManageAttachments.php');
  2631. // We're going to put this on a nice custom dir.
  2632. $uploadDir = $modSettings['custom_avatar_dir'];
  2633. $id_folder = 1;
  2634. $downloadedExternalAvatar = false;
  2635. if ($value == 'external' && allowedTo('profile_remote_avatar') && (stripos($_POST['userpicpersonal'], 'http://') === 0 || stripos($_POST['userpicpersonal'], 'https://') === 0) && strlen($_POST['userpicpersonal']) > 7 && !empty($modSettings['avatar_download_external']))
  2636. {
  2637. if (!is_writable($uploadDir))
  2638. fatal_lang_error('attachments_no_write', 'critical');
  2639. require_once($sourcedir . '/Subs-Package.php');
  2640. $url = parse_url($_POST['userpicpersonal']);
  2641. $contents = fetch_web_data($url['scheme'] . '://' . $url['host'] . (empty($url['port']) ? '' : ':' . $url['port']) . str_replace(' ', '%20', trim($url['path'])));
  2642. $new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
  2643. if ($contents != false && $tmpAvatar = fopen($new_filename, 'wb'))
  2644. {
  2645. fwrite($tmpAvatar, $contents);
  2646. fclose($tmpAvatar);
  2647. $downloadedExternalAvatar = true;
  2648. $_FILES['attachment']['tmp_name'] = $new_filename;
  2649. }
  2650. }
  2651. // Removes whatever attachment there was before updating
  2652. if ($value == 'none')
  2653. {
  2654. $profile_vars['avatar'] = '';
  2655. // Reset the attach ID.
  2656. $cur_profile['id_attach'] = 0;
  2657. $cur_profile['attachment_type'] = 0;
  2658. $cur_profile['filename'] = '';
  2659. removeAttachments(array('id_member' => $memID));
  2660. }
  2661. // An avatar from the server-stored galleries.
  2662. elseif ($value == 'server_stored' && allowedTo('profile_server_avatar'))
  2663. {
  2664. $profile_vars['avatar'] = strtr(empty($_POST['file']) ? (empty($_POST['cat']) ? '' : $_POST['cat']) : $_POST['file'], array('&amp;' => '&'));
  2665. $profile_vars['avatar'] = preg_match('~^([\w _!@%*=\-#()\[\]&.,]+/)?[\w _!@%*=\-#()\[\]&.,]+$~', $profile_vars['avatar']) != 0 && preg_match('/\.\./', $profile_vars['avatar']) == 0 && file_exists($modSettings['avatar_directory'] . '/' . $profile_vars['avatar']) ? ($profile_vars['avatar'] == 'blank.png' ? '' : $profile_vars['avatar']) : '';
  2666. // Clear current profile...
  2667. $cur_profile['id_attach'] = 0;
  2668. $cur_profile['attachment_type'] = 0;
  2669. $cur_profile['filename'] = '';
  2670. // Get rid of their old avatar. (if uploaded.)
  2671. removeAttachments(array('id_member' => $memID));
  2672. }
  2673. elseif ($value == 'external' && allowedTo('profile_remote_avatar') && (stripos($_POST['userpicpersonal'], 'http://') === 0 || stripos($_POST['userpicpersonal'], 'https://') === 0) && empty($modSettings['avatar_download_external']))
  2674. {
  2675. // We need these clean...
  2676. $cur_profile['id_attach'] = 0;
  2677. $cur_profile['attachment_type'] = 0;
  2678. $cur_profile['filename'] = '';
  2679. // Remove any attached avatar...
  2680. removeAttachments(array('id_member' => $memID));
  2681. $profile_vars['avatar'] = str_replace(' ', '%20', preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $_POST['userpicpersonal']));
  2682. if ($profile_vars['avatar'] == 'http://' || $profile_vars['avatar'] == 'http:///')
  2683. $profile_vars['avatar'] = '';
  2684. // Trying to make us do something we'll regret?
  2685. elseif (substr($profile_vars['avatar'], 0, 7) != 'http://' && substr($profile_vars['avatar'], 0, 8) != 'https://')
  2686. return 'bad_avatar_invalid_url';
  2687. // Should we check dimensions?
  2688. elseif (!empty($modSettings['avatar_max_height_external']) || !empty($modSettings['avatar_max_width_external']))
  2689. {
  2690. // Now let's validate the avatar.
  2691. $sizes = url_image_size($profile_vars['avatar']);
  2692. if (is_array($sizes) && (($sizes[0] > $modSettings['avatar_max_width_external'] && !empty($modSettings['avatar_max_width_external'])) || ($sizes[1] > $modSettings['avatar_max_height_external'] && !empty($modSettings['avatar_max_height_external']))))
  2693. {
  2694. // Houston, we have a problem. The avatar is too large!!
  2695. if ($modSettings['avatar_action_too_large'] == 'option_refuse')
  2696. return 'bad_avatar_too_large';
  2697. elseif ($modSettings['avatar_action_too_large'] == 'option_download_and_resize')
  2698. {
  2699. // @todo remove this if appropriate
  2700. require_once($sourcedir . '/Subs-Graphics.php');
  2701. if (downloadAvatar($profile_vars['avatar'], $memID, $modSettings['avatar_max_width_external'], $modSettings['avatar_max_height_external']))
  2702. {
  2703. $profile_vars['avatar'] = '';
  2704. $cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
  2705. $cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
  2706. $cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
  2707. }
  2708. else
  2709. return 'bad_avatar';
  2710. }
  2711. }
  2712. }
  2713. }
  2714. elseif (($value == 'upload' && allowedTo('profile_upload_avatar')) || $downloadedExternalAvatar)
  2715. {
  2716. if ((isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') || $downloadedExternalAvatar)
  2717. {
  2718. // Get the dimensions of the image.
  2719. if (!$downloadedExternalAvatar)
  2720. {
  2721. if (!is_writable($uploadDir))
  2722. fatal_lang_error('attachments_no_write', 'critical');
  2723. $new_filename = $uploadDir . '/' . getAttachmentFilename('avatar_tmp_' . $memID, false, null, true);
  2724. if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $new_filename))
  2725. fatal_lang_error('attach_timeout', 'critical');
  2726. $_FILES['attachment']['tmp_name'] = $new_filename;
  2727. }
  2728. $sizes = @getimagesize($_FILES['attachment']['tmp_name']);
  2729. // No size, then it's probably not a valid pic.
  2730. if ($sizes === false)
  2731. {
  2732. @unlink($_FILES['attachment']['tmp_name']);
  2733. return 'bad_avatar';
  2734. }
  2735. // Check whether the image is too large.
  2736. elseif ((!empty($modSettings['avatar_max_width_upload']) && $sizes[0] > $modSettings['avatar_max_width_upload']) || (!empty($modSettings['avatar_max_height_upload']) && $sizes[1] > $modSettings['avatar_max_height_upload']))
  2737. {
  2738. if (!empty($modSettings['avatar_resize_upload']))
  2739. {
  2740. // Attempt to chmod it.
  2741. @chmod($_FILES['attachment']['tmp_name'], 0644);
  2742. // @todo remove this require when appropriate
  2743. require_once($sourcedir . '/Subs-Graphics.php');
  2744. if (!downloadAvatar($_FILES['attachment']['tmp_name'], $memID, $modSettings['avatar_max_width_upload'], $modSettings['avatar_max_height_upload']))
  2745. {
  2746. @unlink($_FILES['attachment']['tmp_name']);
  2747. return 'bad_avatar';
  2748. }
  2749. // Reset attachment avatar data.
  2750. $cur_profile['id_attach'] = $modSettings['new_avatar_data']['id'];
  2751. $cur_profile['filename'] = $modSettings['new_avatar_data']['filename'];
  2752. $cur_profile['attachment_type'] = $modSettings['new_avatar_data']['type'];
  2753. }
  2754. // Admin doesn't want to resize large avatars, can't do much about it but to tell you to use a different one :(
  2755. else
  2756. {
  2757. @unlink($_FILES['attachment']['tmp_name']);
  2758. return 'bad_avatar_too_large';
  2759. }
  2760. }
  2761. // So far, so good, checks lies ahead!
  2762. elseif (is_array($sizes))
  2763. {
  2764. // Now try to find an infection.
  2765. require_once($sourcedir . '/Subs-Graphics.php');
  2766. if (!checkImageContents($_FILES['attachment']['tmp_name'], !empty($modSettings['avatar_paranoid'])))
  2767. {
  2768. // It's bad. Try to re-encode the contents?
  2769. if (empty($modSettings['avatar_reencode']) || (!reencodeImage($_FILES['attachment']['tmp_name'], $sizes[2])))
  2770. {
  2771. @unlink($_FILES['attachment']['tmp_name']);
  2772. return 'bad_avatar_fail_reencode';
  2773. }
  2774. // We were successful. However, at what price?
  2775. $sizes = @getimagesize($_FILES['attachment']['tmp_name']);
  2776. // Hard to believe this would happen, but can you bet?
  2777. if ($sizes === false)
  2778. {
  2779. @unlink($_FILES['attachment']['tmp_name']);
  2780. return 'bad_avatar';
  2781. }
  2782. }
  2783. $extensions = array(
  2784. '1' => 'gif',
  2785. '2' => 'jpg',
  2786. '3' => 'png',
  2787. '6' => 'bmp'
  2788. );
  2789. $extension = isset($extensions[$sizes[2]]) ? $extensions[$sizes[2]] : 'bmp';
  2790. $mime_type = 'image/' . ($extension === 'jpg' ? 'jpeg' : ($extension === 'bmp' ? 'x-ms-bmp' : $extension));
  2791. $destName = 'avatar_' . $memID . '_' . time() . '.' . $extension;
  2792. list ($width, $height) = getimagesize($_FILES['attachment']['tmp_name']);
  2793. $file_hash = '';
  2794. // Remove previous attachments this member might have had.
  2795. removeAttachments(array('id_member' => $memID));
  2796. $smcFunc['db_insert']('',
  2797. '{db_prefix}attachments',
  2798. array(
  2799. 'id_member' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'fileext' => 'string', 'size' => 'int',
  2800. 'width' => 'int', 'height' => 'int', 'mime_type' => 'string', 'id_folder' => 'int',
  2801. ),
  2802. array(
  2803. $memID, 1, $destName, $file_hash, $extension, filesize($_FILES['attachment']['tmp_name']),
  2804. (int) $width, (int) $height, $mime_type, $id_folder,
  2805. ),
  2806. array('id_attach')
  2807. );
  2808. $cur_profile['id_attach'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
  2809. $cur_profile['filename'] = $destName;
  2810. $cur_profile['attachment_type'] = 1;
  2811. $destinationPath = $uploadDir . '/' . (empty($file_hash) ? $destName : $cur_profile['id_attach'] . '_' . $file_hash . '.dat');
  2812. if (!rename($_FILES['attachment']['tmp_name'], $destinationPath))
  2813. {
  2814. // I guess a man can try.
  2815. removeAttachments(array('id_member' => $memID));
  2816. fatal_lang_error('attach_timeout', 'critical');
  2817. }
  2818. // Attempt to chmod it.
  2819. @chmod($uploadDir . '/' . $destinationPath, 0644);
  2820. }
  2821. $profile_vars['avatar'] = '';
  2822. // Delete any temporary file.
  2823. if (file_exists($_FILES['attachment']['tmp_name']))
  2824. @unlink($_FILES['attachment']['tmp_name']);
  2825. }
  2826. // Selected the upload avatar option and had one already uploaded before or didn't upload one.
  2827. else
  2828. $profile_vars['avatar'] = '';
  2829. }
  2830. else
  2831. $profile_vars['avatar'] = '';
  2832. // Setup the profile variables so it shows things right on display!
  2833. $cur_profile['avatar'] = $profile_vars['avatar'];
  2834. return false;
  2835. }
  2836. /**
  2837. * Validate the signature
  2838. *
  2839. * @param mixed &$value
  2840. * @return boolean|string
  2841. */
  2842. function profileValidateSignature(&$value)
  2843. {
  2844. global $sourcedir, $modSettings, $smcFunc, $txt;
  2845. require_once($sourcedir . '/Subs-Post.php');
  2846. // Admins can do whatever they hell they want!
  2847. if (!allowedTo('admin_forum'))
  2848. {
  2849. // Load all the signature limits.
  2850. list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
  2851. $sig_limits = explode(',', $sig_limits);
  2852. $disabledTags = !empty($sig_bbc) ? explode(',', $sig_bbc) : array();
  2853. $unparsed_signature = strtr(un_htmlspecialchars($value), array("\r" => '', '&#039' => '\''));
  2854. // Too many lines?
  2855. if (!empty($sig_limits[2]) && substr_count($unparsed_signature, "\n") >= $sig_limits[2])
  2856. {
  2857. $txt['profile_error_signature_max_lines'] = sprintf($txt['profile_error_signature_max_lines'], $sig_limits[2]);
  2858. return 'signature_max_lines';
  2859. }
  2860. // Too many images?!
  2861. if (!empty($sig_limits[3]) && (substr_count(strtolower($unparsed_signature), '[img') + substr_count(strtolower($unparsed_signature), '<img')) > $sig_limits[3])
  2862. {
  2863. $txt['profile_error_signature_max_image_count'] = sprintf($txt['profile_error_signature_max_image_count'], $sig_limits[3]);
  2864. return 'signature_max_image_count';
  2865. }
  2866. // What about too many smileys!
  2867. $smiley_parsed = $unparsed_signature;
  2868. parsesmileys($smiley_parsed);
  2869. $smiley_count = substr_count(strtolower($smiley_parsed), '<img') - substr_count(strtolower($unparsed_signature), '<img');
  2870. if (!empty($sig_limits[4]) && $sig_limits[4] == -1 && $smiley_count > 0)
  2871. return 'signature_allow_smileys';
  2872. elseif (!empty($sig_limits[4]) && $sig_limits[4] > 0 && $smiley_count > $sig_limits[4])
  2873. {
  2874. $txt['profile_error_signature_max_smileys'] = sprintf($txt['profile_error_signature_max_smileys'], $sig_limits[4]);
  2875. return 'signature_max_smileys';
  2876. }
  2877. // Maybe we are abusing font sizes?
  2878. if (!empty($sig_limits[7]) && preg_match_all('~\[size=([\d\.]+)?(px|pt|em|x-large|larger)~i', $unparsed_signature, $matches) !== false && isset($matches[2]))
  2879. {
  2880. foreach ($matches[1] as $ind => $size)
  2881. {
  2882. $limit_broke = 0;
  2883. // Attempt to allow all sizes of abuse, so to speak.
  2884. if ($matches[2][$ind] == 'px' && $size > $sig_limits[7])
  2885. $limit_broke = $sig_limits[7] . 'px';
  2886. elseif ($matches[2][$ind] == 'pt' && $size > ($sig_limits[7] * 0.75))
  2887. $limit_broke = ((int) $sig_limits[7] * 0.75) . 'pt';
  2888. elseif ($matches[2][$ind] == 'em' && $size > ((float) $sig_limits[7] / 16))
  2889. $limit_broke = ((float) $sig_limits[7] / 16) . 'em';
  2890. elseif ($matches[2][$ind] != 'px' && $matches[2][$ind] != 'pt' && $matches[2][$ind] != 'em' && $sig_limits[7] < 18)
  2891. $limit_broke = 'large';
  2892. if ($limit_broke)
  2893. {
  2894. $txt['profile_error_signature_max_font_size'] = sprintf($txt['profile_error_signature_max_font_size'], $limit_broke);
  2895. return 'signature_max_font_size';
  2896. }
  2897. }
  2898. }
  2899. // The difficult one - image sizes! Don't error on this - just fix it.
  2900. if ((!empty($sig_limits[5]) || !empty($sig_limits[6])))
  2901. {
  2902. // Get all BBC tags...
  2903. preg_match_all('~\[img(\s+width=([\d]+))?(\s+height=([\d]+))?(\s+width=([\d]+))?\s*\](?:<br>)*([^<">]+?)(?:<br>)*\[/img\]~i', $unparsed_signature, $matches);
  2904. // ... and all HTML ones.
  2905. preg_match_all('~<img\s+src=(?:")?((?:http://|ftp://|https://|ftps://).+?)(?:")?(?:\s+alt=(?:")?(.*?)(?:")?)?(?:\s?/)?>~i', $unparsed_signature, $matches2, PREG_PATTERN_ORDER);
  2906. // And stick the HTML in the BBC.
  2907. if (!empty($matches2))
  2908. {
  2909. foreach ($matches2[0] as $ind => $dummy)
  2910. {
  2911. $matches[0][] = $matches2[0][$ind];
  2912. $matches[1][] = '';
  2913. $matches[2][] = '';
  2914. $matches[3][] = '';
  2915. $matches[4][] = '';
  2916. $matches[5][] = '';
  2917. $matches[6][] = '';
  2918. $matches[7][] = $matches2[1][$ind];
  2919. }
  2920. }
  2921. $replaces = array();
  2922. // Try to find all the images!
  2923. if (!empty($matches))
  2924. {
  2925. foreach ($matches[0] as $key => $image)
  2926. {
  2927. $width = -1; $height = -1;
  2928. // Does it have predefined restraints? Width first.
  2929. if ($matches[6][$key])
  2930. $matches[2][$key] = $matches[6][$key];
  2931. if ($matches[2][$key] && $sig_limits[5] && $matches[2][$key] > $sig_limits[5])
  2932. {
  2933. $width = $sig_limits[5];
  2934. $matches[4][$key] = $matches[4][$key] * ($width / $matches[2][$key]);
  2935. }
  2936. elseif ($matches[2][$key])
  2937. $width = $matches[2][$key];
  2938. // ... and height.
  2939. if ($matches[4][$key] && $sig_limits[6] && $matches[4][$key] > $sig_limits[6])
  2940. {
  2941. $height = $sig_limits[6];
  2942. if ($width != -1)
  2943. $width = $width * ($height / $matches[4][$key]);
  2944. }
  2945. elseif ($matches[4][$key])
  2946. $height = $matches[4][$key];
  2947. // If the dimensions are still not fixed - we need to check the actual image.
  2948. if (($width == -1 && $sig_limits[5]) || ($height == -1 && $sig_limits[6]))
  2949. {
  2950. $sizes = url_image_size($matches[7][$key]);
  2951. if (is_array($sizes))
  2952. {
  2953. // Too wide?
  2954. if ($sizes[0] > $sig_limits[5] && $sig_limits[5])
  2955. {
  2956. $width = $sig_limits[5];
  2957. $sizes[1] = $sizes[1] * ($width / $sizes[0]);
  2958. }
  2959. // Too high?
  2960. if ($sizes[1] > $sig_limits[6] && $sig_limits[6])
  2961. {
  2962. $height = $sig_limits[6];
  2963. if ($width == -1)
  2964. $width = $sizes[0];
  2965. $width = $width * ($height / $sizes[1]);
  2966. }
  2967. elseif ($width != -1)
  2968. $height = $sizes[1];
  2969. }
  2970. }
  2971. // Did we come up with some changes? If so remake the string.
  2972. if ($width != -1 || $height != -1)
  2973. $replaces[$image] = '[img' . ($width != -1 ? ' width=' . round($width) : '') . ($height != -1 ? ' height=' . round($height) : '') . ']' . $matches[7][$key] . '[/img]';
  2974. }
  2975. if (!empty($replaces))
  2976. $value = str_replace(array_keys($replaces), array_values($replaces), $value);
  2977. }
  2978. }
  2979. // Any disabled BBC?
  2980. $disabledSigBBC = implode('|', $disabledTags);
  2981. if (!empty($disabledSigBBC))
  2982. {
  2983. if (preg_match('~\[(' . $disabledSigBBC . '[ =\]/])~i', $unparsed_signature, $matches) !== false && isset($matches[1]))
  2984. {
  2985. $disabledTags = array_unique($disabledTags);
  2986. $txt['profile_error_signature_disabled_bbc'] = sprintf($txt['profile_error_signature_disabled_bbc'], implode(', ', $disabledTags));
  2987. return 'signature_disabled_bbc';
  2988. }
  2989. }
  2990. }
  2991. preparsecode($value);
  2992. // Too long?
  2993. if (!allowedTo('admin_forum') && !empty($sig_limits[1]) && $smcFunc['strlen'](str_replace('<br>', "\n", $value)) > $sig_limits[1])
  2994. {
  2995. $_POST['signature'] = trim($smcFunc['htmlspecialchars'](str_replace('<br>', "\n", $value), ENT_QUOTES));
  2996. $txt['profile_error_signature_max_length'] = sprintf($txt['profile_error_signature_max_length'], $sig_limits[1]);
  2997. return 'signature_max_length';
  2998. }
  2999. return true;
  3000. }
  3001. /**
  3002. * Validate an email address.
  3003. *
  3004. * @param string $email
  3005. * @param int $memID = 0
  3006. * @return boolean|string
  3007. */
  3008. function profileValidateEmail($email, $memID = 0)
  3009. {
  3010. global $smcFunc, $context;
  3011. $email = strtr($email, array('&#039;' => '\''));
  3012. // Check the name and email for validity.
  3013. if (trim($email) == '')
  3014. return 'no_email';
  3015. if (preg_match('~^[0-9A-Za-z=_+\-/][0-9A-Za-z=_\'+\-/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$~', $email) == 0)
  3016. return 'bad_email';
  3017. // Email addresses should be and stay unique.
  3018. $request = $smcFunc['db_query']('', '
  3019. SELECT id_member
  3020. FROM {db_prefix}members
  3021. WHERE ' . ($memID != 0 ? 'id_member != {int:selected_member} AND ' : '') . '
  3022. email_address = {string:email_address}
  3023. LIMIT 1',
  3024. array(
  3025. 'selected_member' => $memID,
  3026. 'email_address' => $email,
  3027. )
  3028. );
  3029. if ($smcFunc['db_num_rows']($request) > 0)
  3030. return 'email_taken';
  3031. $smcFunc['db_free_result']($request);
  3032. return true;
  3033. }
  3034. /**
  3035. * Reload a users settings.
  3036. */
  3037. function profileReloadUser()
  3038. {
  3039. global $sourcedir, $modSettings, $context, $cur_profile, $smcFunc, $profile_vars;
  3040. // Log them back in - using the verify password as they must have matched and this one doesn't get changed by anyone!
  3041. if (isset($_POST['passwrd2']) && $_POST['passwrd2'] != '')
  3042. {
  3043. require_once($sourcedir . '/Subs-Auth.php');
  3044. setLoginCookie(60 * $modSettings['cookieTime'], $context['id_member'], sha1(sha1(strtolower($cur_profile['member_name']) . un_htmlspecialchars($_POST['passwrd2'])) . $cur_profile['password_salt']));
  3045. }
  3046. loadUserSettings();
  3047. writeLog();
  3048. }
  3049. /**
  3050. * Send the user a new activation email if they need to reactivate!
  3051. */
  3052. function profileSendActivation()
  3053. {
  3054. global $sourcedir, $profile_vars, $txt, $context, $scripturl, $smcFunc, $cookiename, $cur_profile, $language, $modSettings;
  3055. require_once($sourcedir . '/Subs-Post.php');
  3056. // Shouldn't happen but just in case.
  3057. if (empty($profile_vars['email_address']))
  3058. return;
  3059. $replacements = array(
  3060. 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $context['id_member'] . ';code=' . $profile_vars['validation_code'],
  3061. 'ACTIVATIONCODE' => $profile_vars['validation_code'],
  3062. 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $context['id_member'],
  3063. );
  3064. // Send off the email.
  3065. $emaildata = loadEmailTemplate('activate_reactivate', $replacements, empty($cur_profile['lngfile']) || empty($modSettings['userLanguage']) ? $language : $cur_profile['lngfile']);
  3066. sendmail($profile_vars['email_address'], $emaildata['subject'], $emaildata['body'], null, 'reactivate', false, 0);
  3067. // Log the user out.
  3068. $smcFunc['db_query']('', '
  3069. DELETE FROM {db_prefix}log_online
  3070. WHERE id_member = {int:selected_member}',
  3071. array(
  3072. 'selected_member' => $context['id_member'],
  3073. )
  3074. );
  3075. $_SESSION['log_time'] = 0;
  3076. $_SESSION['login_' . $cookiename] = serialize(array(0, '', 0));
  3077. if (isset($_COOKIE[$cookiename]))
  3078. $_COOKIE[$cookiename] = '';
  3079. loadUserSettings();
  3080. $context['user']['is_logged'] = false;
  3081. $context['user']['is_guest'] = true;
  3082. redirectexit('action=sendactivation');
  3083. }
  3084. /**
  3085. * Function to allow the user to choose group membership etc...
  3086. *
  3087. * @param int $memID id_member
  3088. */
  3089. function groupMembership($memID)
  3090. {
  3091. global $txt, $scripturl, $user_profile, $context, $smcFunc;
  3092. $curMember = $user_profile[$memID];
  3093. $context['primary_group'] = $curMember['id_group'];
  3094. // Can they manage groups?
  3095. $context['can_manage_membergroups'] = allowedTo('manage_membergroups');
  3096. $context['can_manage_protected'] = allowedTo('admin_forum');
  3097. $context['can_edit_primary'] = $context['can_manage_protected'];
  3098. $context['update_message'] = isset($_GET['msg']) && isset($txt['group_membership_msg_' . $_GET['msg']]) ? $txt['group_membership_msg_' . $_GET['msg']] : '';
  3099. // Get all the groups this user is a member of.
  3100. $groups = explode(',', $curMember['additional_groups']);
  3101. $groups[] = $curMember['id_group'];
  3102. // Ensure the query doesn't croak!
  3103. if (empty($groups))
  3104. $groups = array(0);
  3105. // Just to be sure...
  3106. foreach ($groups as $k => $v)
  3107. $groups[$k] = (int) $v;
  3108. // Get all the membergroups they can join.
  3109. $request = $smcFunc['db_query']('', '
  3110. SELECT mg.id_group, mg.group_name, mg.description, mg.group_type, mg.online_color, mg.hidden,
  3111. IFNULL(lgr.id_member, 0) AS pending
  3112. FROM {db_prefix}membergroups AS mg
  3113. LEFT JOIN {db_prefix}log_group_requests AS lgr ON (lgr.id_member = {int:selected_member} AND lgr.id_group = mg.id_group AND lgr.status = {int:status_open})
  3114. WHERE (mg.id_group IN ({array_int:group_list})
  3115. OR mg.group_type > {int:nonjoin_group_id})
  3116. AND mg.min_posts = {int:min_posts}
  3117. AND mg.id_group != {int:moderator_group}
  3118. ORDER BY group_name',
  3119. array(
  3120. 'group_list' => $groups,
  3121. 'selected_member' => $memID,
  3122. 'status_open' => 0,
  3123. 'nonjoin_group_id' => 1,
  3124. 'min_posts' => -1,
  3125. 'moderator_group' => 3,
  3126. )
  3127. );
  3128. // This beast will be our group holder.
  3129. $context['groups'] = array(
  3130. 'member' => array(),
  3131. 'available' => array()
  3132. );
  3133. while ($row = $smcFunc['db_fetch_assoc']($request))
  3134. {
  3135. // Can they edit their primary group?
  3136. if (($row['id_group'] == $context['primary_group'] && $row['group_type'] > 1) || ($row['hidden'] != 2 && $context['primary_group'] == 0 && in_array($row['id_group'], $groups)))
  3137. $context['can_edit_primary'] = true;
  3138. // If they can't manage (protected) groups, and it's not publically joinable or already assigned, they can't see it.
  3139. if (((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0)) && $row['id_group'] != $context['primary_group'])
  3140. continue;
  3141. $context['groups'][in_array($row['id_group'], $groups) ? 'member' : 'available'][$row['id_group']] = array(
  3142. 'id' => $row['id_group'],
  3143. 'name' => $row['group_name'],
  3144. 'desc' => $row['description'],
  3145. 'color' => $row['online_color'],
  3146. 'type' => $row['group_type'],
  3147. 'pending' => $row['pending'],
  3148. 'is_primary' => $row['id_group'] == $context['primary_group'],
  3149. 'can_be_primary' => $row['hidden'] != 2,
  3150. // Anything more than this needs to be done through account settings for security.
  3151. 'can_leave' => $row['id_group'] != 1 && $row['group_type'] > 1 ? true : false,
  3152. );
  3153. }
  3154. $smcFunc['db_free_result']($request);
  3155. // Add registered members on the end.
  3156. $context['groups']['member'][0] = array(
  3157. 'id' => 0,
  3158. 'name' => $txt['regular_members'],
  3159. 'desc' => $txt['regular_members_desc'],
  3160. 'type' => 0,
  3161. 'is_primary' => $context['primary_group'] == 0 ? true : false,
  3162. 'can_be_primary' => true,
  3163. 'can_leave' => 0,
  3164. );
  3165. // No changing primary one unless you have enough groups!
  3166. if (count($context['groups']['member']) < 2)
  3167. $context['can_edit_primary'] = false;
  3168. // In the special case that someone is requesting membership of a group, setup some special context vars.
  3169. if (isset($_REQUEST['request']) && isset($context['groups']['available'][(int) $_REQUEST['request']]) && $context['groups']['available'][(int) $_REQUEST['request']]['type'] == 2)
  3170. $context['group_request'] = $context['groups']['available'][(int) $_REQUEST['request']];
  3171. }
  3172. /**
  3173. * This function actually makes all the group changes
  3174. *
  3175. * @param array $profile_vars
  3176. * @param array $post_errors
  3177. * @param int $memID id_member
  3178. * @return mixed
  3179. */
  3180. function groupMembership2($profile_vars, $post_errors, $memID)
  3181. {
  3182. global $user_info, $sourcedir, $context, $user_profile, $modSettings, $txt, $smcFunc, $scripturl, $language;
  3183. // Let's be extra cautious...
  3184. if (!$context['user']['is_owner'] || empty($modSettings['show_group_membership']))
  3185. isAllowedTo('manage_membergroups');
  3186. if (!isset($_REQUEST['gid']) && !isset($_POST['primary']))
  3187. fatal_lang_error('no_access', false);
  3188. checkSession(isset($_GET['gid']) ? 'get' : 'post');
  3189. $old_profile = &$user_profile[$memID];
  3190. $context['can_manage_membergroups'] = allowedTo('manage_membergroups');
  3191. $context['can_manage_protected'] = allowedTo('admin_forum');
  3192. // By default the new primary is the old one.
  3193. $newPrimary = $old_profile['id_group'];
  3194. $addGroups = array_flip(explode(',', $old_profile['additional_groups']));
  3195. $canChangePrimary = $old_profile['id_group'] == 0 ? 1 : 0;
  3196. $changeType = isset($_POST['primary']) ? 'primary' : (isset($_POST['req']) ? 'request' : 'free');
  3197. // One way or another, we have a target group in mind...
  3198. $group_id = isset($_REQUEST['gid']) ? (int) $_REQUEST['gid'] : (int) $_POST['primary'];
  3199. $foundTarget = $changeType == 'primary' && $group_id == 0 ? true : false;
  3200. // Sanity check!!
  3201. if ($group_id == 1)
  3202. isAllowedTo('admin_forum');
  3203. // Protected groups too!
  3204. else
  3205. {
  3206. $request = $smcFunc['db_query']('', '
  3207. SELECT group_type
  3208. FROM {db_prefix}membergroups
  3209. WHERE id_group = {int:current_group}
  3210. LIMIT {int:limit}',
  3211. array(
  3212. 'current_group' => $group_id,
  3213. 'limit' => 1,
  3214. )
  3215. );
  3216. list ($is_protected) = $smcFunc['db_fetch_row']($request);
  3217. $smcFunc['db_free_result']($request);
  3218. if ($is_protected == 1)
  3219. isAllowedTo('admin_forum');
  3220. }
  3221. // What ever we are doing, we need to determine if changing primary is possible!
  3222. $request = $smcFunc['db_query']('', '
  3223. SELECT id_group, group_type, hidden, group_name
  3224. FROM {db_prefix}membergroups
  3225. WHERE id_group IN ({int:group_list}, {int:current_group})',
  3226. array(
  3227. 'group_list' => $group_id,
  3228. 'current_group' => $old_profile['id_group'],
  3229. )
  3230. );
  3231. while ($row = $smcFunc['db_fetch_assoc']($request))
  3232. {
  3233. // Is this the new group?
  3234. if ($row['id_group'] == $group_id)
  3235. {
  3236. $foundTarget = true;
  3237. $group_name = $row['group_name'];
  3238. // Does the group type match what we're doing - are we trying to request a non-requestable group?
  3239. if ($changeType == 'request' && $row['group_type'] != 2)
  3240. fatal_lang_error('no_access', false);
  3241. // What about leaving a requestable group we are not a member of?
  3242. elseif ($changeType == 'free' && $row['group_type'] == 2 && $old_profile['id_group'] != $row['id_group'] && !isset($addGroups[$row['id_group']]))
  3243. fatal_lang_error('no_access', false);
  3244. elseif ($changeType == 'free' && $row['group_type'] != 3 && $row['group_type'] != 2)
  3245. fatal_lang_error('no_access', false);
  3246. // We can't change the primary group if this is hidden!
  3247. if ($row['hidden'] == 2)
  3248. $canChangePrimary = false;
  3249. }
  3250. // If this is their old primary, can we change it?
  3251. if ($row['id_group'] == $old_profile['id_group'] && ($row['group_type'] > 1 || $context['can_manage_membergroups']) && $canChangePrimary !== false)
  3252. $canChangePrimary = 1;
  3253. // If we are not doing a force primary move, don't do it automatically if current primary is not 0.
  3254. if ($changeType != 'primary' && $old_profile['id_group'] != 0)
  3255. $canChangePrimary = false;
  3256. // If this is the one we are acting on, can we even act?
  3257. if ((!$context['can_manage_protected'] && $row['group_type'] == 1) || (!$context['can_manage_membergroups'] && $row['group_type'] == 0))
  3258. $canChangePrimary = false;
  3259. }
  3260. $smcFunc['db_free_result']($request);
  3261. // Didn't find the target?
  3262. if (!$foundTarget)
  3263. fatal_lang_error('no_access', false);
  3264. // Final security check, don't allow users to promote themselves to admin.
  3265. if ($context['can_manage_membergroups'] && !allowedTo('admin_forum'))
  3266. {
  3267. $request = $smcFunc['db_query']('', '
  3268. SELECT COUNT(permission)
  3269. FROM {db_prefix}permissions
  3270. WHERE id_group = {int:selected_group}
  3271. AND permission = {string:admin_forum}
  3272. AND add_deny = {int:not_denied}',
  3273. array(
  3274. 'selected_group' => $group_id,
  3275. 'not_denied' => 1,
  3276. 'admin_forum' => 'admin_forum',
  3277. )
  3278. );
  3279. list ($disallow) = $smcFunc['db_fetch_row']($request);
  3280. $smcFunc['db_free_result']($request);
  3281. if ($disallow)
  3282. isAllowedTo('admin_forum');
  3283. }
  3284. // If we're requesting, add the note then return.
  3285. if ($changeType == 'request')
  3286. {
  3287. $request = $smcFunc['db_query']('', '
  3288. SELECT id_member
  3289. FROM {db_prefix}log_group_requests
  3290. WHERE id_member = {int:selected_member}
  3291. AND id_group = {int:selected_group}
  3292. AND status = {int:status_open}',
  3293. array(
  3294. 'selected_member' => $memID,
  3295. 'selected_group' => $group_id,
  3296. 'status_open' => 0,
  3297. )
  3298. );
  3299. if ($smcFunc['db_num_rows']($request) != 0)
  3300. fatal_lang_error('profile_error_already_requested_group');
  3301. $smcFunc['db_free_result']($request);
  3302. // Log the request.
  3303. $smcFunc['db_insert']('',
  3304. '{db_prefix}log_group_requests',
  3305. array(
  3306. 'id_member' => 'int', 'id_group' => 'int', 'time_applied' => 'int', 'reason' => 'string-65534',
  3307. 'status' => 'int', 'id_member_acted' => 'int', 'member_name_acted' => 'string', 'time_acted' => 'int', 'act_reason' => 'string',
  3308. ),
  3309. array(
  3310. $memID, $group_id, time(), $_POST['reason'],
  3311. 0, 0, '', 0, '',
  3312. ),
  3313. array('id_request')
  3314. );
  3315. // Set up some data for our background task...
  3316. $data = serialize(array('id_member' => $memID, 'member_name' => $user_info['name'], 'id_group' => $group_id, 'group_name' => $group_name, 'reason' => $_POST['reason'], 'time' => time()));
  3317. // Add a background task to handle notifying people of this request
  3318. $smcFunc['db_insert']('insert', '{db_prefix}background_tasks',
  3319. array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
  3320. array('$sourcedir/tasks/GroupReq-Notify.php', 'GroupReq_Notify_Background', $data, 0), array()
  3321. );
  3322. return $changeType;
  3323. }
  3324. // Otherwise we are leaving/joining a group.
  3325. elseif ($changeType == 'free')
  3326. {
  3327. // Are we leaving?
  3328. if ($old_profile['id_group'] == $group_id || isset($addGroups[$group_id]))
  3329. {
  3330. if ($old_profile['id_group'] == $group_id)
  3331. $newPrimary = 0;
  3332. else
  3333. unset($addGroups[$group_id]);
  3334. }
  3335. // ... if not, must be joining.
  3336. else
  3337. {
  3338. // Can we change the primary, and do we want to?
  3339. if ($canChangePrimary)
  3340. {
  3341. if ($old_profile['id_group'] != 0)
  3342. $addGroups[$old_profile['id_group']] = -1;
  3343. $newPrimary = $group_id;
  3344. }
  3345. // Otherwise it's an additional group...
  3346. else
  3347. $addGroups[$group_id] = -1;
  3348. }
  3349. }
  3350. // Finally, we must be setting the primary.
  3351. elseif ($canChangePrimary)
  3352. {
  3353. if ($old_profile['id_group'] != 0)
  3354. $addGroups[$old_profile['id_group']] = -1;
  3355. if (isset($addGroups[$group_id]))
  3356. unset($addGroups[$group_id]);
  3357. $newPrimary = $group_id;
  3358. }
  3359. // Finally, we can make the changes!
  3360. foreach ($addGroups as $id => $dummy)
  3361. if (empty($id))
  3362. unset($addGroups[$id]);
  3363. $addGroups = implode(',', array_flip($addGroups));
  3364. // Ensure that we don't cache permissions if the group is changing.
  3365. if ($context['user']['is_owner'])
  3366. $_SESSION['mc']['time'] = 0;
  3367. else
  3368. updateSettings(array('settings_updated' => time()));
  3369. updateMemberData($memID, array('id_group' => $newPrimary, 'additional_groups' => $addGroups));
  3370. return $changeType;
  3371. }
  3372. ?>