usermanager.lib.php 214 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. *
  5. * Class UserManager
  6. *
  7. * This library provides functions for user management.
  8. * Include/require it in your code to use its functionality.
  9. * @package chamilo.library
  10. * @author Julio Montoya <gugli100@gmail.com> Social network groups added 2009/12
  11. *
  12. */
  13. class UserManager
  14. {
  15. // Constants for user extra field types.
  16. const USER_FIELD_TYPE_TEXT = 1;
  17. const USER_FIELD_TYPE_TEXTAREA = 2;
  18. const USER_FIELD_TYPE_RADIO = 3;
  19. const USER_FIELD_TYPE_SELECT = 4;
  20. const USER_FIELD_TYPE_SELECT_MULTIPLE = 5;
  21. const USER_FIELD_TYPE_DATE = 6;
  22. const USER_FIELD_TYPE_DATETIME = 7;
  23. const USER_FIELD_TYPE_DOUBLE_SELECT = 8;
  24. const USER_FIELD_TYPE_DIVIDER = 9;
  25. const USER_FIELD_TYPE_TAG = 10;
  26. const USER_FIELD_TYPE_TIMEZONE = 11;
  27. const USER_FIELD_TYPE_SOCIAL_PROFILE = 12;
  28. const USER_FIELD_TYPE_FILE = 13;
  29. const USER_FIELD_TYPE_MOBILE_PHONE_NUMBER = 14;
  30. /**
  31. * The default constructor only instanciates an empty user object
  32. */
  33. public function __construct()
  34. {
  35. }
  36. /**
  37. * Creates a new user for the platform
  38. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
  39. * @author Roan Embrechts <roan_embrechts@yahoo.com>
  40. * @param string Firstname
  41. * @param string Lastname
  42. * @param int Status (1 for course tutor, 5 for student, 6 for anonymous)
  43. * @param string e-mail address
  44. * @param string Login
  45. * @param string Password
  46. * @param string Any official code (optional)
  47. * @param string User language (optional)
  48. * @param string Phone number (optional)
  49. * @param string Picture URI (optional)
  50. * @param string Authentication source (optional, defaults to 'platform', dependind on constant)
  51. * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00')
  52. * @param int Whether the account is enabled or disabled by default
  53. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  54. * @param array Extra fields
  55. * @param string Encrypt method used if password is given encrypted. Set to an empty string by default
  56. * @return mixed new user id - if the new user creation succeeds, false otherwise
  57. * @desc The function tries to retrieve $_user['user_id'] from the global space. If it exists, $_user['user_id'] is the creator id. If a problem arises, it stores the error message in global $api_failureList
  58. * @assert ('Sam','Gamegie',5,'sam@example.com','jo','jo') > 1
  59. * @assert ('Pippin','Took',null,null,'jo','jo') === false
  60. */
  61. public static function create_user(
  62. $firstName,
  63. $lastName,
  64. $status,
  65. $email,
  66. $loginName,
  67. $password,
  68. $official_code = '',
  69. $language = '',
  70. $phone = '',
  71. $picture_uri = '',
  72. $auth_source = PLATFORM_AUTH_SOURCE,
  73. $expiration_date = '0000-00-00 00:00:00',
  74. $active = 1,
  75. $hr_dept_id = 0,
  76. $extra = null,
  77. $encrypt_method = '',
  78. $send_mail = false
  79. ) {
  80. $hook = HookCreateUser::create();
  81. if (!empty($hook)) {
  82. $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE);
  83. }
  84. global $_user, $_configuration;
  85. $original_password = $password;
  86. $access_url_id = 1;
  87. if (api_get_multiple_access_url()) {
  88. $access_url_id = api_get_current_access_url_id();
  89. }
  90. if (is_array($_configuration[$access_url_id]) &&
  91. isset($_configuration[$access_url_id]['hosting_limit_users']) &&
  92. $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
  93. $num = self::get_number_of_users();
  94. if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
  95. api_warn_hosting_contact('hosting_limit_users');
  96. return api_set_failure('portal users limit reached');
  97. }
  98. }
  99. if ($status === 1 &&
  100. is_array($_configuration[$access_url_id]) &&
  101. isset($_configuration[$access_url_id]['hosting_limit_teachers']) &&
  102. $_configuration[$access_url_id]['hosting_limit_teachers'] > 0
  103. ) {
  104. $num = self::get_number_of_users(1);
  105. if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
  106. api_warn_hosting_contact('hosting_limit_teachers');
  107. return api_set_failure('portal teachers limit reached');
  108. }
  109. }
  110. $firstName = Security::remove_XSS($firstName);
  111. $lastName = Security::remove_XSS($lastName);
  112. $loginName = Security::remove_XSS($loginName);
  113. $phone = Security::remove_XSS($phone);
  114. // database table definition
  115. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  116. //Checking the user language
  117. $languages = api_get_languages();
  118. $language = strtolower($language);
  119. if (!in_array($language, $languages['folder'])) {
  120. $language = api_get_setting('platformLanguage');
  121. }
  122. if ($_user['user_id']) {
  123. $creator_id = intval($_user['user_id']);
  124. } else {
  125. $creator_id = '';
  126. }
  127. // First check wether the login already exists
  128. if (!self::is_username_available($loginName)) {
  129. return api_set_failure('login-pass already taken');
  130. }
  131. //$password = "PLACEHOLDER";
  132. if (empty($encrypt_method)) {
  133. $password = api_get_encrypted_password($password);
  134. } else {
  135. if ($_configuration['password_encryption'] === $encrypt_method) {
  136. if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
  137. return api_set_failure('encrypt_method invalid');
  138. } else if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
  139. return api_set_failure('encrypt_method invalid');
  140. }
  141. } else {
  142. return api_set_failure('encrypt_method invalid');
  143. }
  144. }
  145. $current_date = api_get_utc_datetime();
  146. $sql = "INSERT INTO $table_user
  147. SET lastname = '".Database::escape_string(trim($lastName))."',
  148. firstname = '".Database::escape_string(trim($firstName))."',
  149. username = '".Database::escape_string(trim($loginName))."',
  150. status = '".Database::escape_string($status)."',
  151. password = '".Database::escape_string($password)."',
  152. email = '".Database::escape_string($email)."',
  153. official_code = '".Database::escape_string($official_code)."',
  154. picture_uri = '".Database::escape_string($picture_uri)."',
  155. creator_id = '".Database::escape_string($creator_id)."',
  156. auth_source = '".Database::escape_string($auth_source)."',
  157. phone = '".Database::escape_string($phone)."',
  158. language = '".Database::escape_string($language)."',
  159. registration_date = '".$current_date."',
  160. expiration_date = '".Database::escape_string($expiration_date)."',
  161. hr_dept_id = '".Database::escape_string($hr_dept_id)."',
  162. active = '".Database::escape_string($active)."'";
  163. $result = Database::query($sql);
  164. if ($result) {
  165. //echo "id returned";
  166. $return = Database::insert_id();
  167. if (api_get_multiple_access_url()) {
  168. UrlManager::add_user_to_url($return, api_get_current_access_url_id());
  169. } else {
  170. //we are adding by default the access_url_user table with access_url_id = 1
  171. UrlManager::add_user_to_url($return, 1);
  172. }
  173. if (!empty($email) && $send_mail) {
  174. $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS);
  175. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  176. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  177. $email_admin = api_get_setting('emailAdministrator');
  178. if (api_is_multiple_url_enabled()) {
  179. $access_url_id = api_get_current_access_url_id();
  180. if ($access_url_id != -1) {
  181. $url = api_get_access_url($access_url_id);
  182. $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstName, $lastName)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$loginName."\n".get_lang('Pass')." : ".stripslashes($original_password)."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
  183. }
  184. } else {
  185. $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstName, $lastName)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$loginName."\n".get_lang('Pass')." : ".stripslashes($original_password)."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$_configuration['root_web']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
  186. }
  187. /* MANAGE EVENT WITH MAIL */
  188. if (EventsMail::check_if_using_class('user_registration')) {
  189. $values["about_user"] = $return;
  190. $values["password"] = $original_password;
  191. $values["send_to"] = array($return);
  192. $values["prior_lang"] = null;
  193. EventsDispatcher::events('user_registration', $values);
  194. } else {
  195. $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null;
  196. $additionalParameters = array(
  197. 'smsType' => ClockworksmsPlugin::WELCOME_LOGIN_PASSWORD,
  198. 'userId' => $return,
  199. 'mobilePhoneNumber' => $phoneNumber,
  200. 'password' => $original_password
  201. );
  202. api_mail_html(
  203. $recipient_name,
  204. $email,
  205. $emailsubject,
  206. $emailbody,
  207. $sender_name,
  208. $email_admin,
  209. null,
  210. null,
  211. null,
  212. $additionalParameters
  213. );
  214. }
  215. /* ENDS MANAGE EVENT WITH MAIL */
  216. }
  217. event_system(LOG_USER_CREATE, LOG_USER_ID, $return);
  218. } else {
  219. return api_set_failure('error inserting in Database');
  220. }
  221. if (is_array($extra) && count($extra) > 0) {
  222. $res = true;
  223. foreach ($extra as $fname => $fvalue) {
  224. $res = $res && self::update_extra_field_value($return, $fname, $fvalue);
  225. }
  226. }
  227. self::update_extra_field_value($return, 'already_logged_in', 'false');
  228. if (!empty($hook)) {
  229. $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST);
  230. }
  231. return $return;
  232. }
  233. /**
  234. * Can user be deleted? This function checks whether there's a course
  235. * in which the given user is the
  236. * only course administrator. If that is the case, the user can't be
  237. * deleted because the course would remain without a course admin.
  238. * @param int $user_id The user id
  239. * @return boolean true if user can be deleted
  240. * @assert (null) === false
  241. * @assert (-1) === false
  242. * @assert ('abc') === false
  243. */
  244. public static function can_delete_user($user_id)
  245. {
  246. global $_configuration;
  247. if (isset($_configuration['deny_delete_users']) &&
  248. $_configuration['deny_delete_users'] == true
  249. ) {
  250. return false;
  251. }
  252. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  253. if ($user_id != strval(intval($user_id)))
  254. return false;
  255. if ($user_id === false)
  256. return false;
  257. $sql = "SELECT * FROM $table_course_user
  258. WHERE status = '1' AND user_id = '".$user_id."'";
  259. $res = Database::query($sql);
  260. while ($course = Database::fetch_object($res)) {
  261. $sql = "SELECT user_id FROM $table_course_user
  262. WHERE status='1' AND course_code ='".Database::escape_string($course->course_code)."'";
  263. $res2 = Database::query($sql);
  264. if (Database::num_rows($res2) == 1) {
  265. return false;
  266. }
  267. }
  268. return true;
  269. }
  270. /**
  271. * Delete a user from the platform, and all its belongings. This is a
  272. * very dangerous function that should only be accessible by
  273. * super-admins. Other roles should only be able to disable a user,
  274. * which removes access to the platform but doesn't delete anything.
  275. * @param int The ID of th user to be deleted
  276. * @return boolean true if user is successfully deleted, false otherwise
  277. * @assert (null) === false
  278. * @assert ('abc') === false
  279. */
  280. public static function delete_user($user_id)
  281. {
  282. if ($user_id != strval(intval($user_id))) {
  283. return false;
  284. }
  285. if ($user_id === false) {
  286. return false;
  287. }
  288. if (!self::can_delete_user($user_id)) {
  289. return false;
  290. }
  291. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  292. $usergroup_rel_user = Database :: get_main_table(TABLE_USERGROUP_REL_USER);
  293. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  294. $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  295. $table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  296. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  297. $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  298. $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  299. $table_group = Database :: get_course_table(TABLE_GROUP_USER);
  300. $table_work = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  301. // Unsubscribe the user from all groups in all his courses
  302. $sql = "SELECT c.id FROM $table_course c, $table_course_user cu
  303. WHERE
  304. cu.user_id = '".$user_id."' AND
  305. relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  306. c.code = cu.course_code";
  307. $res = Database::query($sql);
  308. while ($course = Database::fetch_object($res)) {
  309. $sql = "DELETE FROM $table_group
  310. WHERE c_id = {$course->id} AND user_id = $user_id";
  311. Database::query($sql);
  312. }
  313. // Unsubscribe user from all classes
  314. //Classes are not longer supported
  315. /* $sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
  316. Database::query($sql); */
  317. // Unsubscribe user from usergroup_rel_user
  318. $sql = "DELETE FROM $usergroup_rel_user WHERE user_id = '".$user_id."'";
  319. Database::query($sql);
  320. // Unsubscribe user from all courses
  321. $sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
  322. Database::query($sql);
  323. // Unsubscribe user from all courses in sessions
  324. $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
  325. Database::query($sql);
  326. // If the user was added as a id_coach then set the current admin as coach see BT#
  327. $currentUserId = api_get_user_id();
  328. $sql = "UPDATE $table_session SET id_coach = $currentUserId WHERE id_coach = '".$user_id."'";
  329. Database::query($sql);
  330. $sql = "UPDATE $table_session SET id_coach = $currentUserId WHERE session_admin_id = '".$user_id."'";
  331. Database::query($sql);
  332. // Unsubscribe user from all sessions
  333. $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
  334. Database::query($sql);
  335. // Delete user picture
  336. /* TODO: Logic about api_get_setting('split_users_upload_directory') == 'true'
  337. a user has 4 differnt sized photos to be deleted. */
  338. $user_info = api_get_user_info($user_id);
  339. if (strlen($user_info['picture_uri']) > 0) {
  340. $img_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/'.$user_info['picture_uri'];
  341. if (file_exists($img_path))
  342. unlink($img_path);
  343. }
  344. // Delete the personal course categories
  345. $course_cat_table = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  346. $sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
  347. Database::query($sql);
  348. // Delete user from database
  349. $sql = "DELETE FROM $table_user WHERE user_id = '".$user_id."'";
  350. Database::query($sql);
  351. // Delete user from the admin table
  352. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  353. Database::query($sql);
  354. // Delete the personal agenda-items from this user
  355. $agenda_table = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
  356. $sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
  357. Database::query($sql);
  358. $gradebook_results_table = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
  359. $sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
  360. Database::query($sql);
  361. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  362. $sqlv = "DELETE FROM $t_ufv WHERE user_id = $user_id";
  363. Database::query($sqlv);
  364. require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
  365. if (api_get_multiple_access_url()) {
  366. $url_id = api_get_current_access_url_id();
  367. UrlManager::delete_url_rel_user($user_id, $url_id);
  368. } else {
  369. //we delete the user from the url_id =1
  370. UrlManager::delete_url_rel_user($user_id, 1);
  371. }
  372. if (api_get_setting('allow_social_tool') == 'true') {
  373. require_once api_get_path(LIBRARY_PATH).'group_portal_manager.lib.php';
  374. //Delete user from portal groups
  375. $group_list = GroupPortalManager::get_groups_by_user($user_id);
  376. if (!empty($group_list)) {
  377. foreach ($group_list as $group_id => $data) {
  378. GroupPortalManager::delete_user_rel_group($user_id, $group_id);
  379. }
  380. }
  381. // Delete user from friend lists
  382. SocialManager::remove_user_rel_user($user_id, true);
  383. }
  384. // Removing survey invitation
  385. survey_manager::delete_all_survey_invitations_by_user($user_id);
  386. // Delete students works
  387. $sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
  388. Database::query($sql);
  389. // Add event to system log
  390. $user_id_manager = api_get_user_id();
  391. event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info);
  392. event_system(LOG_USER_DELETE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager, null, $user_info);
  393. return true;
  394. }
  395. /**
  396. * Deletes users completely. Can be called either as:
  397. * - UserManager :: delete_users(1, 2, 3); or
  398. * - UserManager :: delete_users(array(1, 2, 3));
  399. * @param array|int $ids
  400. * @return boolean True if at least one user was successfuly deleted. False otherwise.
  401. * @author Laurent Opprecht
  402. * @uses UserManager::delete_user() to actually delete each user
  403. * @assert (null) === false
  404. * @assert (-1) === false
  405. * @assert (array(-1)) === false
  406. */
  407. static function delete_users($ids = array())
  408. {
  409. $result = false;
  410. $ids = is_array($ids) ? $ids : func_get_args();
  411. if (!is_array($ids) or count($ids) == 0) { return false; }
  412. $ids = array_map('intval', $ids);
  413. foreach ($ids as $id) {
  414. if (empty($id) or $id < 1) { continue; }
  415. $deleted = self::delete_user($id);
  416. $result = $deleted || $result;
  417. }
  418. return $result;
  419. }
  420. /**
  421. * Disable users. Can be called either as:
  422. * - UserManager :: deactivate_users(1, 2, 3);
  423. * - UserManager :: deactivate_users(array(1, 2, 3));
  424. * @param array|int $ids
  425. * @return boolean
  426. * @author Laurent Opprecht
  427. * @assert (null) === false
  428. * @assert (array(-1)) === false
  429. */
  430. static function deactivate_users($ids = array())
  431. {
  432. if (empty($ids)) {
  433. return false;
  434. }
  435. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  436. $ids = is_array($ids) ? $ids : func_get_args();
  437. $ids = array_map('intval', $ids);
  438. $ids = implode(',', $ids);
  439. $sql = "UPDATE $table_user SET active = 0 WHERE user_id IN ($ids)";
  440. $r = Database::query($sql);
  441. if ($r !== false) {
  442. event_system(LOG_USER_DISABLE,LOG_USER_ID,$ids);
  443. }
  444. return $r;
  445. }
  446. /**
  447. * Enable users. Can be called either as:
  448. * - UserManager :: activate_users(1, 2, 3);
  449. * - UserManager :: activate_users(array(1, 2, 3));
  450. * @param array|int IDs of the users to enable
  451. * @return boolean
  452. * @author Laurent Opprecht
  453. * @assert (null) === false
  454. * @assert (array(-1)) === false
  455. */
  456. static function activate_users($ids = array())
  457. {
  458. if (empty($ids)) {
  459. return false;
  460. }
  461. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  462. $ids = is_array($ids) ? $ids : func_get_args();
  463. $ids = array_map('intval', $ids);
  464. $ids = implode(',', $ids);
  465. $sql = "UPDATE $table_user SET active = 1 WHERE user_id IN ($ids)";
  466. $r = Database::query($sql);
  467. if ($r !== false) {
  468. event_system(LOG_USER_ENABLE,LOG_USER_ID,$ids);
  469. }
  470. return $r;
  471. }
  472. /**
  473. * Update user information with new openid
  474. * @param int $user_id
  475. * @param string $openid
  476. * @return boolean true if the user information was updated
  477. * @assert (false,'') === false
  478. * @assert (-1,'') === false
  479. */
  480. public static function update_openid($user_id, $openid)
  481. {
  482. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  483. if ($user_id != strval(intval($user_id)))
  484. return false;
  485. if ($user_id === false)
  486. return false;
  487. $sql = "UPDATE $table_user SET
  488. openid='".Database::escape_string($openid)."'";
  489. $sql .= " WHERE user_id='$user_id'";
  490. return Database::query($sql);
  491. }
  492. /**
  493. * Update user information with all the parameters passed to this function
  494. * @param int The ID of the user to be updated
  495. * @param string The user's firstname
  496. * @param string The user's lastname
  497. * @param string The user's username (login)
  498. * @param string The user's password
  499. * @param string The authentication source (default: "platform")
  500. * @param string The user's e-mail address
  501. * @param int The user's status
  502. * @param string The user's official code (usually just an internal institutional code)
  503. * @param string The user's phone number
  504. * @param string The user's picture URL (internal to the Chamilo directory)
  505. * @param int The user ID of the person who registered this user (optional, defaults to null)
  506. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  507. * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
  508. * @return boolean true if the user information was updated
  509. * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
  510. */
  511. public static function update_user(
  512. $user_id,
  513. $firstname,
  514. $lastname,
  515. $username,
  516. $password = null,
  517. $auth_source = null,
  518. $email,
  519. $status,
  520. $official_code,
  521. $phone,
  522. $picture_uri,
  523. $expiration_date,
  524. $active,
  525. $creator_id = null,
  526. $hr_dept_id = 0,
  527. $extra = null,
  528. $language = 'english',
  529. $encrypt_method = '',
  530. $send_email = false,
  531. $reset_password = 0
  532. ) {
  533. $hook = HookUpdateUser::create();
  534. if (!empty($hook)) {
  535. $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
  536. }
  537. global $_configuration;
  538. $original_password = $password;
  539. if (empty($user_id)) { return false; }
  540. $user_info = api_get_user_info($user_id, false, true);
  541. if ($reset_password == 0) {
  542. $password = null;
  543. $auth_source = $user_info['auth_source'];
  544. } elseif ($reset_password == 1) {
  545. $original_password = $password = api_generate_password();
  546. $auth_source = PLATFORM_AUTH_SOURCE;
  547. } elseif ($reset_password == 2) {
  548. $password = $password;
  549. $auth_source = PLATFORM_AUTH_SOURCE;
  550. } elseif ($reset_password == 3) {
  551. $password = $password;
  552. $auth_source = $auth_source;
  553. }
  554. if ($user_id != strval(intval($user_id)))
  555. return false;
  556. if ($user_id === false)
  557. return false;
  558. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  559. //Checking the user language
  560. $languages = api_get_languages();
  561. if (!in_array($language, $languages['folder'])) {
  562. $language = api_get_setting('platformLanguage');
  563. }
  564. $change_active = 0;
  565. if ($user_info['active'] != $active) {
  566. $change_active = 1;
  567. }
  568. $sql = "UPDATE $table_user SET
  569. lastname='".Database::escape_string($lastname)."',
  570. firstname='".Database::escape_string($firstname)."',
  571. username='".Database::escape_string($username)."',
  572. language='".Database::escape_string($language)."',";
  573. if (!is_null($password)) {
  574. if ($encrypt_method == '') {
  575. $password = api_get_encrypted_password($password);
  576. } else {
  577. if ($_configuration['password_encryption'] === $encrypt_method) {
  578. if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
  579. return api_set_failure('encrypt_method invalid');
  580. } else if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
  581. return api_set_failure('encrypt_method invalid');
  582. }
  583. } else {
  584. return api_set_failure('encrypt_method invalid');
  585. }
  586. }
  587. $sql .= " password='".Database::escape_string($password)."',";
  588. }
  589. if (!is_null($auth_source)) {
  590. $sql .= " auth_source='".Database::escape_string($auth_source)."',";
  591. }
  592. $sql .= "
  593. email='".Database::escape_string($email)."',
  594. status='".Database::escape_string($status)."',
  595. official_code='".Database::escape_string($official_code)."',
  596. phone='".Database::escape_string($phone)."',
  597. picture_uri='".Database::escape_string($picture_uri)."',
  598. expiration_date='".Database::escape_string($expiration_date)."',
  599. active='".Database::escape_string($active)."',
  600. hr_dept_id=".intval($hr_dept_id);
  601. if (!is_null($creator_id)) {
  602. $sql .= ", creator_id='".intval($creator_id)."'";
  603. }
  604. $sql .= " WHERE user_id='$user_id'";
  605. $return = Database::query($sql);
  606. if ($change_active == 1 && $return) {
  607. if ($active == 1) {
  608. $event_title = LOG_USER_ENABLE;
  609. } else {
  610. $event_title = LOG_USER_DISABLE;
  611. }
  612. event_system($event_title, LOG_USER_ID, $user_id);
  613. }
  614. if (is_array($extra) && count($extra) > 0) {
  615. $res = true;
  616. foreach ($extra as $fname => $fvalue) {
  617. $res = $res && self::update_extra_field_value($user_id, $fname, $fvalue);
  618. }
  619. }
  620. if (!empty($email) && $send_email) {
  621. $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
  622. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  623. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  624. $email_admin = api_get_setting('emailAdministrator');
  625. if (api_is_multiple_url_enabled()) {
  626. $access_url_id = api_get_current_access_url_id();
  627. if ($access_url_id != -1) {
  628. $url = api_get_access_url($access_url_id);
  629. $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
  630. }
  631. } else {
  632. $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$_configuration['root_web']."\n\n".get_lang('Problem')."\n\n".get_lang('SignatureFormula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
  633. }
  634. @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
  635. }
  636. if (!empty($hook)) {
  637. $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
  638. }
  639. return $return;
  640. }
  641. /**
  642. * Disables or enables a user
  643. * @param int user_id
  644. * @param int Enable or disable
  645. * @return void
  646. * @assert (-1,0) === false
  647. * @assert (1,1) === true
  648. */
  649. private static function change_active_state($user_id, $active)
  650. {
  651. if (strval(intval($user_id)) != $user_id) {
  652. return false;
  653. }
  654. if ($user_id < 1) {
  655. return false;
  656. }
  657. $user_id = intval($user_id);
  658. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  659. $sql = "UPDATE $table_user SET active = '$active' WHERE user_id = '$user_id';";
  660. $r = Database::query($sql);
  661. $ev = LOG_USER_DISABLE;
  662. if ($active == 1) {
  663. $ev = LOG_USER_ENABLE;
  664. }
  665. if ($r !== false) {
  666. event_system($ev,LOG_USER_ID,$user_id);
  667. }
  668. return $r;
  669. }
  670. /**
  671. * Disables a user
  672. * @param int User id
  673. * @uses UserManager::change_active_state() to actually disable the user
  674. * @assert (0) === false
  675. */
  676. public static function disable($user_id)
  677. {
  678. if (empty($user_id)) {
  679. return false;
  680. }
  681. self::change_active_state($user_id, 0);
  682. }
  683. /**
  684. * Enable a user
  685. * @param int User id
  686. * @uses UserManager::change_active_state() to actually disable the user
  687. * @assert (0) === false
  688. */
  689. public static function enable($user_id)
  690. {
  691. if (empty($user_id)) {
  692. return false;
  693. }
  694. self::change_active_state($user_id, 1);
  695. }
  696. /**
  697. * Returns the user's id based on the original id and field name in
  698. * the extra fields. Returns 0 if no user was found. This function is
  699. * mostly useful in the context of a web services-based sinchronization
  700. * @param string Original user id
  701. * @param string Original field name
  702. * @return int User id
  703. * @assert ('0','---') === 0
  704. */
  705. public static function get_user_id_from_original_id($original_user_id_value, $original_user_id_name)
  706. {
  707. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  708. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  709. $sql = "SELECT user_id
  710. FROM $t_uf uf
  711. INNER JOIN $t_ufv ufv
  712. ON ufv.field_id=uf.id
  713. WHERE
  714. field_variable='$original_user_id_name' AND
  715. field_value='$original_user_id_value';";
  716. $res = Database::query($sql);
  717. $row = Database::fetch_object($res);
  718. if ($row) {
  719. return $row->user_id;
  720. } else {
  721. return 0;
  722. }
  723. }
  724. /**
  725. * Check if a username is available
  726. * @param string the wanted username
  727. * @return boolean true if the wanted username is available
  728. * @assert ('') === false
  729. * @assert ('xyzxyzxyz') === true
  730. */
  731. public static function is_username_available($username)
  732. {
  733. if (empty($username)) {
  734. return false;
  735. }
  736. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  737. $sql = "SELECT username FROM $table_user
  738. WHERE username = '".Database::escape_string($username)."'";
  739. $res = Database::query($sql);
  740. return Database::num_rows($res) == 0;
  741. }
  742. /**
  743. * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
  744. * @param string $firstname The first name of the user.
  745. * @param string $lastname The last name of the user.
  746. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  747. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  748. * @return string Suggests a username that contains only ASCII-letters and digits, without check for uniqueness within the system.
  749. * @author Julio Montoya Armas
  750. * @author Ivan Tcholakov, 2009 - rework about internationalization.
  751. * @assert ('','') === false
  752. * @assert ('a','b') === 'ab'
  753. */
  754. public static function create_username($firstname, $lastname, $language = null, $encoding = null)
  755. {
  756. if (is_null($encoding)) {
  757. $encoding = api_get_system_encoding();
  758. }
  759. if (is_null($language)) {
  760. $language = api_get_interface_language();
  761. }
  762. if (empty($firstname) && empty($lastname)) {
  763. return false;
  764. }
  765. $firstname = api_substr(preg_replace(USERNAME_PURIFIER, '', api_transliterate($firstname, '', $encoding)), 0, 1); // The first letter only.
  766. //Looking for a space in the lastname
  767. $pos = api_strpos($lastname, ' ');
  768. if ($pos !== false) {
  769. $lastname = api_substr($lastname, 0, $pos);
  770. }
  771. $lastname = preg_replace(USERNAME_PURIFIER, '', api_transliterate($lastname, '', $encoding));
  772. //$username = api_is_western_name_order(null, $language) ? $firstname.$lastname : $lastname.$firstname;
  773. $username = $firstname.$lastname;
  774. if (empty($username)) {
  775. $username = 'user';
  776. }
  777. return strtolower(substr($username, 0, USERNAME_MAX_LENGTH - 3));
  778. }
  779. /**
  780. * Creates a unique username, using:
  781. * 1. the first name and the last name of a user;
  782. * 2. an already created username but not checked for uniqueness yet.
  783. * @param string $firstname The first name of a given user. If the second parameter $lastname is NULL, then this
  784. * parameter is treated as username which is to be checked for uniqueness and to be modified when it is necessary.
  785. * @param string $lastname The last name of the user.
  786. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  787. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  788. * @return string Returns a username that contains only ASCII-letters and digits, and that is unique within the system.
  789. * Note: When the method is called several times with same parameters, its results look like the following sequence: ivan, ivan2, ivan3, ivan4, ...
  790. * @author Ivan Tcholakov, 2009
  791. */
  792. public static function create_unique_username($firstname, $lastname = null, $language = null, $encoding = null)
  793. {
  794. if (is_null($lastname)) {
  795. // In this case the actual input parameter $firstname should contain ASCII-letters and digits only.
  796. // For making this method tolerant of mistakes, let us transliterate and purify the suggested input username anyway.
  797. // So, instead of the sentence $username = $firstname; we place the following:
  798. $username = strtolower(preg_replace(USERNAME_PURIFIER, '', api_transliterate($firstname, '', $encoding)));
  799. } else {
  800. $username = self::create_username($firstname, $lastname, $language, $encoding);
  801. }
  802. if (!self::is_username_available($username)) {
  803. $i = 2;
  804. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string) $i)).$i;
  805. while (!self::is_username_available($temp_username)) {
  806. $i++;
  807. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string) $i)).$i;
  808. }
  809. $username = $temp_username;
  810. }
  811. return $username;
  812. }
  813. /**
  814. * Modifies a given username accordingly to the specification for valid characters and length.
  815. * @param $username string The input username.
  816. * @param bool $strict (optional) When this flag is TRUE, the result is guaranteed for full compliance, otherwise compliance may be partial. The default value is FALSE.
  817. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  818. * @return string The resulting purified username.
  819. */
  820. public static function purify_username($username, $strict = false, $encoding = null)
  821. {
  822. if ($strict) {
  823. // 1. Conversion of unacceptable letters (latinian letters with accents for example) into ASCII letters in order they not to be totally removed.
  824. // 2. Applying the strict purifier.
  825. // 3. Length limitation.
  826. $toreturn = api_get_setting('login_is_email') == 'true' ? substr(preg_replace(USERNAME_PURIFIER_MAIL, '', api_transliterate($username, '', $encoding)), 0, USERNAME_MAX_LENGTH) : substr(preg_replace(USERNAME_PURIFIER, '', api_transliterate($username, '', $encoding)), 0, USERNAME_MAX_LENGTH);
  827. return $toreturn;
  828. }
  829. // 1. Applying the shallow purifier.
  830. // 2. Length limitation.
  831. return substr(preg_replace(USERNAME_PURIFIER_SHALLOW, '', $username), 0, USERNAME_MAX_LENGTH);
  832. }
  833. /**
  834. * Checks whether the user id exists in the database
  835. *
  836. * @param int User id
  837. * @return bool True if user id was found, false otherwise
  838. */
  839. public static function is_user_id_valid($user_id)
  840. {
  841. $user_id = (int) $user_id;
  842. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  843. $sql = "SELECT user_id FROM $table_user WHERE user_id = '".$user_id."'";
  844. $res = Database::query($sql);
  845. $num_rows = Database::num_rows($res);
  846. if ($num_rows == 0) {
  847. return false;
  848. } else {
  849. return true;
  850. }
  851. }
  852. /**
  853. * Checks whether a given username matches to the specification strictly. The empty username is assumed here as invalid.
  854. * Mostly this function is to be used in the user interface built-in validation routines for providing feedback while usernames are enterd manually.
  855. * @param string $username The input username.
  856. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  857. * @return bool Returns TRUE if the username is valid, FALSE otherwise.
  858. */
  859. public static function is_username_valid($username, $encoding = null)
  860. {
  861. return !empty($username) && $username == self::purify_username($username, true);
  862. }
  863. /**
  864. * Checks whether a username is empty. If the username contains whitespace characters, such as spaces, tabulators, newlines, etc.,
  865. * it is assumed as empty too. This function is safe for validation unpurified data (during importing).
  866. * @param string $username The given username.
  867. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  868. */
  869. public static function is_username_empty($username)
  870. {
  871. return (strlen(self::purify_username($username, false)) == 0);
  872. }
  873. /**
  874. * Checks whether a username is too long or not.
  875. * @param string $username The given username, it should contain only ASCII-letters and digits.
  876. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  877. */
  878. public static function is_username_too_long($username)
  879. {
  880. return (strlen($username) > USERNAME_MAX_LENGTH);
  881. }
  882. /**
  883. * Get the users by ID
  884. * @param array $ids student ids
  885. * @param string $active
  886. * @param string $order
  887. * @param string $limit
  888. * @return array $result student information
  889. */
  890. public static function get_user_list_by_ids($ids = array(), $active = null, $order = null, $limit = null)
  891. {
  892. if (empty($ids)) {
  893. return array();
  894. }
  895. $ids = is_array($ids) ? $ids : array($ids);
  896. $ids = array_map('intval', $ids);
  897. $ids = implode(',', $ids);
  898. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  899. $sql = "SELECT * FROM $tbl_user WHERE user_id IN ($ids)";
  900. if (!is_null($active)) {
  901. $sql .= ' AND active='.($active ? '1' : '0');
  902. }
  903. if (!is_null($order)) {
  904. $order = Database::escape_string($order);
  905. $sql .= ' ORDER BY ' . $order;
  906. }
  907. if (!is_null($limit)) {
  908. $limit = Database::escape_string($limit);
  909. $sql .= ' LIMIT ' . $limit;
  910. }
  911. $rs = Database::query($sql);
  912. $result = array();
  913. while ($row = Database::fetch_array($rs)) {
  914. $result[] = $row;
  915. }
  916. return $result;
  917. }
  918. /**
  919. * Get a list of users of which the given conditions match with an = 'cond'
  920. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  921. * @param array $order_by a list of fields on which sort
  922. * @return array An array with all users of the platform.
  923. * @todo optional course code parameter, optional sorting parameters...
  924. * @todo security filter order by
  925. */
  926. public static function get_user_list($conditions = array(), $order_by = array(), $limit_from = false, $limit_to = false)
  927. {
  928. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  929. $return_array = array();
  930. $sql_query = "SELECT * FROM $user_table";
  931. if (count($conditions) > 0) {
  932. $sql_query .= ' WHERE ';
  933. foreach ($conditions as $field => $value) {
  934. $field = Database::escape_string($field);
  935. $value = Database::escape_string($value);
  936. $sql_query .= "$field = '$value'";
  937. }
  938. }
  939. if (count($order_by) > 0) {
  940. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by), null, false);
  941. }
  942. if (is_numeric($limit_from) && is_numeric($limit_from)) {
  943. $limit_from = intval($limit_from);
  944. $limit_to = intval($limit_to);
  945. $sql_query .= " LIMIT $limit_from, $limit_to";
  946. }
  947. $sql_result = Database::query($sql_query);
  948. while ($result = Database::fetch_array($sql_result)) {
  949. $return_array[] = $result;
  950. }
  951. return $return_array;
  952. }
  953. /**
  954. * Get a list of users of which the given conditions match with a LIKE '%cond%'
  955. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  956. * @param array $order_by a list of fields on which sort
  957. * @return array An array with all users of the platform.
  958. * @todo optional course code parameter, optional sorting parameters...
  959. * @todo security filter order_by
  960. */
  961. public static function get_user_list_like($conditions = array(), $order_by = array(), $simple_like = false, $condition = 'AND')
  962. {
  963. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  964. $return_array = array();
  965. $sql_query = "SELECT * FROM $user_table";
  966. if (count($conditions) > 0) {
  967. $sql_query .= ' WHERE ';
  968. $temp_conditions = array();
  969. foreach ($conditions as $field => $value) {
  970. $field = Database::escape_string($field);
  971. $value = Database::escape_string($value);
  972. if ($simple_like) {
  973. $temp_conditions[] = $field." LIKE '$value%'";
  974. } else {
  975. $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
  976. }
  977. }
  978. if (!empty($temp_conditions)) {
  979. $sql_query .= implode(' '.$condition.' ', $temp_conditions);
  980. }
  981. }
  982. if (count($order_by) > 0) {
  983. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by), null, false);
  984. }
  985. $sql_result = Database::query($sql_query);
  986. while ($result = Database::fetch_array($sql_result)) {
  987. $return_array[] = $result;
  988. }
  989. return $return_array;
  990. }
  991. /**
  992. * Get user information
  993. * @param string The username
  994. * @return array All user information as an associative array
  995. */
  996. public static function get_user_info($username)
  997. {
  998. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  999. $username = Database::escape_string($username);
  1000. $sql = "SELECT * FROM $user_table WHERE username='".$username."'";
  1001. $res = Database::query($sql);
  1002. if (Database::num_rows($res) > 0) {
  1003. return Database::fetch_array($res);
  1004. }
  1005. return false;
  1006. }
  1007. /**
  1008. * Get user information
  1009. * @param string The id
  1010. * @param boolean Whether to return the user's extra fields (defaults to false)
  1011. * @return array All user information as an associative array
  1012. * @todo Use api_get_user_info() instead
  1013. */
  1014. public static function get_user_info_by_id($user_id, $user_fields = false)
  1015. {
  1016. $user_id = intval($user_id);
  1017. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  1018. $sql = "SELECT * FROM $user_table WHERE user_id=".$user_id;
  1019. $res = Database::query($sql);
  1020. if (Database::num_rows($res) > 0) {
  1021. $user = Database::fetch_array($res);
  1022. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1023. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1024. $sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
  1025. $resf = Database::query($sqlf);
  1026. if (Database::num_rows($resf) > 0) {
  1027. while ($rowf = Database::fetch_array($resf)) {
  1028. $sqlv = "SELECT * FROM $t_ufv WHERE field_id = ".$rowf['id']." AND user_id = ".$user['user_id']." ORDER BY id DESC";
  1029. $resv = Database::query($sqlv);
  1030. if (Database::num_rows($resv) > 0) {
  1031. //There should be only one value for a field and a user
  1032. $rowv = Database::fetch_array($resv);
  1033. $user['extra'][$rowf['field_variable']] = $rowv['field_value'];
  1034. } else {
  1035. $user['extra'][$rowf['field_variable']] = '';
  1036. }
  1037. }
  1038. }
  1039. return $user;
  1040. }
  1041. return false;
  1042. }
  1043. /**
  1044. * Get the teacher list
  1045. * @param int the course ID
  1046. * @param array Content the list ID of user_id selected
  1047. */
  1048. //for survey
  1049. // TODO: Ivan, 14-SEP-2009: It seems that this method is not used at all (it can be located in a test unit only. To be deprecated?
  1050. public static function get_teacher_list($course_id, $sel_teacher = '')
  1051. {
  1052. $user_course_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1053. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  1054. $course_id = Database::escape_string($course_id);
  1055. $sql = "SELECT * FROM $user_table a, $user_course_table b
  1056. WHERE a.user_id=b.user_id AND b.status=1 AND b.course_code='$course_id'";
  1057. $sql_result = Database::query($sql);
  1058. echo "<select name=\"author\">";
  1059. while ($result = Database::fetch_array($sql_result)) {
  1060. if ($sel_teacher == $result['user_id'])
  1061. $selected = "selected";
  1062. echo "\n<option value=\"".$result['user_id']."\" $selected>".$result['firstname']."</option>";
  1063. }
  1064. echo "</select>";
  1065. }
  1066. /**
  1067. * Get user picture URL or path from user ID (returns an array).
  1068. * The return format is a complete path, enabling recovery of the directory
  1069. * with dirname() or the file with basename(). This also works for the
  1070. * functions dealing with the user's productions, as they are located in
  1071. * the same directory.
  1072. * @param integer User ID
  1073. * @param string Type of path to return (can be 'none', 'system', 'rel', 'web')
  1074. * @param bool deprecated see #7110
  1075. * @param bool If we want that the function returns the /main/img/unknown.jpg image set it at true
  1076. * @return array Array of 2 elements: 'dir' and 'file' which contain the dir and file as the name implies if image does not exist it will return the unknow image if anonymous parameter is true if not it returns an empty er's
  1077. */
  1078. public static function get_user_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false)
  1079. {
  1080. switch ($type) {
  1081. case 'system': // Base: absolute system path.
  1082. $base = api_get_path(SYS_CODE_PATH);
  1083. break;
  1084. case 'rel': // Base: semi-absolute web path (no server base).
  1085. $base = api_get_path(REL_CODE_PATH);
  1086. break;
  1087. case 'web': // Base: absolute web path.
  1088. $base = api_get_path(WEB_CODE_PATH);
  1089. break;
  1090. case 'none':
  1091. default: // Base: empty, the result path below will be relative.
  1092. $base = '';
  1093. }
  1094. if (empty($id) || empty($type)) {
  1095. return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
  1096. }
  1097. $user_id = intval($id);
  1098. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  1099. $sql = "SELECT picture_uri FROM $user_table WHERE user_id=".$user_id;
  1100. $res = Database::query($sql);
  1101. if (!Database::num_rows($res)) {
  1102. return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
  1103. }
  1104. $user = Database::fetch_array($res);
  1105. $picture_filename = trim($user['picture_uri']);
  1106. if (api_get_setting('split_users_upload_directory') === 'true') {
  1107. /*if (!empty($picture_filename) or $preview) {
  1108. $dir = $base.'upload/users/'.substr((string) $user_id, 0, 1).'/'.$user_id.'/';
  1109. } else {
  1110. $dir = $base.'upload/users/'.$user_id.'/';
  1111. }*/
  1112. $dir = $base.'upload/users/'.substr((string) $user_id, 0, 1).'/'.$user_id.'/';
  1113. } else {
  1114. $dir = $base.'upload/users/'.$user_id.'/';
  1115. }
  1116. if (empty($picture_filename) && $anonymous) {
  1117. return array('dir' => $base.'img/', 'file' => 'unknown.jpg');
  1118. }
  1119. return array('dir' => $dir, 'file' => $picture_filename);
  1120. }
  1121. /**
  1122. * Creates new user photos in various sizes of a user, or deletes user photos.
  1123. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
  1124. * @param int $user_id The user internal identitfication number.
  1125. * @param string $file The common file name for the newly created photos.
  1126. * It will be checked and modified for compatibility with the file system.
  1127. * If full name is provided, path component is ignored.
  1128. * If an empty name is provided, then old user photos are deleted only,
  1129. * @see UserManager::delete_user_picture() as the prefered way for deletion.
  1130. * @param string $source_file The full system name of the image from which user photos will be created.
  1131. * @return string/bool Returns the resulting common file name of created images which usually should be stored in database.
  1132. * When deletion is recuested returns empty string. In case of internal error or negative validation returns FALSE.
  1133. */
  1134. public static function update_user_picture($user_id, $file = null, $source_file = null)
  1135. {
  1136. if (empty($user_id)) {
  1137. return false;
  1138. }
  1139. $delete = empty($file);
  1140. if (empty($source_file)) {
  1141. $source_file = $file;
  1142. }
  1143. // Configuration options about user photos.
  1144. require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
  1145. // User-reserved directory where photos have to be placed.
  1146. $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
  1147. $path = $path_info['dir'];
  1148. // If this directory does not exist - we create it.
  1149. if (!file_exists($path)) {
  1150. @mkdir($path, api_get_permissions_for_new_directories(), true);
  1151. }
  1152. // The old photos (if any).
  1153. $old_file = $path_info['file'];
  1154. // Let us delete them.
  1155. if (!empty($old_file)) {
  1156. if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
  1157. $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
  1158. @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
  1159. @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
  1160. @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
  1161. @rename($path.$old_file, $path.$prefix.$old_file);
  1162. } else {
  1163. @unlink($path.'small_'.$old_file);
  1164. @unlink($path.'medium_'.$old_file);
  1165. @unlink($path.'big_'.$old_file);
  1166. @unlink($path.$old_file);
  1167. }
  1168. }
  1169. // Exit if only deletion has been requested. Return an empty picture name.
  1170. if ($delete) {
  1171. return '';
  1172. }
  1173. // Validation 2.
  1174. $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
  1175. $file = str_replace('\\', '/', $file);
  1176. $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
  1177. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  1178. if (!in_array($extension, $allowed_types)) {
  1179. return false;
  1180. }
  1181. // This is the common name for the new photos.
  1182. if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
  1183. $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
  1184. $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
  1185. $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
  1186. } else {
  1187. $filename = replace_dangerous_char($filename);
  1188. if (PREFIX_IMAGE_FILENAME_WITH_UID) {
  1189. $filename = uniqid('').'_'.$filename;
  1190. }
  1191. // We always prefix user photos with user ids, so on setting
  1192. // api_get_setting('split_users_upload_directory') === 'true'
  1193. // the correspondent directories to be found successfully.
  1194. $filename = $user_id.'_'.$filename;
  1195. }
  1196. // Storing the new photos in 4 versions with various sizes.
  1197. $small = self::resize_picture($source_file, 22);
  1198. $medium = self::resize_picture($source_file, 85);
  1199. $normal = self::resize_picture($source_file, 200);
  1200. $big = new Image($source_file); // This is the original picture.
  1201. $ok = $small && $small->send_image($path.'small_'.$filename) &&
  1202. $medium && $medium->send_image($path.'medium_'.$filename) &&
  1203. $normal && $normal->send_image($path.$filename) &&
  1204. $big && $big->send_image($path.'big_'.$filename);
  1205. return $ok ? $filename : false;
  1206. }
  1207. /**
  1208. * Update User extra field file type into {user_folder}/{$extra_field}
  1209. * @param int $user_id The user internal identification number
  1210. * @param string $extra_field The $extra_field The extra field name
  1211. * @param null $file The filename
  1212. * @param null $source_file The temporal filename
  1213. * @return bool|null return filename if success, but false
  1214. */
  1215. public static function update_user_extra_file($user_id, $extra_field = '', $file = null, $source_file = null)
  1216. {
  1217. // Add Filter
  1218. $source_file = Security::filter_filename($source_file);
  1219. $file = Security::filter_filename($file);
  1220. if (empty($user_id)) {
  1221. return false;
  1222. }
  1223. if (empty($source_file)) {
  1224. $source_file = $file;
  1225. }
  1226. // User-reserved directory where extra file have to be placed.
  1227. $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
  1228. $path = $path_info['dir'];
  1229. if (!empty($extra_field)) {
  1230. $path .= $extra_field . '/';
  1231. }
  1232. // If this directory does not exist - we create it.
  1233. if (!file_exists($path)) {
  1234. @mkdir($path, api_get_permissions_for_new_directories(), true);
  1235. }
  1236. if (filter_extension($file)) {
  1237. if (@move_uploaded_file($source_file,$path.$file)) {
  1238. if ($extra_field) {
  1239. return $extra_field.'/'.$file;
  1240. } else {
  1241. return $file;
  1242. }
  1243. }
  1244. }
  1245. return false; // this should be returned if anything went wrong with the upload
  1246. }
  1247. /**
  1248. * Deletes user photos.
  1249. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
  1250. * @param int $user_id The user internal identitfication number.
  1251. * @return string/bool Returns empty string on success, FALSE on error.
  1252. */
  1253. public static function delete_user_picture($user_id)
  1254. {
  1255. return self::update_user_picture($user_id);
  1256. }
  1257. /**
  1258. * Returns an XHTML formatted list of productions for a user, or FALSE if he
  1259. * doesn't have any.
  1260. *
  1261. * If there has been a request to remove a production, the function will return
  1262. * without building the list unless forced to do so by the optional second
  1263. * parameter. This increases performance by avoiding to read through the
  1264. * productions on the filesystem before the removal request has been carried
  1265. * out because they'll have to be re-read afterwards anyway.
  1266. *
  1267. * @param $user_id User id
  1268. * @param $force Optional parameter to force building after a removal request
  1269. * @return A string containing the XHTML code to dipslay the production list, or FALSE
  1270. */
  1271. public static function build_production_list($user_id, $force = false, $showdelete = false)
  1272. {
  1273. if (!$force && !empty($_POST['remove_production'])) {
  1274. return true; // postpone reading from the filesystem
  1275. }
  1276. $productions = self::get_user_productions($user_id);
  1277. if (empty($productions)) {
  1278. return false;
  1279. }
  1280. $production_path = self::get_user_picture_path_by_id($user_id, 'web');
  1281. $production_dir = $production_path['dir'];
  1282. $del_image = api_get_path(WEB_CODE_PATH).'img/delete.png';
  1283. $add_image = api_get_path(WEB_CODE_PATH).'img/archive.png';
  1284. $del_text = get_lang('Delete');
  1285. $production_list = '';
  1286. if (count($productions) > 0) {
  1287. $production_list = '<div class="files-production"> <ul id="productions">';
  1288. foreach ($productions as $file) {
  1289. $production_list .= '<li><img src="'.$add_image.'" /><a href="'.$production_dir.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  1290. if ($showdelete) {
  1291. $production_list .= '&nbsp;&nbsp;<input style="width:16px;" type="image" name="remove_production['.urlencode($file).']" src="'.$del_image.'" alt="'.$del_text.'" title="'.$del_text.' '.htmlentities($file).'" onclick="javascript: return confirmation(\''.htmlentities($file).'\');" /></li>';
  1292. }
  1293. }
  1294. $production_list .= '</ul></div>';
  1295. }
  1296. return $production_list;
  1297. }
  1298. /**
  1299. * Returns an array with the user's productions.
  1300. *
  1301. * @param $user_id User id
  1302. * @return An array containing the user's productions
  1303. */
  1304. public static function get_user_productions($user_id)
  1305. {
  1306. $production_path = self::get_user_picture_path_by_id($user_id, 'system');
  1307. $production_repository = $production_path['dir'];
  1308. $productions = array();
  1309. if (is_dir($production_repository)) {
  1310. $handle = opendir($production_repository);
  1311. while ($file = readdir($handle)) {
  1312. if ($file == '.' ||
  1313. $file == '..' ||
  1314. $file == '.htaccess' ||
  1315. is_dir($production_repository.$file)
  1316. ) {
  1317. // skip current/parent directory and .htaccess
  1318. continue;
  1319. }
  1320. if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) {
  1321. // User's photos should not be listed as productions.
  1322. continue;
  1323. }
  1324. $productions[] = $file;
  1325. }
  1326. }
  1327. return $productions;
  1328. }
  1329. /**
  1330. * Remove a user production.
  1331. *
  1332. * @param $user_id User id
  1333. * @param $production The production to remove
  1334. */
  1335. public static function remove_user_production($user_id, $production)
  1336. {
  1337. $production_path = self::get_user_picture_path_by_id($user_id, 'system');
  1338. $production_file = $production_path['dir'].$production;
  1339. if (is_file($production_file)) {
  1340. unlink($production_file);
  1341. return true;
  1342. }
  1343. return false;
  1344. }
  1345. /**
  1346. * Update an extra field. This function is called when a user changes his/her profile
  1347. * and by consequence fills or edits his/her extra fields.
  1348. *
  1349. * @param integer Field ID
  1350. * @param array Database columns and their new value
  1351. * @return boolean true if field updated, false otherwise
  1352. */
  1353. public static function update_extra_field($fid, $columns)
  1354. {
  1355. //TODO check that values added are values proposed for enumerated field types
  1356. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1357. $fid = Database::escape_string($fid);
  1358. $sqluf = "UPDATE $t_uf SET ";
  1359. $known_fields = array(
  1360. 'id',
  1361. 'field_variable',
  1362. 'field_type',
  1363. 'field_display_text',
  1364. 'field_default_value',
  1365. 'field_order',
  1366. 'field_visible',
  1367. 'field_changeable',
  1368. 'field_filter'
  1369. );
  1370. $safecolumns = array();
  1371. foreach ($columns as $index => $newval) {
  1372. if (in_array($index, $known_fields)) {
  1373. $safecolumns[$index] = Database::escape_string($newval);
  1374. $sqluf .= $index." = '".$safecolumns[$index]."', ";
  1375. }
  1376. }
  1377. $time = time();
  1378. $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'";
  1379. $resuf = Database::query($sqluf);
  1380. return $resuf;
  1381. }
  1382. /**
  1383. * Update an extra field value for a given user
  1384. * @param integer $user_id User ID
  1385. * @param string $fname Field variable name
  1386. * @param string $fvalue Field value
  1387. *
  1388. * @return boolean true if field updated, false otherwise
  1389. */
  1390. public static function update_extra_field_value($user_id, $fname, $fvalue = '')
  1391. {
  1392. //TODO check that values added are values proposed for enumerated field types
  1393. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1394. $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1395. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1396. $fname = Database::escape_string($fname);
  1397. if ($user_id != strval(intval($user_id))) {
  1398. return false;
  1399. }
  1400. if ($user_id === false) {
  1401. return false;
  1402. }
  1403. $fvalues = '';
  1404. if (is_array($fvalue)) {
  1405. foreach ($fvalue as $val) {
  1406. $fvalues .= $val.';';
  1407. }
  1408. if (!empty($fvalues)) {
  1409. $fvalues = substr($fvalues, 0, -1);
  1410. }
  1411. } else {
  1412. $fvalues = $fvalue;
  1413. }
  1414. $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
  1415. $resuf = Database::query($sqluf);
  1416. $is_extra_file = false;
  1417. if (Database::num_rows($resuf) == 1) {
  1418. //ok, the field exists
  1419. // Check if enumerated field, if the option is available
  1420. $rowuf = Database::fetch_array($resuf);
  1421. switch ($rowuf['field_type']) {
  1422. case self::USER_FIELD_TYPE_TAG :
  1423. //4. Tags are process here comes from main/auth/profile.php
  1424. UserManager::process_tags(explode(';', $fvalues), $user_id, $rowuf['id']);
  1425. return true;
  1426. break;
  1427. /*case self::USER_FIELD_TYPE_SELECT_MULTIPLE :
  1428. // check code from UserManager::update_user_picture() to use something similar here
  1429. break;*/
  1430. case self::USER_FIELD_TYPE_RADIO:
  1431. case self::USER_FIELD_TYPE_SELECT:
  1432. case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
  1433. $sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
  1434. $resuo = Database::query($sqluo);
  1435. $values = explode(';', $fvalues);
  1436. if (Database::num_rows($resuo) > 0) {
  1437. $check = false;
  1438. while ($rowuo = Database::fetch_array($resuo)) {
  1439. if (in_array($rowuo['option_value'], $values)) {
  1440. $check = true;
  1441. break;
  1442. }
  1443. }
  1444. if (!$check) {
  1445. return false; //option value not found
  1446. }
  1447. } else {
  1448. return false; //enumerated type but no option found
  1449. }
  1450. break;
  1451. case self::USER_FIELD_TYPE_FILE:
  1452. $is_extra_file = true;
  1453. if (isset($fvalue['tmp_name'])) {
  1454. // Filter against dangerous filenames
  1455. $fvalue['name'] = Security::filter_filename($fvalue['name']);
  1456. $fvalue['tmp_name'] = Security::filter_filename($fvalue['tmp_name']);
  1457. // Update and recover the filename
  1458. $fvalues = UserManager::update_user_extra_file(
  1459. $user_id,
  1460. $rowuf['field_variable'],
  1461. $fvalue['name'],
  1462. $fvalue['tmp_name']
  1463. );
  1464. } else {
  1465. // Set empty string to $fvalues to delete it
  1466. $fvalues = '';
  1467. }
  1468. break;
  1469. case 1:
  1470. case 2:
  1471. default:
  1472. break;
  1473. }
  1474. $tms = time();
  1475. $sqlufv = "SELECT * FROM $t_ufv
  1476. WHERE user_id = $user_id AND field_id = ".$rowuf['id']."
  1477. ORDER BY id";
  1478. $resufv = Database::query($sqlufv);
  1479. $n = Database::num_rows($resufv);
  1480. if ($n > 1) {
  1481. //problem, we already have two values for this field and user combination - keep last one
  1482. while ($rowufv = Database::fetch_array($resufv)) {
  1483. if ($n > 1) {
  1484. $sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
  1485. Database::query($sqld);
  1486. $n--;
  1487. }
  1488. $rowufv = Database::fetch_array($resufv);
  1489. if ($rowufv['field_value'] != $fvalues) {
  1490. $sqlu = "UPDATE $t_ufv SET
  1491. field_value = '".Database::escape_string($fvalues)."',
  1492. tms = FROM_UNIXTIME($tms)
  1493. WHERE id = ".$rowufv['id'];
  1494. $resu = Database::query($sqlu);
  1495. return ($resu ? true : false);
  1496. }
  1497. return true;
  1498. }
  1499. } elseif ($n == 1) {
  1500. //we need to update the current record
  1501. $rowufv = Database::fetch_array($resufv);
  1502. if ($rowufv['field_value'] != $fvalues) {
  1503. if ($is_extra_file) {
  1504. // To remove from user folder
  1505. self::remove_user_extra_file(
  1506. $user_id,
  1507. $fname,
  1508. $rowufv['field_value']
  1509. );
  1510. }
  1511. // If the new field is empty, delete it
  1512. if ($fvalues == '') {
  1513. $sql_query = "DELETE FROM $t_ufv
  1514. WHERE id = ".$rowufv['id'].";";
  1515. } else {
  1516. // Otherwise update it
  1517. $sql_query = "UPDATE $t_ufv SET
  1518. field_value = '".Database::escape_string($fvalues)."',
  1519. tms = FROM_UNIXTIME($tms)
  1520. WHERE id = ".$rowufv['id'];
  1521. }
  1522. $resu = Database::query($sql_query);
  1523. return ($resu ? true : false);
  1524. }
  1525. return true;
  1526. } else {
  1527. $sql = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms)
  1528. VALUES ( $user_id, ".$rowuf['id'].", '".Database::escape_string($fvalues)."', FROM_UNIXTIME($tms))";
  1529. $res = Database::query($sql);
  1530. return $res ? true : false;
  1531. }
  1532. } else {
  1533. // Field not found
  1534. return false;
  1535. }
  1536. }
  1537. /**
  1538. * Get an array of extra fields with field details (type, default value and options)
  1539. * @param integer Offset (from which row)
  1540. * @param integer Number of items
  1541. * @param integer Column on which sorting is made
  1542. * @param string Sorting direction
  1543. * @param boolean Optional. Whether we get all the fields or just the visible ones
  1544. * @param int Optional. Whether we get all the fields with field_filter 1 or 0 or everything
  1545. * @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
  1546. */
  1547. public static function get_extra_fields(
  1548. $from = 0,
  1549. $number_of_items = 0,
  1550. $column = 5,
  1551. $direction = 'ASC',
  1552. $all_visibility = true,
  1553. $field_filter = null
  1554. ) {
  1555. $fields = array();
  1556. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1557. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1558. $columns = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_filter', 'tms');
  1559. $column = intval($column);
  1560. $sort_direction = '';
  1561. if (in_array(strtoupper($direction), array('ASC', 'DESC'))) {
  1562. $sort_direction = strtoupper($direction);
  1563. }
  1564. $sqlf = "SELECT * FROM $t_uf WHERE 1 = 1 ";
  1565. if (!$all_visibility) {
  1566. $sqlf .= " AND field_visible = 1 ";
  1567. }
  1568. if (!is_null($field_filter)) {
  1569. $field_filter = intval($field_filter);
  1570. $sqlf .= " AND field_filter = $field_filter ";
  1571. }
  1572. $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction ";
  1573. if ($number_of_items != 0) {
  1574. $sqlf .= " LIMIT ".intval($from).','.intval($number_of_items);
  1575. }
  1576. $resf = Database::query($sqlf);
  1577. if (Database::num_rows($resf) > 0) {
  1578. while ($rowf = Database::fetch_array($resf)) {
  1579. $fields[$rowf['id']] = array(
  1580. 0 => $rowf['id'],
  1581. 1 => $rowf['field_variable'],
  1582. 2 => $rowf['field_type'],
  1583. //3 => (empty($rowf['field_display_text']) ? '' : get_lang($rowf['field_display_text'], '')),
  1584. // Temporarily removed auto-translation. Need update to get_lang() to know if translation exists (todo)
  1585. // Ivan, 15-SEP-2009: get_lang() has been modified accordingly in order this issue to be solved.
  1586. 3 => (empty($rowf['field_display_text']) ? '' : $rowf['field_display_text']),
  1587. 4 => $rowf['field_default_value'],
  1588. 5 => $rowf['field_order'],
  1589. 6 => $rowf['field_visible'],
  1590. 7 => $rowf['field_changeable'],
  1591. 8 => $rowf['field_filter'],
  1592. 9 => array(),
  1593. 10 => '<a name="'.$rowf['id'].'"></a>',
  1594. );
  1595. $sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id']." ORDER BY option_order ASC";
  1596. $reso = Database::query($sqlo);
  1597. if (Database::num_rows($reso) > 0) {
  1598. while ($rowo = Database::fetch_array($reso)) {
  1599. $fields[$rowf['id']][9][$rowo['id']] = array(
  1600. 0 => $rowo['id'],
  1601. 1 => $rowo['option_value'],
  1602. //2 => (empty($rowo['option_display_text']) ? '' : get_lang($rowo['option_display_text'], '')),
  1603. 2 => (empty($rowo['option_display_text']) ? '' : $rowo['option_display_text']),
  1604. 3 => $rowo['option_order']
  1605. );
  1606. }
  1607. }
  1608. }
  1609. }
  1610. return $fields;
  1611. }
  1612. /**
  1613. * Build a list of extra file already uploaded in $user_folder/{$extra_field}/
  1614. * @param $user_id
  1615. * @param $extra_field
  1616. * @param bool $force
  1617. * @param bool $showdelete
  1618. * @return bool|string
  1619. */
  1620. public static function build_user_extra_file_list($user_id, $extra_field, $force = false, $showdelete = false)
  1621. {
  1622. if (!$force && !empty($_POST['remove_'.$extra_field])) {
  1623. return true; // postpone reading from the filesystem
  1624. }
  1625. $extra_files = self::get_user_extra_files($user_id, $extra_field);
  1626. if (empty($extra_files)) {
  1627. return false;
  1628. }
  1629. $path_info = self::get_user_picture_path_by_id($user_id, 'web', true);
  1630. $path = $path_info['dir'];
  1631. $del_image = api_get_path(WEB_CODE_PATH).'img/delete.png';
  1632. $del_text = get_lang('Delete');
  1633. $extra_file_list = '';
  1634. if (count($extra_files) > 0) {
  1635. $extra_file_list = '<div class="files-production"><ul id="productions">';
  1636. foreach ($extra_files as $file) {
  1637. $filename = substr($file,strlen($extra_field)+1);
  1638. $extra_file_list .= '<li>'.Display::return_icon('archive.png').'<a href="'.$path.$extra_field.'/'.urlencode($filename).'" target="_blank">'.htmlentities($filename).'</a> ';
  1639. if ($showdelete) {
  1640. $extra_file_list .= '<input style="width:16px;" type="image" name="remove_extra_' . $extra_field . '['.urlencode($file).']" src="'.$del_image.'" alt="'.$del_text.'" title="'.$del_text.' '.htmlentities($filename).'" onclick="javascript: return confirmation(\''.htmlentities($filename).'\');" /></li>';
  1641. }
  1642. }
  1643. $extra_file_list .= '</ul></div>';
  1644. }
  1645. return $extra_file_list;
  1646. }
  1647. /**
  1648. * Get valid filenames in $user_folder/{$extra_field}/
  1649. * @param $user_id
  1650. * @param $extra_field
  1651. * @param bool $full_path
  1652. * @return array
  1653. */
  1654. public static function get_user_extra_files($user_id, $extra_field, $full_path = false)
  1655. {
  1656. if (!$full_path) {
  1657. // Nothing to do
  1658. } else {
  1659. $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
  1660. $path = $path_info['dir'];
  1661. }
  1662. $extra_data = self::get_extra_user_data_by_field($user_id, $extra_field);
  1663. $extra_files = $extra_data[$extra_field];
  1664. if (is_array($extra_files)) {
  1665. foreach ($extra_files as $key => $value) {
  1666. if (!$full_path) {
  1667. // Relative path from user folder
  1668. $files[] = $value;
  1669. } else {
  1670. $files[] = $path.$value;
  1671. }
  1672. }
  1673. } elseif (!empty($extra_files)) {
  1674. if (!$full_path) {
  1675. // Relative path from user folder
  1676. $files[] = $extra_files;
  1677. } else {
  1678. $files[] = $path.$extra_files;
  1679. }
  1680. }
  1681. return $files; // can be an empty array
  1682. }
  1683. /**
  1684. * Remove an {$extra_file} from the user folder $user_folder/{$extra_field}/
  1685. * @param $user_id
  1686. * @param $extra_field
  1687. * @param $extra_file
  1688. * @return bool
  1689. */
  1690. public static function remove_user_extra_file($user_id, $extra_field, $extra_file)
  1691. {
  1692. $extra_file = Security::filter_filename($extra_file);
  1693. $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
  1694. if (strpos($extra_file, $extra_field) !== false) {
  1695. $path_extra_file = $path_info['dir'].$extra_file;
  1696. } else {
  1697. $path_extra_file = $path_info['dir'].$extra_field.'/'.$extra_file;
  1698. }
  1699. if (is_file($path_extra_file)) {
  1700. unlink($path_extra_file);
  1701. return true;
  1702. }
  1703. return false;
  1704. }
  1705. /**
  1706. * Get the list of options attached to an extra field
  1707. * @param string $fieldname the name of the field
  1708. * @return array the list of options
  1709. */
  1710. public static function get_extra_field_options($field_name)
  1711. {
  1712. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1713. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1714. $sql = 'SELECT options.*
  1715. FROM '.$t_ufo.' options
  1716. INNER JOIN '.$t_uf.' fields
  1717. ON fields.id = options.field_id
  1718. AND fields.field_variable="'.Database::escape_string($field_name).'"';
  1719. $rs = Database::query($sql);
  1720. return Database::store_result($rs);
  1721. }
  1722. /**
  1723. * Get the number of extra fields currently recorded
  1724. * @param boolean Optional switch. true (default) returns all fields, false returns only visible fields
  1725. * @return integer Number of fields
  1726. */
  1727. public static function get_number_of_extra_fields($all_visibility = true)
  1728. {
  1729. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1730. $sqlf = "SELECT * FROM $t_uf ";
  1731. if (!$all_visibility) {
  1732. $sqlf .= " WHERE field_visible = 1 ";
  1733. }
  1734. $sqlf .= " ORDER BY field_order";
  1735. $resf = Database::query($sqlf);
  1736. return Database::num_rows($resf);
  1737. }
  1738. /**
  1739. * Creates a new extra field
  1740. * @param string Field's internal variable name
  1741. * @param int Field's type
  1742. * @param string Field's language var name
  1743. * @param string Field's default value
  1744. * @param string Optional comma-separated list of options to provide for select and radio
  1745. * @return int new user id - if the new user creation succeeds, false otherwise
  1746. */
  1747. public static function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '')
  1748. {
  1749. // database table definition
  1750. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1751. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1752. // First check wether the login already exists
  1753. if (self::is_extra_field_available($fieldvarname)) {
  1754. return api_set_failure('login-pass already taken');
  1755. }
  1756. $sql = "SELECT MAX(field_order) FROM $table_field";
  1757. $res = Database::query($sql);
  1758. $order = 0;
  1759. if (Database::num_rows($res) > 0) {
  1760. $row = Database::fetch_array($res);
  1761. $order = $row[0] + 1;
  1762. }
  1763. $time = time();
  1764. $sql = "INSERT INTO $table_field
  1765. SET field_type = '".Database::escape_string($fieldtype)."',
  1766. field_variable = '".Database::escape_string($fieldvarname)."',
  1767. field_display_text = '".Database::escape_string($fieldtitle)."',
  1768. field_default_value = '".Database::escape_string($fielddefault)."',
  1769. field_order = '$order',
  1770. tms = FROM_UNIXTIME($time)";
  1771. $result = Database::query($sql);
  1772. if ($result) {
  1773. //echo "id returned";
  1774. $return = Database::insert_id();
  1775. event_system(LOG_USER_FIELD_CREATE, LOG_USER_FIELD_VARIABLE, Database::escape_string($fieldvarname));
  1776. } else {
  1777. //echo "false - failed" ;
  1778. return false;
  1779. }
  1780. if (!empty($fieldoptions) && in_array($fieldtype, array(self::USER_FIELD_TYPE_RADIO, self::USER_FIELD_TYPE_SELECT, self::USER_FIELD_TYPE_SELECT_MULTIPLE, self::USER_FIELD_TYPE_DOUBLE_SELECT))) {
  1781. if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
  1782. $twolist = explode('|', $fieldoptions);
  1783. $counter = 0;
  1784. foreach ($twolist as $individual_list) {
  1785. $splitted_individual_list = explode(';', $individual_list);
  1786. foreach ($splitted_individual_list as $individual_list_option) {
  1787. //echo 'counter:'.$counter;
  1788. if ($counter == 0) {
  1789. $list[] = $individual_list_option;
  1790. } else {
  1791. $list[] = str_repeat('*', $counter).$individual_list_option;
  1792. }
  1793. }
  1794. $counter++;
  1795. }
  1796. } else {
  1797. $list = explode(';', $fieldoptions);
  1798. }
  1799. foreach ($list as $option) {
  1800. $option = Database::escape_string($option);
  1801. $sql = "SELECT * FROM $table_field_options WHERE field_id = $return AND option_value = '".$option."'";
  1802. $res = Database::query($sql);
  1803. if (Database::num_rows($res) > 0) {
  1804. //the option already exists, do nothing
  1805. } else {
  1806. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = $return";
  1807. $res = Database::query($sql);
  1808. $max = 1;
  1809. if (Database::num_rows($res) > 0) {
  1810. $row = Database::fetch_array($res);
  1811. $max = $row[0] + 1;
  1812. }
  1813. $time = time();
  1814. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms)
  1815. VALUES ($return,'$option','$option',$max,FROM_UNIXTIME($time))";
  1816. $res = Database::query($sql);
  1817. if ($res === false) {
  1818. $return = false;
  1819. }
  1820. }
  1821. }
  1822. }
  1823. return $return;
  1824. }
  1825. /**
  1826. * Save the changes in the definition of the extra user profile field
  1827. * The function is called after you (as admin) decide to store the changes you have made to one of the fields you defined
  1828. *
  1829. * There is quite some logic in this field
  1830. * 1. store the changes to the field (tupe, name, label, default text)
  1831. * 2. remove the options and the choices of the users from the database that no longer occur in the form field 'possible values'. We should only remove
  1832. * the options (and choices) that do no longer have to appear. We cannot remove all options and choices because if you remove them all
  1833. * and simply re-add them all then all the user who have already filled this form will loose their selected value.
  1834. * 3. we add the options that are newly added
  1835. *
  1836. * <code> current options are a;b;c and the user changes this to a;b;x (removing c and adding x)
  1837. * we first remove c (and also the entry in the option_value table for the users who have chosen this)
  1838. * we then add x
  1839. * a and b are neither removed nor added
  1840. * </code>
  1841. * @param integer $fieldid the id of the field we are editing
  1842. * @param string $fieldvarname the internal variable name of the field
  1843. * @param int $fieldtype the type of the field
  1844. * @param string $fieldtitle the title of the field
  1845. * @param string $fielddefault the default value of the field
  1846. * @param string $fieldoptions Optional comma-separated list of options to provide for select and radio
  1847. * @return boolean true
  1848. *
  1849. *
  1850. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1851. * @version July 2008
  1852. * @since v1.8.6
  1853. */
  1854. public static function save_extra_field_changes($fieldid, $fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '')
  1855. {
  1856. // database table definition
  1857. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1858. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1859. $table_field_options_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1860. // we first update the field definition with the new values
  1861. $time = time();
  1862. $sql = "UPDATE $table_field
  1863. SET field_type = '".Database::escape_string($fieldtype)."',
  1864. field_variable = '".Database::escape_string($fieldvarname)."',
  1865. field_display_text = '".Database::escape_string($fieldtitle)."',
  1866. field_default_value = '".Database::escape_string($fielddefault)."',
  1867. tms = FROM_UNIXTIME($time)
  1868. WHERE id = '".intval($fieldid)."'";
  1869. $result = Database::query($sql);
  1870. // we create an array with all the options (will be used later in the script)
  1871. if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
  1872. $twolist = explode('|', $fieldoptions);
  1873. $counter = 0;
  1874. foreach ($twolist as $individual_list) {
  1875. $splitted_individual_list = explode(';', $individual_list);
  1876. foreach ($splitted_individual_list as $individual_list_option) {
  1877. //echo 'counter:'.$counter;
  1878. if ($counter == 0) {
  1879. $list[] = trim($individual_list_option);
  1880. } else {
  1881. $list[] = str_repeat('*', $counter).trim($individual_list_option);
  1882. }
  1883. }
  1884. $counter++;
  1885. }
  1886. } else {
  1887. $templist = explode(';', $fieldoptions);
  1888. $list = array_map('trim', $templist);
  1889. }
  1890. // Remove all the field options (and also the choices of the user) that are NOT in the new list of options
  1891. $sql = "SELECT * FROM $table_field_options WHERE option_value NOT IN ('".implode("','", $list)."') AND field_id = '".intval($fieldid)."'";
  1892. $result = Database::query($sql);
  1893. $return['deleted_options'] = 0;
  1894. while ($row = Database::fetch_array($result)) {
  1895. // deleting the option
  1896. $sql_delete_option = "DELETE FROM $table_field_options WHERE id='".intval($row['id'])."'";
  1897. Database::query($sql_delete_option);
  1898. $return['deleted_options']++;
  1899. // deleting the answer of the user who has chosen this option
  1900. $sql_delete_option_value = "DELETE FROM $table_field_options_values
  1901. WHERE field_id = '".intval($fieldid)."' AND field_value = '".Database::escape_string($row['option_value'])."'";
  1902. Database::query($sql_delete_option_value);
  1903. $return['deleted_option_values'] = $return['deleted_option_values'] + Database::affected_rows();
  1904. }
  1905. // we now try to find the field options that are newly added
  1906. $sql = "SELECT * FROM $table_field_options WHERE field_id = '".intval($fieldid)."'";
  1907. $result = Database::query($sql);
  1908. while ($row = Database::fetch_array($result)) {
  1909. // we remove every option that is already in the database from the $list
  1910. if (in_array(trim($row['option_display_text']), $list)) {
  1911. $key = array_search(trim($row['option_display_text']), $list);
  1912. unset($list[$key]);
  1913. }
  1914. }
  1915. // we store the new field options in the database
  1916. foreach ($list as $key => $option) {
  1917. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = '".intval($fieldid)."'";
  1918. $res = Database::query($sql);
  1919. $max = 1;
  1920. if (Database::num_rows($res) > 0) {
  1921. $row = Database::fetch_array($res);
  1922. $max = $row[0] + 1;
  1923. }
  1924. $time = time();
  1925. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms)
  1926. VALUES ('".intval($fieldid)."','".Database::escape_string($option)."','".Database::escape_string($option)."',$max,FROM_UNIXTIME($time))";
  1927. $result = Database::query($sql);
  1928. }
  1929. return true;
  1930. }
  1931. /**
  1932. * Check if a field is available
  1933. * @param string the wanted fieldname
  1934. * @return boolean true if the wanted username is available
  1935. */
  1936. public static function is_extra_field_available($fieldname)
  1937. {
  1938. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1939. $sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
  1940. $res = Database::query($sql);
  1941. return Database::num_rows($res) > 0;
  1942. }
  1943. /**
  1944. * Gets user extra fields data
  1945. * @param integer User ID
  1946. * @param boolean Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  1947. * @param boolean Whether to return invisible fields as well
  1948. * @param boolean Whether to split multiple-selection fields or not
  1949. * @return array Array of fields => value for the given user
  1950. */
  1951. public static function get_extra_user_data($user_id, $prefix = false, $all_visibility = true, $splitmultiple = false, $field_filter = null)
  1952. {
  1953. // A sanity check.
  1954. if (empty($user_id)) {
  1955. $user_id = 0;
  1956. } else {
  1957. if ($user_id != strval(intval($user_id)))
  1958. return array();
  1959. }
  1960. $extra_data = array();
  1961. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1962. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1963. $user_id = intval($user_id);
  1964. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1965. $filter_cond = '';
  1966. if (!$all_visibility) {
  1967. if (isset($field_filter)) {
  1968. $field_filter = intval($field_filter);
  1969. $filter_cond .= " AND field_filter = $field_filter ";
  1970. }
  1971. $sql .= " WHERE f.field_visible = 1 $filter_cond ";
  1972. } else {
  1973. if (isset($field_filter)) {
  1974. $field_filter = intval($field_filter);
  1975. $sql .= " WHERE field_filter = $field_filter ";
  1976. }
  1977. }
  1978. $sql .= " ORDER BY f.field_order";
  1979. $res = Database::query($sql);
  1980. if (Database::num_rows($res) > 0) {
  1981. while ($row = Database::fetch_array($res)) {
  1982. if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
  1983. $tags = self::get_user_tags_to_string($user_id, $row['id'], false);
  1984. $extra_data['extra_'.$row['fvar']] = $tags;
  1985. } else {
  1986. $sqlu = "SELECT field_value as fval FROM $t_ufv WHERE field_id=".$row['id']." AND user_id = ".$user_id;
  1987. $resu = Database::query($sqlu);
  1988. $fval = '';
  1989. // get default value
  1990. $sql_df = "SELECT field_default_value as fval_df ".
  1991. " FROM $t_uf ".
  1992. " WHERE id=".$row['id'];
  1993. $res_df = Database::query($sql_df);
  1994. if (Database::num_rows($resu) > 0) {
  1995. $rowu = Database::fetch_array($resu);
  1996. $fval = $rowu['fval'];
  1997. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  1998. $fval = explode(';', $rowu['fval']);
  1999. }
  2000. } else {
  2001. $row_df = Database::fetch_array($res_df);
  2002. $fval = $row_df['fval_df'];
  2003. }
  2004. // We get here (and fill the $extra_data array) even if there is no user with data (we fill it with default values)
  2005. if ($prefix) {
  2006. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2007. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2008. } else {
  2009. $extra_data['extra_'.$row['fvar']] = $fval;
  2010. }
  2011. } else {
  2012. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  2013. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  2014. } else {
  2015. $extra_data[$row['fvar']] = $fval;
  2016. }
  2017. }
  2018. }
  2019. }
  2020. }
  2021. return $extra_data;
  2022. }
  2023. /** Get extra user data by field
  2024. * @param int user ID
  2025. * @param string the internal variable name of the field
  2026. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2027. */
  2028. public static function get_extra_user_data_by_field($user_id, $field_variable, $prefix = false, $all_visibility = true, $splitmultiple = false)
  2029. {
  2030. // A sanity check.
  2031. if (empty($user_id)) {
  2032. $user_id = 0;
  2033. } else {
  2034. if ($user_id != strval(intval($user_id)))
  2035. return array();
  2036. }
  2037. $extra_data = array();
  2038. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  2039. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  2040. $user_id = intval($user_id);
  2041. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  2042. $sql .= " WHERE f.field_variable = '$field_variable' ";
  2043. if (!$all_visibility) {
  2044. $sql .= " AND f.field_visible = 1 ";
  2045. }
  2046. $sql .= " ORDER BY f.field_order";
  2047. $res = Database::query($sql);
  2048. if (Database::num_rows($res) > 0) {
  2049. while ($row = Database::fetch_array($res)) {
  2050. $sqlu = "SELECT field_value as fval ".
  2051. " FROM $t_ufv ".
  2052. " WHERE field_id=".$row['id']."".
  2053. " AND user_id=".$user_id;
  2054. $resu = Database::query($sqlu);
  2055. $fval = '';
  2056. if (Database::num_rows($resu) > 0) {
  2057. $rowu = Database::fetch_array($resu);
  2058. $fval = $rowu['fval'];
  2059. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  2060. $fval = explode(';', $rowu['fval']);
  2061. }
  2062. }
  2063. if ($prefix) {
  2064. $extra_data['extra_'.$row['fvar']] = $fval;
  2065. } else {
  2066. $extra_data[$row['fvar']] = $fval;
  2067. }
  2068. }
  2069. }
  2070. return $extra_data;
  2071. }
  2072. /**
  2073. * Get the extra field information for a certain field (the options as well)
  2074. * @param int The name of the field we want to know everything about
  2075. * @return array Array containing all the information about the extra profile field
  2076. * (first level of array contains field details, then 'options' sub-array contains options details,
  2077. * as returned by the database)
  2078. * @author Julio Montoya
  2079. * @since v1.8.6
  2080. */
  2081. public static function get_extra_field_information_by_name($field_variable, $fuzzy = false)
  2082. {
  2083. // database table definition
  2084. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  2085. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  2086. // all the information of the field
  2087. $sql = "SELECT * FROM $table_field WHERE field_variable='".Database::escape_string($field_variable)."'";
  2088. $result = Database::query($sql);
  2089. $return = Database::fetch_array($result);
  2090. // all the options of the field
  2091. $sql = "SELECT * FROM $table_field_options WHERE field_id='".intval($return['id'])."' ORDER BY option_order ASC";
  2092. $result = Database::query($sql);
  2093. while ($row = Database::fetch_array($result)) {
  2094. $return['options'][$row['id']] = $row;
  2095. }
  2096. return $return;
  2097. }
  2098. public static function get_all_extra_field_by_type($field_type)
  2099. {
  2100. // database table definition
  2101. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  2102. // all the information of the field
  2103. $sql = "SELECT * FROM $table_field WHERE field_type='".Database::escape_string($field_type)."'";
  2104. $result = Database::query($sql);
  2105. $return = array();
  2106. while ($row = Database::fetch_array($result)) {
  2107. $return[] = $row['id'];
  2108. }
  2109. return $return;
  2110. }
  2111. /**
  2112. * Get all the extra field information of a certain field (also the options)
  2113. *
  2114. * @param int $field_name the name of the field we want to know everything of
  2115. * @return array $return containing all th information about the extra profile field
  2116. * @author Julio Montoya
  2117. * @since v1.8.6
  2118. */
  2119. public static function get_extra_field_information($field_id)
  2120. {
  2121. // database table definition
  2122. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  2123. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  2124. // all the information of the field
  2125. $sql = "SELECT * FROM $table_field WHERE id='".intval($field_id)."'";
  2126. $result = Database::query($sql);
  2127. $return = Database::fetch_array($result);
  2128. // all the options of the field
  2129. $sql = "SELECT * FROM $table_field_options WHERE field_id='".intval($field_id)."' ORDER BY option_order ASC";
  2130. $result = Database::query($sql);
  2131. while ($row = Database::fetch_array($result)) {
  2132. $return['options'][$row['id']] = $row;
  2133. }
  2134. return $return;
  2135. }
  2136. /** Get extra user data by value
  2137. * @param string the internal variable name of the field
  2138. * @param string the internal value of the field
  2139. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  2140. */
  2141. public static function get_extra_user_data_by_value($field_variable, $field_value, $all_visibility = true)
  2142. {
  2143. $extra_data = array();
  2144. $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  2145. $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  2146. $table_user_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  2147. $where = '';
  2148. /*
  2149. if (is_array($field_variable_array) && is_array($field_value_array)) {
  2150. if (count($field_variable_array) == count($field_value_array)) {
  2151. $field_var_count = count($field_variable_array);
  2152. for ($i = 0; $i < $field_var_count; $i++) {
  2153. if ($i != 0 && $i != $field_var_count) {
  2154. $where.= ' AND ';
  2155. }
  2156. $where.= "field_variable='".Database::escape_string($field_variable_array[$i])."' AND user_field_options.id='".Database::escape_string($field_value_array[$i])."'";
  2157. }
  2158. }
  2159. } */
  2160. $where = "field_variable='".Database::escape_string($field_variable)."' AND field_value='".Database::escape_string($field_value)."'";
  2161. $sql = "SELECT user_id FROM $table_user_field user_field INNER JOIN $table_user_field_values user_field_values
  2162. ON (user_field.id = user_field_values.field_id)
  2163. WHERE $where";
  2164. if ($all_visibility) {
  2165. $sql .= " AND user_field.field_visible = 1 ";
  2166. } else {
  2167. $sql .= " AND user_field.field_visible = 0 ";
  2168. }
  2169. $res = Database::query($sql);
  2170. $result_data = array();
  2171. if (Database::num_rows($res) > 0) {
  2172. while ($row = Database::fetch_array($res)) {
  2173. $result_data[] = $row['user_id'];
  2174. }
  2175. }
  2176. return $result_data;
  2177. }
  2178. /**
  2179. * Get extra user data by field variable
  2180. * @param string field variable
  2181. * @return array data
  2182. */
  2183. public static function get_extra_user_data_by_field_variable($field_variable)
  2184. {
  2185. $tbl_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  2186. $extra_information_by_variable = self::get_extra_field_information_by_name($field_variable);
  2187. $field_id = intval($extra_information_by_variable['id']);
  2188. $data = array();
  2189. $sql = "SELECT * FROM $tbl_user_field_values WHERE field_id='$field_id'";
  2190. $rs = Database::query($sql);
  2191. if (Database::num_rows($rs) > 0) {
  2192. while ($row = Database::fetch_array($rs)) {
  2193. $user_id = $row['user_id'];
  2194. $data[$user_id] = $row;
  2195. }
  2196. }
  2197. return $data;
  2198. }
  2199. /**
  2200. * Gives a list of [session_category][session_id] for the current user.
  2201. * @param integer $user_id
  2202. * @param boolean whether to fill the first element or not (to give space for courses out of categories)
  2203. * @param boolean optional true if limit time from session is over, false otherwise
  2204. * @return array list of statuses [session_category][session_id]
  2205. * @todo ensure multiple access urls are managed correctly
  2206. */
  2207. public static function get_sessions_by_category(
  2208. $user_id,
  2209. $is_time_over = false,
  2210. $ignore_visibility_for_admins = false
  2211. ) {
  2212. // Database Table Definitions
  2213. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2214. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2215. $tbl_session_category = Database :: get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2216. if ($user_id != strval(intval($user_id))) {
  2217. return array();
  2218. }
  2219. // Get the list of sessions per user
  2220. $now = api_get_utc_datetime();
  2221. $sql = "SELECT DISTINCT
  2222. session.id,
  2223. session.name,
  2224. session.date_start,
  2225. session.date_end,
  2226. session_category_id,
  2227. session_category.name as session_category_name,
  2228. session_category.date_start session_category_date_start,
  2229. session_category.date_end session_category_date_end,
  2230. nb_days_access_before_beginning,
  2231. nb_days_access_after_end
  2232. FROM $tbl_session as session
  2233. LEFT JOIN $tbl_session_category session_category
  2234. ON (session_category_id = session_category.id)
  2235. LEFT JOIN $tbl_session_course_user as session_rel_course_user
  2236. ON (session_rel_course_user.id_session = session.id)
  2237. WHERE (
  2238. session_rel_course_user.id_user = $user_id OR
  2239. session.id_coach = $user_id
  2240. )
  2241. ORDER BY session_category_name, name";
  2242. $result = Database::query($sql);
  2243. $categories = array();
  2244. if (Database::num_rows($result) > 0) {
  2245. while ($row = Database::fetch_array($result)) {
  2246. // User portal filters:
  2247. if ($is_time_over) {
  2248. // History
  2249. if (isset($row['date_end']) && $row['date_end'] != '0000-00-00') {
  2250. if ($row['date_end'].' 23:59:59' > $now) {
  2251. continue;
  2252. }
  2253. }
  2254. if ($row['date_end'] == '0000-00-00') {
  2255. continue;
  2256. }
  2257. } else {
  2258. // Current user portal
  2259. if (api_is_allowed_to_create_course()) {
  2260. // Teachers can access the session depending in the access_coach date
  2261. } else {
  2262. if (isset($row['date_end']) && $row['date_end'] != '0000-00-00') {
  2263. if ($row['date_end'].' 23:59:59' <= $now) {
  2264. continue;
  2265. }
  2266. }
  2267. }
  2268. }
  2269. $categories[$row['session_category_id']]['session_category'] = array(
  2270. 'id' => $row['session_category_id'],
  2271. 'name' => $row['session_category_name'],
  2272. 'date_start' => $row['session_category_date_start'],
  2273. 'date_end' => $row['session_category_date_end']
  2274. );
  2275. $session_id = $row['id'];
  2276. $courseList = UserManager::get_courses_list_by_session(
  2277. $user_id,
  2278. $row['id']
  2279. );
  2280. // Session visibility.
  2281. $visibility = api_get_session_visibility(
  2282. $session_id,
  2283. null,
  2284. $ignore_visibility_for_admins
  2285. );
  2286. // Course Coach session visibility.
  2287. $blockedCourseCount = 0;
  2288. $closedVisibilityList = array(
  2289. COURSE_VISIBILITY_CLOSED,
  2290. COURSE_VISIBILITY_HIDDEN
  2291. );
  2292. foreach ($courseList as $course) {
  2293. // Checking session visibility
  2294. $visibility = api_get_session_visibility(
  2295. $session_id,
  2296. $course['code'],
  2297. $ignore_visibility_for_admins
  2298. );
  2299. $courseIsVisible = !in_array($course['visibility'], $closedVisibilityList);
  2300. if ($courseIsVisible == false || $visibility == SESSION_INVISIBLE) {
  2301. $blockedCourseCount++;
  2302. }
  2303. }
  2304. // If all courses are blocked then no show in the list.
  2305. if ($blockedCourseCount == count($courseList)) {
  2306. $visibility = SESSION_INVISIBLE;
  2307. }
  2308. switch ($visibility) {
  2309. case SESSION_VISIBLE_READ_ONLY:
  2310. case SESSION_VISIBLE:
  2311. case SESSION_AVAILABLE:
  2312. break;
  2313. case SESSION_INVISIBLE:
  2314. continue(2);
  2315. }
  2316. $categories[$row['session_category_id']]['sessions'][$row['id']] = array(
  2317. 'session_name' => $row['name'],
  2318. 'session_id' => $row['id'],
  2319. 'date_start' => $row['date_start'],
  2320. 'date_end' => $row['date_end'],
  2321. 'nb_days_access_before_beginning' => $row['nb_days_access_before_beginning'],
  2322. 'nb_days_access_after_end' => $row['nb_days_access_after_end'],
  2323. 'courses' => $courseList
  2324. );
  2325. }
  2326. }
  2327. return $categories;
  2328. }
  2329. /**
  2330. * Gives a list of [session_id-course_code] => [status] for the current user.
  2331. * @param integer $user_id
  2332. * @return array list of statuses (session_id-course_code => status)
  2333. */
  2334. public static function get_personal_session_course_list($user_id)
  2335. {
  2336. // Database Table Definitions
  2337. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  2338. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  2339. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2340. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  2341. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2342. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2343. if ($user_id != strval(intval($user_id))) {
  2344. return array();
  2345. }
  2346. // We filter the courses from the URL
  2347. $join_access_url = $where_access_url = '';
  2348. if (api_get_multiple_access_url()) {
  2349. $access_url_id = api_get_current_access_url_id();
  2350. if ($access_url_id != -1) {
  2351. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2352. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  2353. $where_access_url = " AND access_url_id = $access_url_id ";
  2354. }
  2355. }
  2356. // Courses in which we subscribed out of any session
  2357. $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  2358. $sql = "SELECT
  2359. course.code,
  2360. course_rel_user.status course_rel_status,
  2361. course_rel_user.sort sort,
  2362. course_rel_user.user_course_cat user_course_cat
  2363. FROM ".$tbl_course_user." course_rel_user
  2364. LEFT JOIN ".$tbl_course." course
  2365. ON course.code = course_rel_user.course_code
  2366. LEFT JOIN ".$tbl_user_course_category." user_course_category
  2367. ON course_rel_user.user_course_cat = user_course_category.id
  2368. $join_access_url
  2369. WHERE
  2370. course_rel_user.user_id = '".$user_id."' AND
  2371. course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
  2372. $where_access_url
  2373. ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
  2374. $course_list_sql_result = Database::query($sql);
  2375. $personal_course_list = array();
  2376. if (Database::num_rows($course_list_sql_result) > 0) {
  2377. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2378. $course_info = api_get_course_info($result_row['code']);
  2379. $result_row['course_info'] = $course_info;
  2380. $personal_course_list[] = $result_row;
  2381. }
  2382. }
  2383. $coachCourseConditions = null;
  2384. // Getting sessions that are related to a coach in the session_rel_course_rel_user table
  2385. if (api_is_allowed_to_create_course()) {
  2386. $sessionListFromCourseCoach = array();
  2387. $sql =" SELECT DISTINCT id_session FROM $tbl_session_course_user
  2388. WHERE id_user = $user_id AND status = 2 ";
  2389. $result = Database::query($sql);
  2390. if (Database::num_rows($result)) {
  2391. $result = Database::store_result($result);
  2392. foreach ($result as $session) {
  2393. $sessionListFromCourseCoach[]= $session['id_session'];
  2394. }
  2395. }
  2396. if (!empty($sessionListFromCourseCoach)) {
  2397. $condition = implode("','", $sessionListFromCourseCoach);
  2398. $coachCourseConditions = " OR ( id IN ('$condition'))";
  2399. }
  2400. }
  2401. // Get the list of sessions where the user is subscribed
  2402. // This is divided into two different queries
  2403. $sessions = array();
  2404. $sql = "SELECT DISTINCT id, name, date_start, date_end
  2405. FROM $tbl_session_user, $tbl_session
  2406. WHERE (
  2407. id_session = id AND
  2408. id_user = $user_id AND
  2409. relation_type <> ".SESSION_RELATION_TYPE_RRHH."
  2410. )
  2411. $coachCourseConditions
  2412. ORDER BY date_start, date_end, name";
  2413. $result = Database::query($sql);
  2414. if (Database::num_rows($result)>0) {
  2415. while ($row = Database::fetch_assoc($result)) {
  2416. $sessions[$row['id']] = $row;
  2417. }
  2418. }
  2419. $sql = "SELECT DISTINCT id, name, date_start, date_end
  2420. FROM $tbl_session_user, $tbl_session
  2421. WHERE (
  2422. id_coach = $user_id
  2423. )
  2424. $coachCourseConditions
  2425. ORDER BY date_start, date_end, name";
  2426. $result = Database::query($sql);
  2427. if (Database::num_rows($result)>0) {
  2428. while ($row = Database::fetch_assoc($result)) {
  2429. if (empty($sessions[$row['id']])) {
  2430. $sessions[$row['id']] = $row;
  2431. }
  2432. }
  2433. }
  2434. if (api_is_allowed_to_create_course()) {
  2435. foreach ($sessions as $enreg) {
  2436. $session_id = $enreg['id'];
  2437. $session_visibility = api_get_session_visibility($session_id);
  2438. if ($session_visibility == SESSION_INVISIBLE) {
  2439. continue;
  2440. }
  2441. $id_session = $enreg['id'];
  2442. $personal_course_list_sql = "SELECT DISTINCT
  2443. course.code code,
  2444. course.title i,
  2445. ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t,
  2446. email, course.course_language l,
  2447. 1 sort,
  2448. category_code user_course_cat,
  2449. date_start,
  2450. date_end,
  2451. session.id as id_session,
  2452. session.name as session_name
  2453. FROM $tbl_session_course_user as session_course_user
  2454. INNER JOIN $tbl_course AS course
  2455. ON course.code = session_course_user.course_code
  2456. INNER JOIN $tbl_session as session
  2457. ON session.id = session_course_user.id_session
  2458. LEFT JOIN $tbl_user as user
  2459. ON user.user_id = session_course_user.id_user OR session.id_coach = user.user_id
  2460. WHERE
  2461. session_course_user.id_session = $id_session AND (
  2462. (session_course_user.id_user = $user_id AND session_course_user.status = 2)
  2463. OR session.id_coach = $user_id
  2464. )
  2465. ORDER BY i";
  2466. $course_list_sql_result = Database::query($personal_course_list_sql);
  2467. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2468. $result_row['course_info'] = api_get_course_info($result_row['code']);
  2469. $key = $result_row['id_session'].' - '.$result_row['code'];
  2470. $personal_course_list[$key] = $result_row;
  2471. }
  2472. }
  2473. }
  2474. foreach ($sessions as $enreg) {
  2475. $session_id = $enreg['id'];
  2476. $session_visibility = api_get_session_visibility($session_id);
  2477. if ($session_visibility == SESSION_INVISIBLE) {
  2478. continue;
  2479. }
  2480. /* This query is very similar to the above query,
  2481. but it will check the session_rel_course_user table if there are courses registered to our user or not */
  2482. $personal_course_list_sql = "SELECT DISTINCT
  2483. course.code code,
  2484. course.title i, CONCAT(user.lastname,' ',user.firstname) t,
  2485. email,
  2486. course.course_language l,
  2487. 1 sort,
  2488. category_code user_course_cat,
  2489. date_start,
  2490. date_end,
  2491. session.id as id_session,
  2492. session.name as session_name,
  2493. IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5')
  2494. FROM $tbl_session_course_user as session_course_user
  2495. INNER JOIN $tbl_course AS course
  2496. ON course.code = session_course_user.course_code AND session_course_user.id_session = $session_id
  2497. INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
  2498. LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
  2499. WHERE session_course_user.id_user = $user_id
  2500. ORDER BY i";
  2501. $course_list_sql_result = Database::query($personal_course_list_sql);
  2502. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  2503. $result_row['course_info'] = api_get_course_info($result_row['code']);
  2504. $key = $result_row['id_session'].' - '.$result_row['code'];
  2505. if (!isset($personal_course_list[$key])) {
  2506. $personal_course_list[$key] = $result_row;
  2507. }
  2508. }
  2509. }
  2510. return $personal_course_list;
  2511. }
  2512. /**
  2513. * Gives a list of courses for the given user in the given session
  2514. * @param integer $user_id
  2515. * @param integer $session_id
  2516. * @return array list of statuses (session_id-course_code => status)
  2517. */
  2518. public static function get_courses_list_by_session($user_id, $session_id)
  2519. {
  2520. // Database Table Definitions
  2521. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2522. $tableCourse = Database :: get_main_table(TABLE_MAIN_COURSE);
  2523. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2524. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  2525. $user_id = intval($user_id);
  2526. $session_id = intval($session_id);
  2527. //we filter the courses from the URL
  2528. $join_access_url = $where_access_url = '';
  2529. if (api_get_multiple_access_url()) {
  2530. $access_url_id = api_get_current_access_url_id();
  2531. if ($access_url_id != -1) {
  2532. $tbl_url_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2533. $join_access_url = " , $tbl_url_session url_rel_session ";
  2534. $where_access_url = " AND access_url_id = $access_url_id AND url_rel_session.session_id = $session_id ";
  2535. }
  2536. }
  2537. $personal_course_list = array();
  2538. $courses = array();
  2539. /* This query is very similar to the query below, but it will check the
  2540. session_rel_course_user table if there are courses registered
  2541. to our user or not */
  2542. $sql = "SELECT DISTINCT
  2543. scu.course_code as code, c.visibility, c.id as real_id
  2544. FROM $tbl_session_course_user as scu
  2545. INNER JOIN $tbl_session_course sc
  2546. ON (scu.id_session = sc.id_session AND scu.course_code = sc.course_code)
  2547. INNER JOIN $tableCourse as c
  2548. ON (scu.course_code = c.code)
  2549. $join_access_url
  2550. WHERE
  2551. scu.id_user = $user_id AND
  2552. scu.id_session = $session_id
  2553. $where_access_url
  2554. ORDER BY sc.position ASC";
  2555. $result = Database::query($sql);
  2556. if (Database::num_rows($result) > 0) {
  2557. while ($result_row = Database::fetch_array($result)) {
  2558. $result_row['status'] = 5;
  2559. if (!in_array($result_row['code'], $courses)) {
  2560. $personal_course_list[] = $result_row;
  2561. $courses[] = $result_row['code'];
  2562. }
  2563. }
  2564. }
  2565. if (api_is_allowed_to_create_course()) {
  2566. $sql = "SELECT DISTINCT
  2567. scu.course_code as code, c.visibility, c.id as real_id
  2568. FROM $tbl_session_course_user as scu
  2569. INNER JOIN $tbl_session as s
  2570. ON (scu.id_session = s.id)
  2571. INNER JOIN $tbl_session_course sc
  2572. ON (scu.id_session = sc.id_session AND scu.course_code = sc.course_code)
  2573. INNER JOIN $tableCourse as c
  2574. ON (scu.course_code = c.code)
  2575. $join_access_url
  2576. WHERE
  2577. s.id = $session_id AND
  2578. (
  2579. (scu.id_user=$user_id AND scu.status=2) OR
  2580. s.id_coach = $user_id
  2581. )
  2582. $where_access_url
  2583. ORDER BY sc.position ASC";
  2584. $result = Database::query($sql);
  2585. if (Database::num_rows($result) > 0) {
  2586. while ($result_row = Database::fetch_array($result)) {
  2587. $result_row['status'] = 2;
  2588. if (!in_array($result_row['code'], $courses)) {
  2589. $personal_course_list[] = $result_row;
  2590. $courses[] = $result_row['code'];
  2591. }
  2592. }
  2593. }
  2594. }
  2595. if (api_is_drh()) {
  2596. $session_list = SessionManager::get_sessions_followed_by_drh($user_id);
  2597. $session_list = array_keys($session_list);
  2598. if (in_array($session_id, $session_list)) {
  2599. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  2600. if (!empty($course_list)) {
  2601. foreach ($course_list as $course) {
  2602. $personal_course_list[] = $course;
  2603. }
  2604. }
  2605. }
  2606. } else {
  2607. //check if user is general coach for this session
  2608. $s = api_get_session_info($session_id);
  2609. if ($s['id_coach'] == $user_id) {
  2610. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  2611. if (!empty($course_list)) {
  2612. foreach ($course_list as $course) {
  2613. if (!in_array($course['code'], $courses)) {
  2614. $personal_course_list[] = $course;
  2615. }
  2616. }
  2617. }
  2618. }
  2619. }
  2620. return $personal_course_list;
  2621. }
  2622. /**
  2623. * Get user id from a username
  2624. * @param string Username
  2625. * @return int User ID (or false if not found)
  2626. */
  2627. public static function get_user_id_from_username($username)
  2628. {
  2629. if (empty($username)) {
  2630. return false;
  2631. }
  2632. $username = trim($username);
  2633. $username = Database::escape_string($username);
  2634. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  2635. $sql = "SELECT user_id FROM $t_user WHERE username = '$username'";
  2636. $res = Database::query($sql);
  2637. if ($res === false) {
  2638. return false;
  2639. }
  2640. if (Database::num_rows($res) !== 1) {
  2641. return false;
  2642. }
  2643. $row = Database::fetch_array($res);
  2644. return $row['user_id'];
  2645. }
  2646. /**
  2647. * Get the users files upload from his share_folder
  2648. * @param string User ID
  2649. * @param string course directory
  2650. * @param string resourcetype: images, all
  2651. * @return int User ID (or false if not found)
  2652. */
  2653. public static function get_user_upload_files_by_course($user_id, $course, $resourcetype = 'all')
  2654. {
  2655. $return = '';
  2656. if (!empty($user_id) && !empty($course)) {
  2657. $user_id = intval($user_id);
  2658. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  2659. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  2660. $file_list = array();
  2661. if (is_dir($path)) {
  2662. $handle = opendir($path);
  2663. while ($file = readdir($handle)) {
  2664. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
  2665. continue; // skip current/parent directory and .htaccess
  2666. }
  2667. $file_list[] = $file;
  2668. }
  2669. if (count($file_list) > 0) {
  2670. $return = "<h4>$course</h4>";
  2671. $return .= '<ul class="thumbnails">';
  2672. }
  2673. foreach ($file_list as $file) {
  2674. if ($resourcetype == "all") {
  2675. $return .= '<li><a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a></li>';
  2676. } elseif ($resourcetype == "images") {
  2677. //get extension
  2678. $ext = explode('.', $file);
  2679. if ($ext[1] == 'jpg' || $ext[1] == 'jpeg' || $ext[1] == 'png' || $ext[1] == 'gif' || $ext[1] == 'bmp' || $ext[1] == 'tif') {
  2680. $return .= '<li class="span2"><a class="thumbnail" href="'.$web_path.urlencode($file).'" target="_blank">
  2681. <img src="'.$web_path.urlencode($file).'" ></a>
  2682. </li>';
  2683. }
  2684. }
  2685. }
  2686. if (count($file_list) > 0) {
  2687. $return .= '</ul>';
  2688. }
  2689. }
  2690. }
  2691. return $return;
  2692. }
  2693. /**
  2694. * Gets the API key (or keys) and return them into an array
  2695. * @param int Optional user id (defaults to the result of api_get_user_id())
  2696. * @return array Non-indexed array containing the list of API keys for this user, or FALSE on error
  2697. */
  2698. public static function get_api_keys($user_id = null, $api_service = 'dokeos')
  2699. {
  2700. if ($user_id != strval(intval($user_id)))
  2701. return false;
  2702. if (empty($user_id)) {
  2703. $user_id = api_get_user_id();
  2704. }
  2705. if ($user_id === false)
  2706. return false;
  2707. $service_name = Database::escape_string($api_service);
  2708. if (is_string($service_name) === false) {
  2709. return false;
  2710. }
  2711. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2712. $sql = "SELECT * FROM $t_api WHERE user_id = $user_id AND api_service='$api_service';";
  2713. $res = Database::query($sql);
  2714. if ($res === false)
  2715. return false; //error during query
  2716. $num = Database::num_rows($res);
  2717. if ($num == 0)
  2718. return false;
  2719. $list = array();
  2720. while ($row = Database::fetch_array($res)) {
  2721. $list[$row['id']] = $row['api_key'];
  2722. }
  2723. return $list;
  2724. }
  2725. /**
  2726. * Adds a new API key to the users' account
  2727. * @param int Optional user ID (defaults to the results of api_get_user_id())
  2728. * @return boolean True on success, false on failure
  2729. */
  2730. public static function add_api_key($user_id = null, $api_service = 'dokeos')
  2731. {
  2732. if ($user_id != strval(intval($user_id)))
  2733. return false;
  2734. if (empty($user_id)) {
  2735. $user_id = api_get_user_id();
  2736. }
  2737. if ($user_id === false)
  2738. return false;
  2739. $service_name = Database::escape_string($api_service);
  2740. if (is_string($service_name) === false) {
  2741. return false;
  2742. }
  2743. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2744. $md5 = md5((time() + ($user_id * 5)) - rand(10000, 10000)); //generate some kind of random key
  2745. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  2746. $res = Database::query($sql);
  2747. if ($res === false)
  2748. return false; //error during query
  2749. $num = Database::insert_id();
  2750. return ($num == 0) ? false : $num;
  2751. }
  2752. /**
  2753. * Deletes an API key from the user's account
  2754. * @param int API key's internal ID
  2755. * @return boolean True on success, false on failure
  2756. */
  2757. public static function delete_api_key($key_id)
  2758. {
  2759. if ($key_id != strval(intval($key_id)))
  2760. return false;
  2761. if ($key_id === false)
  2762. return false;
  2763. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2764. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  2765. $res = Database::query($sql);
  2766. if ($res === false)
  2767. return false; //error during query
  2768. $num = Database::num_rows($res);
  2769. if ($num !== 1)
  2770. return false;
  2771. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  2772. $res = Database::query($sql);
  2773. if ($res === false)
  2774. return false; //error during query
  2775. return true;
  2776. }
  2777. /**
  2778. * Regenerate an API key from the user's account
  2779. * @param int user ID (defaults to the results of api_get_user_id())
  2780. * @param string API key's internal ID
  2781. * @return int num
  2782. */
  2783. public static function update_api_key($user_id, $api_service)
  2784. {
  2785. if ($user_id != strval(intval($user_id)))
  2786. return false;
  2787. if ($user_id === false)
  2788. return false;
  2789. $service_name = Database::escape_string($api_service);
  2790. if (is_string($service_name) === false) {
  2791. return false;
  2792. }
  2793. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2794. $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  2795. $res = Database::query($sql);
  2796. $num = Database::num_rows($res);
  2797. if ($num == 1) {
  2798. $id_key = Database::fetch_array($res, 'ASSOC');
  2799. self::delete_api_key($id_key['id']);
  2800. $num = self::add_api_key($user_id, $api_service);
  2801. } elseif ($num == 0) {
  2802. $num = self::add_api_key($user_id);
  2803. }
  2804. return $num;
  2805. }
  2806. /**
  2807. * @param int user ID (defaults to the results of api_get_user_id())
  2808. * @param string API key's internal ID
  2809. * @return int row ID, or return false if not found
  2810. */
  2811. public static function get_api_key_id($user_id, $api_service)
  2812. {
  2813. if ($user_id != strval(intval($user_id)))
  2814. return false;
  2815. if ($user_id === false)
  2816. return false;
  2817. if (empty($api_service))
  2818. return false;
  2819. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2820. $service_name = Database::escape_string($api_service);
  2821. $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  2822. $res = Database::query($sql);
  2823. if (Database::num_rows($res) < 1) {
  2824. return false;
  2825. }
  2826. $row = Database::fetch_array($res, 'ASSOC');
  2827. return $row['id'];
  2828. }
  2829. /**
  2830. * Checks if a user_id is platform admin
  2831. * @param int user ID
  2832. * @return boolean True if is admin, false otherwise
  2833. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  2834. */
  2835. public static function is_admin($user_id)
  2836. {
  2837. if (empty($user_id) or $user_id != strval(intval($user_id))) {
  2838. return false;
  2839. }
  2840. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  2841. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  2842. $res = Database::query($sql);
  2843. return Database::num_rows($res) === 1;
  2844. }
  2845. /**
  2846. * Get the total count of users
  2847. * @param int Status of users to be counted
  2848. * @param int Access URL ID (optional)
  2849. * @return mixed Number of users or false on error
  2850. */
  2851. public static function get_number_of_users($status = 0, $access_url_id = null)
  2852. {
  2853. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  2854. $t_a = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2855. $sql = "SELECT count(*) FROM $t_u u";
  2856. $sql2 = '';
  2857. if (is_int($status) && $status > 0) {
  2858. $sql2 .= " WHERE u.status = $status ";
  2859. }
  2860. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  2861. $sql .= ", $t_a a ";
  2862. $sql2 .= " AND a.access_url_id = $access_url_id AND u.user_id = a.user_id ";
  2863. }
  2864. $sql = $sql.$sql2;
  2865. $res = Database::query($sql);
  2866. if (Database::num_rows($res) === 1) {
  2867. return (int) Database::result($res, 0, 0);
  2868. }
  2869. return false;
  2870. }
  2871. /**
  2872. * Resize a picture
  2873. *
  2874. * @param string file picture
  2875. * @param int size in pixels
  2876. * @todo move this function somewhere else image.lib?
  2877. * @return obj image object
  2878. */
  2879. public static function resize_picture($file, $max_size_for_picture)
  2880. {
  2881. $temp = false;
  2882. if (file_exists($file)) {
  2883. $temp = new Image($file);
  2884. $image_size = $temp->get_image_size($file);
  2885. $width = $image_size['width'];
  2886. $height = $image_size['height'];
  2887. if ($width >= $height) {
  2888. if ($width >= $max_size_for_picture) {
  2889. // scale height
  2890. $new_height = round($height * ($max_size_for_picture / $width));
  2891. $temp->resize($max_size_for_picture, $new_height, 0);
  2892. }
  2893. } else { // height > $width
  2894. if ($height >= $max_size_for_picture) {
  2895. // scale width
  2896. $new_width = round($width * ($max_size_for_picture / $height));
  2897. $temp->resize($new_width, $max_size_for_picture, 0);
  2898. }
  2899. }
  2900. }
  2901. return $temp;
  2902. }
  2903. /**
  2904. * Gets the current user image
  2905. * @param string user id
  2906. * @param string picture user name
  2907. * @param string height
  2908. * @param string picture size it can be USER_IMAGE_SIZE_SMALL, USER_IMAGE_SIZE_MEDIUM, USER_IMAGE_SIZE_BIG or USER_IMAGE_SIZE_ORIGINAL
  2909. * @param string style css
  2910. * @return array with the file and the style of an image i.e $array['file'] $array['style']
  2911. */
  2912. public static function get_picture_user($user_id, $picture_file, $height, $size_picture = USER_IMAGE_SIZE_MEDIUM, $style = '')
  2913. {
  2914. $picture = array();
  2915. $picture['style'] = $style;
  2916. if ($picture_file == 'unknown.jpg') {
  2917. switch ($size_picture) {
  2918. case USER_IMAGE_SIZE_ORIGINAL :
  2919. case USER_IMAGE_SIZE_BIG :
  2920. case USER_IMAGE_SIZE_MEDIUM :
  2921. $picture_file = 'unknown.jpg';
  2922. break;
  2923. case USER_IMAGE_SIZE_SMALL:
  2924. $picture_file = 'unknown_22.jpg';
  2925. break;
  2926. }
  2927. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/'.$picture_file;
  2928. return $picture;
  2929. }
  2930. switch ($size_picture) {
  2931. case USER_IMAGE_SIZE_ORIGINAL :
  2932. $size_picture = '';
  2933. break;
  2934. case USER_IMAGE_SIZE_BIG :
  2935. $size_picture = 'big_';
  2936. break;
  2937. case USER_IMAGE_SIZE_MEDIUM :
  2938. $size_picture = 'medium_';
  2939. break;
  2940. case USER_IMAGE_SIZE_SMALL :
  2941. $size_picture = 'small_';
  2942. break;
  2943. default:
  2944. $size_picture = 'medium_';
  2945. }
  2946. $image_array_sys = self::get_user_picture_path_by_id($user_id, 'system', false, true);
  2947. $image_array = self::get_user_picture_path_by_id($user_id, 'web', false, true);
  2948. $file = $image_array_sys['dir'].$size_picture.$picture_file;
  2949. if (file_exists($file)) {
  2950. $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
  2951. $picture['style'] = '';
  2952. if ($height > 0) {
  2953. $dimension = api_getimagesize($picture['file']);
  2954. $margin = (($height - $dimension['width']) / 2);
  2955. //@ todo the padding-top should not be here
  2956. $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension['width'].'px; height:'.$dimension['height'].'px;" ';
  2957. $picture['original_height'] = $dimension['width'];
  2958. $picture['original_width'] = $dimension['height'];
  2959. }
  2960. } else {
  2961. $file = $image_array_sys['dir'].$picture_file;
  2962. if (file_exists($file) && !is_dir($file)) {
  2963. $picture['file'] = $image_array['dir'].$picture_file;
  2964. } else {
  2965. switch ($size_picture) {
  2966. case 'big_' :
  2967. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
  2968. break;
  2969. case 'medium_' :
  2970. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_50_50.jpg';
  2971. break;
  2972. case 'small_' :
  2973. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
  2974. break;
  2975. default:
  2976. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
  2977. break;
  2978. }
  2979. }
  2980. }
  2981. return $picture;
  2982. }
  2983. /**
  2984. * @author Isaac flores <isaac.flores@dokeos.com>
  2985. * @param string The email administrator
  2986. * @param integer The user id
  2987. * @param string The message title
  2988. * @param string The content message
  2989. */
  2990. public static function send_message_in_outbox($email_administrator, $user_id, $title, $content)
  2991. {
  2992. $table_message = Database::get_main_table(TABLE_MESSAGE);
  2993. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2994. $title = api_utf8_decode($title);
  2995. $content = api_utf8_decode($content);
  2996. $email_administrator = Database::escape_string($email_administrator);
  2997. //message in inbox
  2998. $sql_message_outbox = 'SELECT user_id from '.$table_user.' WHERE email="'.$email_administrator.'" ';
  2999. //$num_row_query = Database::num_rows($sql_message_outbox);
  3000. $res_message_outbox = Database::query($sql_message_outbox);
  3001. $array_users_administrator = array();
  3002. while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) {
  3003. $array_users_administrator[] = $row_message_outbox['user_id'];
  3004. }
  3005. //allow to insert messages in outbox
  3006. for ($i = 0; $i < count($array_users_administrator); $i++) {
  3007. $sql_insert_outbox = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
  3008. " VALUES (".
  3009. "'".(int) $user_id."', '".(int) ($array_users_administrator[$i])."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
  3010. ")";
  3011. $rs = Database::query($sql_insert_outbox);
  3012. }
  3013. }
  3014. /*
  3015. *
  3016. * USER TAGS
  3017. *
  3018. * Intructions to create a new user tag by Julio Montoya <gugli100@gmail.com>
  3019. *
  3020. * 1. Create a new extra field in main/admin/user_fields.php with the "TAG" field type make it available and visible. Called it "books" for example.
  3021. * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags.
  3022. * 3. All the tags are registered in the user_tag table and the relationship between user and tags is in the user_rel_tag table
  3023. * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies.
  3024. * 5. Test and enjoy.
  3025. *
  3026. */
  3027. /**
  3028. * Gets the tags of a specific field_id
  3029. *
  3030. * @param int field_id
  3031. * @param string how we are going to result value in array or in a string (json)
  3032. * @return mixed
  3033. * @since Nov 2009
  3034. * @version 1.8.6.2
  3035. */
  3036. public static function get_tags($tag, $field_id, $return_format = 'json', $limit = 10)
  3037. {
  3038. // database table definition
  3039. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3040. $field_id = intval($field_id);
  3041. $limit = intval($limit);
  3042. $tag = trim(Database::escape_string($tag));
  3043. // all the information of the field
  3044. $sql = "SELECT DISTINCT id, tag from $table_user_tag
  3045. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit";
  3046. $result = Database::query($sql);
  3047. $return = array();
  3048. if (Database::num_rows($result) > 0) {
  3049. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3050. $return[] = array('caption' => $row['tag'], 'value' => $row['tag']);
  3051. }
  3052. }
  3053. if ($return_format == 'json') {
  3054. $return = json_encode($return);
  3055. }
  3056. return $return;
  3057. }
  3058. /**
  3059. * @param int $field_id
  3060. * @param int $limit
  3061. * @return array
  3062. */
  3063. public static function get_top_tags($field_id, $limit = 100)
  3064. {
  3065. // database table definition
  3066. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3067. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3068. $field_id = intval($field_id);
  3069. $limit = intval($limit);
  3070. // all the information of the field
  3071. $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv INNER JOIN $table_user_tag ut ON(ut.id = uv.tag_id)
  3072. WHERE field_id = $field_id GROUP BY tag_id ORDER BY count DESC LIMIT $limit";
  3073. $result = Database::query($sql);
  3074. $return = array();
  3075. if (Database::num_rows($result) > 0) {
  3076. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3077. $return[] = $row;
  3078. }
  3079. }
  3080. return $return;
  3081. }
  3082. /**
  3083. * Get user's tags
  3084. * @param int field_id
  3085. * @param int user_id
  3086. * @return array
  3087. */
  3088. public static function get_user_tags($user_id, $field_id)
  3089. {
  3090. // database table definition
  3091. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3092. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3093. $field_id = intval($field_id);
  3094. $user_id = intval($user_id);
  3095. // all the information of the field
  3096. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID)
  3097. WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag";
  3098. $result = Database::query($sql);
  3099. $return = array();
  3100. if (Database::num_rows($result) > 0) {
  3101. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3102. $return[$row['id']] = array('tag' => $row['tag'], 'count' => $row['count']);
  3103. }
  3104. }
  3105. return $return;
  3106. }
  3107. /**
  3108. * Get user's tags
  3109. * @param int user_id
  3110. * @param int field_id
  3111. * @param bool show links or not
  3112. * @return array
  3113. */
  3114. public static function get_user_tags_to_string($user_id, $field_id, $show_links = true)
  3115. {
  3116. // database table definition
  3117. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3118. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3119. $field_id = intval($field_id);
  3120. $user_id = intval($user_id);
  3121. // all the information of the field
  3122. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID)
  3123. WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag";
  3124. $result = Database::query($sql);
  3125. $return = array();
  3126. if (Database::num_rows($result) > 0) {
  3127. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3128. $return[$row['id']] = array('tag' => $row['tag'], 'count' => $row['count']);
  3129. }
  3130. }
  3131. $user_tags = $return;
  3132. $tag_tmp = array();
  3133. foreach ($user_tags as $tag) {
  3134. if ($show_links) {
  3135. $tag_tmp[] = '<a href="'.api_get_path(WEB_PATH).'main/search/index.php?q='.$tag['tag'].'">'.$tag['tag'].'</a>';
  3136. } else {
  3137. $tag_tmp[] = $tag['tag'];
  3138. }
  3139. }
  3140. if (is_array($user_tags) && count($user_tags) > 0) {
  3141. $return = implode(', ', $tag_tmp);
  3142. } else {
  3143. return '';
  3144. }
  3145. return $return;
  3146. }
  3147. /**
  3148. * Get the tag id
  3149. * @param int tag
  3150. * @param int field_id
  3151. * @return int returns 0 if fails otherwise the tag id
  3152. */
  3153. public static function get_tag_id($tag, $field_id)
  3154. {
  3155. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3156. $tag = Database::escape_string($tag);
  3157. $field_id = intval($field_id);
  3158. //with COLLATE latin1_bin to select query in a case sensitive mode
  3159. $sql = "SELECT id FROM $table_user_tag WHERE tag LIKE '$tag' AND field_id = $field_id";
  3160. $result = Database::query($sql);
  3161. if (Database::num_rows($result) > 0) {
  3162. $row = Database::fetch_array($result, 'ASSOC');
  3163. return $row['id'];
  3164. } else {
  3165. return 0;
  3166. }
  3167. }
  3168. /**
  3169. * Get the tag id
  3170. * @param int tag
  3171. * @param int field_id
  3172. * @return int 0 if fails otherwise the tag id
  3173. */
  3174. public static function get_tag_id_from_id($tag_id, $field_id)
  3175. {
  3176. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3177. $tag_id = intval($tag_id);
  3178. $field_id = intval($field_id);
  3179. $sql = "SELECT id FROM $table_user_tag WHERE id = '$tag_id' AND field_id = $field_id";
  3180. $result = Database::query($sql);
  3181. if (Database::num_rows($result) > 0) {
  3182. $row = Database::fetch_array($result, 'ASSOC');
  3183. return $row['id'];
  3184. } else {
  3185. return false;
  3186. }
  3187. }
  3188. /**
  3189. * Adds a user-tag value
  3190. * @param mixed tag
  3191. * @param int The user id
  3192. * @param int field id of the tag
  3193. * @return bool
  3194. */
  3195. public static function add_tag($tag, $user_id, $field_id)
  3196. {
  3197. // database table definition
  3198. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3199. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3200. $tag = trim(Database::escape_string($tag));
  3201. $user_id = intval($user_id);
  3202. $field_id = intval($field_id);
  3203. $tag_id = UserManager::get_tag_id($tag, $field_id);
  3204. /* IMPORTANT
  3205. * @todo we don't create tags with numbers
  3206. *
  3207. */
  3208. if (is_numeric($tag)) {
  3209. //the form is sending an id this means that the user select it from the list so it MUST exists
  3210. /* $new_tag_id = UserManager::get_tag_id_from_id($tag,$field_id);
  3211. if ($new_tag_id !== false) {
  3212. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id";
  3213. $result = Database::query($sql);
  3214. $last_insert_id = $new_tag_id;
  3215. } else {
  3216. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3217. $result = Database::query($sql);
  3218. $last_insert_id = Database::get_last_insert_id();
  3219. } */
  3220. } else {
  3221. }
  3222. //this is a new tag
  3223. if ($tag_id == 0) {
  3224. //the tag doesn't exist
  3225. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  3226. Database::query($sql);
  3227. $last_insert_id = Database::insert_id();
  3228. } else {
  3229. //the tag exists we update it
  3230. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $tag_id";
  3231. Database::query($sql);
  3232. $last_insert_id = $tag_id;
  3233. }
  3234. if (!empty($last_insert_id) && ($last_insert_id != 0)) {
  3235. //we insert the relationship user-tag
  3236. $sql_select = "SELECT tag_id FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $last_insert_id ";
  3237. $result = Database::query($sql_select);
  3238. //if the relationship does not exist we create it
  3239. if (Database::num_rows($result) == 0) {
  3240. $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
  3241. Database::query($sql);
  3242. }
  3243. }
  3244. }
  3245. /**
  3246. * Deletes an user tag
  3247. * @param int user id
  3248. * @param int field id
  3249. *
  3250. */
  3251. public static function delete_user_tags($user_id, $field_id)
  3252. {
  3253. // database table definition
  3254. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3255. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3256. $tags = UserManager::get_user_tags($user_id, $field_id);
  3257. if (is_array($tags) && count($tags) > 0) {
  3258. foreach ($tags as $key => $tag) {
  3259. if ($tag['count'] > '0') {
  3260. $sql = "UPDATE $table_user_tag SET count = count - 1 WHERE id = $key ";
  3261. Database::query($sql);
  3262. }
  3263. $sql = "DELETE FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $key";
  3264. Database::query($sql);
  3265. }
  3266. }
  3267. }
  3268. /**
  3269. * Process the tag list comes from the UserManager::update_extra_field_value() function
  3270. * @param array the tag list that will be added
  3271. * @param int user id
  3272. * @param int field id
  3273. * @return bool
  3274. */
  3275. public static function process_tags($tags, $user_id, $field_id)
  3276. {
  3277. //We loop the tags and add it to the DB
  3278. if (is_array($tags)) {
  3279. foreach ($tags as $tag) {
  3280. UserManager::add_tag($tag, $user_id, $field_id);
  3281. }
  3282. } else {
  3283. UserManager::add_tag($tags, $user_id, $field_id);
  3284. }
  3285. return true;
  3286. }
  3287. /**
  3288. * Returns a list of all administrators
  3289. * @author jmontoya
  3290. * @return array
  3291. */
  3292. public static function get_all_administrators()
  3293. {
  3294. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  3295. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  3296. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3297. $access_url_id = api_get_current_access_url_id();
  3298. if (api_get_multiple_access_url()) {
  3299. $sql = "SELECT admin.user_id, username, firstname, lastname, email
  3300. FROM $tbl_url_rel_user as url
  3301. INNER JOIN $table_admin as admin
  3302. ON (admin.user_id=url.user_id)
  3303. INNER JOIN $table_user u
  3304. ON (u.user_id=admin.user_id)
  3305. WHERE access_url_id ='".$access_url_id."'";
  3306. } else {
  3307. $sql = "SELECT admin.user_id, username, firstname, lastname, email
  3308. FROM $table_admin as admin
  3309. INNER JOIN $table_user u
  3310. ON (u.user_id=admin.user_id)";
  3311. }
  3312. $result = Database::query($sql);
  3313. $return = array();
  3314. if (Database::num_rows($result) > 0) {
  3315. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3316. $return[$row['user_id']] = $row;
  3317. }
  3318. }
  3319. return $return;
  3320. }
  3321. /**
  3322. * Search an user (tags, first name, last name and email )
  3323. * @param string $tag
  3324. * @param int $field_id field id of the tag
  3325. * @param int $from where to start in the query
  3326. * @param int $number_of_items
  3327. * @param bool $getCount get count or not
  3328. * @return array
  3329. */
  3330. public static function get_all_user_tags(
  3331. $tag,
  3332. $field_id = 0,
  3333. $from = 0,
  3334. $number_of_items = 10,
  3335. $getCount = false
  3336. ) {
  3337. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  3338. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  3339. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  3340. $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3341. $field_id = intval($field_id);
  3342. $from = intval($from);
  3343. $number_of_items = intval($number_of_items);
  3344. $where_field = "";
  3345. $where_extra_fields = UserManager::get_search_form_where_extra_fields();
  3346. if ($field_id != 0) {
  3347. $where_field = " field_id = $field_id AND ";
  3348. }
  3349. // all the information of the field
  3350. if ($getCount) {
  3351. $select = "SELECT count(DISTINCT u.user_id) count";
  3352. } else {
  3353. $select = "SELECT DISTINCT u.user_id, u.username, firstname, lastname, email, tag, picture_uri";
  3354. }
  3355. $sql = " $select
  3356. FROM $user_table u
  3357. INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id = url_rel_user.user_id)
  3358. LEFT JOIN $table_user_tag_values uv ON (u.user_id AND uv.user_id AND uv.user_id = url_rel_user.user_id)
  3359. LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
  3360. WHERE
  3361. ($where_field tag LIKE '".Database::escape_string($tag."%")."') OR
  3362. (
  3363. u.firstname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3364. u.lastname LIKE '".Database::escape_string("%".$tag."%")."' OR
  3365. u.username LIKE '".Database::escape_string("%".$tag."%")."' OR
  3366. concat(u.firstname, ' ', u.lastname) LIKE '".Database::escape_string("%".$tag."%")."' OR
  3367. concat(u.lastname, ' ', u.firstname) LIKE '".Database::escape_string("%".$tag."%")."'
  3368. )
  3369. ".(!empty($where_extra_fields) ? $where_extra_fields : '')."
  3370. AND
  3371. url_rel_user.access_url_id=".api_get_current_access_url_id();
  3372. $keyword_active = true;
  3373. // only active users
  3374. if ($keyword_active) {
  3375. $sql .= " AND u.active='1'";
  3376. }
  3377. // avoid anonymous
  3378. $sql .= " AND u.status <> 6 ";
  3379. $sql .= " ORDER BY username";
  3380. $sql .= " LIMIT $from , $number_of_items";
  3381. $result = Database::query($sql);
  3382. $return = array();
  3383. if (Database::num_rows($result) > 0) {
  3384. if ($getCount) {
  3385. $row = Database::fetch_array($result, 'ASSOC');
  3386. return $row['count'];
  3387. }
  3388. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3389. if (isset($return[$row['user_id']]) &&
  3390. !empty($return[$row['user_id']]['tag'])
  3391. ) {
  3392. $url = Display::url(
  3393. $row['tag'],
  3394. api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'],
  3395. array('class' => 'tag')
  3396. );
  3397. $row['tag'] = $url;
  3398. }
  3399. $return[$row['user_id']] = $row;
  3400. }
  3401. }
  3402. return $return;
  3403. }
  3404. /**
  3405. * Get extra filtrable user fields (type select)
  3406. * @return array
  3407. */
  3408. public static function get_extra_filtrable_fields()
  3409. {
  3410. $extraFieldList = UserManager::get_extra_fields();
  3411. $extraFiltrableFields = array();
  3412. if (is_array($extraFieldList)) {
  3413. foreach ($extraFieldList as $extraField) {
  3414. //if is enabled to filter and is a "<select>" field type
  3415. if ($extraField[8] == 1 && $extraField[2] == 4) {
  3416. $extraFiltrableFields[] = array(
  3417. 'name' => $extraField[3],
  3418. 'variable' => $extraField[1],
  3419. 'data' => $extraField[9]
  3420. );
  3421. }
  3422. }
  3423. }
  3424. if (is_array($extraFiltrableFields) && count($extraFiltrableFields) > 0 ) {
  3425. return $extraFiltrableFields;
  3426. }
  3427. }
  3428. /**
  3429. * Get extra where clauses for finding users based on extra filtrable user fields (type select)
  3430. * @return string With AND clauses based on user's ID which have the values to search in extra user fields
  3431. */
  3432. public static function get_search_form_where_extra_fields()
  3433. {
  3434. $useExtraFields = false;
  3435. $extraFields = UserManager::get_extra_filtrable_fields();
  3436. $extraFieldResult = array();
  3437. if (is_array($extraFields) && count($extraFields)>0 ) {
  3438. foreach ($extraFields as $extraField) {
  3439. $varName = 'field_'.$extraField['variable'];
  3440. if (UserManager::is_extra_field_available($extraField['variable'])) {
  3441. if (isset($_GET[$varName]) && $_GET[$varName]!='0') {
  3442. $useExtraFields = true;
  3443. $extraFieldResult[]= UserManager::get_extra_user_data_by_value($extraField['variable'], $_GET[$varName]);
  3444. }
  3445. }
  3446. }
  3447. }
  3448. if ($useExtraFields) {
  3449. $finalResult = array();
  3450. if (count($extraFieldResult)>1) {
  3451. for ($i=0; $i < count($extraFieldResult) -1; $i++) {
  3452. if (is_array($extraFieldResult[$i+1])) {
  3453. $finalResult = array_intersect($extraFieldResult[$i], $extraFieldResult[$i+1]);
  3454. }
  3455. }
  3456. } else {
  3457. $finalResult = $extraFieldResult[0];
  3458. }
  3459. if (is_array($finalResult) && count($finalResult)>0) {
  3460. $whereFilter = " AND u.user_id IN ('".implode("','", $finalResult)."') ";
  3461. } else {
  3462. //no results
  3463. $whereFilter = " AND u.user_id = -1 ";
  3464. }
  3465. return $whereFilter;
  3466. }
  3467. }
  3468. /**
  3469. * Show the search form
  3470. * @param string $query the value of the search box
  3471. * @return string HTML form
  3472. */
  3473. public static function get_search_form($query)
  3474. {
  3475. $extraFiltrableFields = UserManager::get_extra_filtrable_fields();
  3476. $extraFields = null;
  3477. if (is_array($extraFiltrableFields) && count($extraFiltrableFields)>0 ) {
  3478. foreach ($extraFiltrableFields as $extraField) {
  3479. $extraFields .= '<label class="extra_field">'.$extraField['name'].'</label>';
  3480. $varName = 'field_'.$extraField['variable'];
  3481. $extraFields .= '&nbsp;<select name="'.$varName.'" class="extra_field">';
  3482. $extraFields .= '<option value="0">--'.get_lang('Select').'--</option>';
  3483. foreach ($extraField['data'] as $option) {
  3484. $checked='';
  3485. if (isset($_GET[$varName])) {
  3486. if ($_GET[$varName]==$option[1]) {
  3487. $checked = 'selected="true"';
  3488. }
  3489. }
  3490. $extraFields .= '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';
  3491. }
  3492. $extraFields .= '</select>';
  3493. $extraFields .= '&nbsp;&nbsp;';
  3494. }
  3495. }
  3496. $searchType = isset($_GET['search_type']) ? $_GET['search_type'] : null;
  3497. return '
  3498. <form method="GET" class="well form-search" action="'.api_get_path(WEB_PATH).'main/social/search.php">
  3499. <input placeholder="'.get_lang('UsersGroups').'" type="text" class="input-small" value="'.api_htmlentities(Security::remove_XSS($query)).'" name="q"/> &nbsp;
  3500. ' . get_lang('Type') .'
  3501. <select name="search_type" onchange="javascript: extra_field_toogle();">
  3502. <option value="0">--'.get_lang('Select').'--</option>
  3503. <option value="1"' . (($searchType=='1')?'selected="selected"':"") . '>--' . get_lang('User') .'--</option>
  3504. <option value="2"' . (($searchType=='2')?'selected="selected"':"") . '>--' . get_lang('Group') . '--</option>
  3505. </select>
  3506. '.$extraFields.'
  3507. <button class="btn" type="submit" value="search">'.get_lang('Search').'</button>
  3508. </form>
  3509. <script>
  3510. extra_field_toogle();
  3511. function extra_field_toogle()
  3512. {
  3513. if (jQuery("select[name=search_type]").val() != "1") { jQuery(".extra_field").hide(); } else { jQuery(".extra_field").show(); }
  3514. }
  3515. </script>
  3516. ';
  3517. }
  3518. /**
  3519. * Shows the user menu
  3520. */
  3521. public static function show_menu()
  3522. {
  3523. echo '<div class="actions">';
  3524. echo '<a href="/main/auth/profile.php">'.Display::return_icon('profile.png').' '.get_lang('PersonalData').'</a>';
  3525. echo '<a href="/main/messages/inbox.php">'.Display::return_icon('inbox.png').' '.get_lang('Inbox').'</a>';
  3526. echo '<a href="/main/messages/outbox.php">'.Display::return_icon('outbox.png').' '.get_lang('Outbox').'</a>';
  3527. echo '<span style="float:right; padding-top:7px;">'.
  3528. '<a href="/main/auth/profile.php?show=1">'.Display::return_icon('edit.gif').' '.get_lang('Configuration').'</a>';
  3529. '</span>';
  3530. echo '</div>';
  3531. }
  3532. /**
  3533. * Gives a list of course auto-register (field special_course)
  3534. * @return array list of course
  3535. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>
  3536. * @deprecated this function is never use in chamilo, use CourseManager::get_special_course_list
  3537. * @since v1.8.6.2
  3538. */
  3539. public static function get_special_course_list()
  3540. {
  3541. // Database Table Definitions
  3542. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  3543. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  3544. $tbl_course_field = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
  3545. $tbl_course_field_value = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  3546. $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  3547. //we filter the courses from the URL
  3548. $join_access_url = $where_access_url = '';
  3549. if (api_get_multiple_access_url()) {
  3550. $access_url_id = api_get_current_access_url_id();
  3551. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3552. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  3553. $where_access_url = " AND access_url_id = $access_url_id ";
  3554. }
  3555. // Filter special courses
  3556. $sql_special_course = "SELECT course_code FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf ON ".
  3557. " tcfv.field_id = tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
  3558. $special_course_result = Database::query($sql_special_course);
  3559. $code_special_courses = '';
  3560. if (Database::num_rows($special_course_result) > 0) {
  3561. $special_course_list = array();
  3562. while ($result_row = Database::fetch_array($special_course_result)) {
  3563. $special_course_list[] = '"'.$result_row['course_code'].'"';
  3564. }
  3565. $code_special_courses = ' course.code IN ('.join($special_course_list, ',').') ';
  3566. }
  3567. $course_list = array();
  3568. if (!empty($code_special_courses)) {
  3569. $course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
  3570. FROM ".$tbl_course_user." course_rel_user
  3571. LEFT JOIN ".$tbl_course." course
  3572. ON course.code = course_rel_user.course_code
  3573. LEFT JOIN ".$tbl_user_course_category." user_course_category
  3574. ON course_rel_user.user_course_cat = user_course_category.id
  3575. $join_access_url
  3576. WHERE $code_special_courses $where_access_url
  3577. GROUP BY course.code
  3578. ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC";
  3579. $course_list_sql_result = Database::query($course_list_sql);
  3580. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  3581. $course_list[] = $result_row;
  3582. }
  3583. }
  3584. return $course_list;
  3585. }
  3586. /**
  3587. * Allow to register contact to social network
  3588. * @param int $friend_id user friend id
  3589. * @param int $my_user_id user id
  3590. * @param int $relation_type relation between users see constants definition
  3591. */
  3592. public static function relate_users($friend_id, $my_user_id, $relation_type)
  3593. {
  3594. $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
  3595. $friend_id = intval($friend_id);
  3596. $my_user_id = intval($my_user_id);
  3597. $relation_type = intval($relation_type);
  3598. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.' WHERE friend_user_id='.$friend_id.' AND user_id='.$my_user_id.' AND relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
  3599. $result = Database::query($sql);
  3600. $row = Database :: fetch_array($result, 'ASSOC');
  3601. $current_date = date('Y-m-d H:i:s');
  3602. if ($row['count'] == 0) {
  3603. $sql_i = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)values('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'");';
  3604. Database::query($sql_i);
  3605. return true;
  3606. } else {
  3607. $sql = 'SELECT COUNT(*) as count, relation_type FROM '.$tbl_my_friend.' WHERE friend_user_id='.$friend_id.' AND user_id='.$my_user_id.' AND relation_type <> '.USER_RELATION_TYPE_RRHH.' ';
  3608. $result = Database::query($sql);
  3609. $row = Database :: fetch_array($result, 'ASSOC');
  3610. if ($row['count'] == 1) {
  3611. //only for the case of a RRHH
  3612. if ($row['relation_type'] != $relation_type && $relation_type == USER_RELATION_TYPE_RRHH) {
  3613. $sql_i = 'INSERT INTO '.$tbl_my_friend.'(friend_user_id,user_id,relation_type,last_edit)values('.$friend_id.','.$my_user_id.','.$relation_type.',"'.$current_date.'");';
  3614. } else {
  3615. $sql_i = 'UPDATE '.$tbl_my_friend.' SET relation_type='.$relation_type.' WHERE friend_user_id='.$friend_id.' AND user_id='.$my_user_id;
  3616. }
  3617. Database::query($sql_i);
  3618. return true;
  3619. } else {
  3620. return false;
  3621. }
  3622. }
  3623. }
  3624. /**
  3625. * Deletes a contact
  3626. * @param int user friend id
  3627. * @param bool true will delete ALL friends relationship from $friend_id
  3628. * @author isaac flores paz <isaac.flores@dokeos.com>
  3629. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  3630. */
  3631. public static function remove_user_rel_user($friend_id, $real_removed = false, $with_status_condition = '')
  3632. {
  3633. $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
  3634. $tbl_my_message = Database :: get_main_table(TABLE_MAIN_MESSAGE);
  3635. $friend_id = intval($friend_id);
  3636. if ($real_removed) {
  3637. //Delete user friend
  3638. /*
  3639. $sql_delete_relationship1 = 'UPDATE ' . $tbl_my_friend .' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE friend_user_id='.$friend_id;
  3640. $sql_delete_relationship2 = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id;
  3641. Database::query($sql_delete_relationship1);
  3642. Database::query($sql_delete_relationship2); */
  3643. $extra_condition = '';
  3644. if ($with_status_condition != '') {
  3645. $extra_condition = ' AND relation_type = '.intval($with_status_condition);
  3646. }
  3647. $sql_delete_relationship1 = 'DELETE FROM '.$tbl_my_friend.' WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND friend_user_id='.$friend_id.' '.$extra_condition;
  3648. $sql_delete_relationship2 = 'DELETE FROM '.$tbl_my_friend.' WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND user_id='.$friend_id.' '.$extra_condition;
  3649. Database::query($sql_delete_relationship1);
  3650. Database::query($sql_delete_relationship2);
  3651. } else {
  3652. $user_id = api_get_user_id();
  3653. $sql = 'SELECT COUNT(*) as count FROM '.$tbl_my_friend.' WHERE user_id='.$user_id.' AND relation_type NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND friend_user_id='.$friend_id;
  3654. $result = Database::query($sql);
  3655. $row = Database :: fetch_array($result, 'ASSOC');
  3656. if ($row['count'] == 1) {
  3657. //Delete user rel user
  3658. $sql_i = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
  3659. $sql_j = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.' WHERE user_receiver_id='.$user_id.' AND user_sender_id='.$friend_id.' AND update_date="0000-00-00 00:00:00" ';
  3660. //Delete user
  3661. $sql_ij = 'UPDATE '.$tbl_my_friend.' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id='.$friend_id.' AND friend_user_id='.$user_id;
  3662. $sql_ji = 'UPDATE '.$tbl_my_message.' SET msg_status='.MESSAGE_STATUS_INVITATION_DENIED.' WHERE user_receiver_id='.$friend_id.' AND user_sender_id='.$user_id.' AND update_date="0000-00-00 00:00:00" ';
  3663. Database::query($sql_i);
  3664. Database::query($sql_j);
  3665. Database::query($sql_ij);
  3666. Database::query($sql_ji);
  3667. }
  3668. }
  3669. }
  3670. /**
  3671. * @param int $userId
  3672. * @return array
  3673. */
  3674. public static function getDrhListFromUser($userId)
  3675. {
  3676. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  3677. $tblUserRelUser = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3678. $tblUserRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3679. $userId = intval($userId);
  3680. $orderBy = null;
  3681. if (api_is_western_name_order()) {
  3682. $orderBy .= " ORDER BY firstname, lastname ";
  3683. } else {
  3684. $orderBy .= " ORDER BY lastname, firstname ";
  3685. }
  3686. $sql = "SELECT u.user_id, username, u.firstname, u.lastname
  3687. FROM $tblUser u
  3688. INNER JOIN $tblUserRelUser uru ON (uru.friend_user_id = u.user_id)
  3689. INNER JOIN $tblUserRelAccessUrl a ON (a.user_id = u.user_id)
  3690. WHERE
  3691. access_url_id = ".api_get_current_access_url_id()." AND
  3692. uru.user_id = '$userId' AND
  3693. relation_type = '".USER_RELATION_TYPE_RRHH."'
  3694. $orderBy
  3695. ";
  3696. $result = Database::query($sql);
  3697. return Database::store_result($result);
  3698. }
  3699. /**
  3700. * get users followed by human resource manager
  3701. * @param int $userId
  3702. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  3703. * @param bool $getOnlyUserId
  3704. * @param bool $getSql
  3705. * @param bool $getCount
  3706. * @param int $from
  3707. * @param int $numberItems
  3708. * @param int $column
  3709. * @param string $direction
  3710. * @param int $active
  3711. * @param string $lastConnectionDate
  3712. * @return array users
  3713. */
  3714. public static function get_users_followed_by_drh(
  3715. $userId,
  3716. $userStatus = 0,
  3717. $getOnlyUserId = false,
  3718. $getSql = false,
  3719. $getCount = false,
  3720. $from = null,
  3721. $numberItems = null,
  3722. $column = null,
  3723. $direction = null,
  3724. $active = null,
  3725. $lastConnectionDate = null
  3726. ) {
  3727. return self::getUsersFollowedByUser(
  3728. $userId,
  3729. $userStatus,
  3730. $getOnlyUserId,
  3731. $getSql,
  3732. $getCount,
  3733. $from,
  3734. $numberItems,
  3735. $column,
  3736. $direction,
  3737. $active,
  3738. $lastConnectionDate,
  3739. DRH
  3740. );
  3741. }
  3742. /**
  3743. * Get users followed by human resource manager
  3744. * @param int $userId
  3745. * @param int $userStatus Filter users by status (STUDENT, COURSEMANAGER, etc)
  3746. * @param bool $getOnlyUserId
  3747. * @param bool $getSql
  3748. * @param bool $getCount
  3749. * @param int $from
  3750. * @param int $numberItems
  3751. * @param int $column
  3752. * @param string $direction
  3753. * @param int $active
  3754. * @param string $lastConnectionDate
  3755. * @param int $status the function is called by who? COURSEMANAGER, DRH?
  3756. * @param string $keyword
  3757. *
  3758. * @return array user list
  3759. */
  3760. public static function getUsersFollowedByUser(
  3761. $userId,
  3762. $userStatus = null,
  3763. $getOnlyUserId = false,
  3764. $getSql = false,
  3765. $getCount = false,
  3766. $from = null,
  3767. $numberItems = null,
  3768. $column = null,
  3769. $direction = null,
  3770. $active = null,
  3771. $lastConnectionDate = null,
  3772. $status = null,
  3773. $keyword = null
  3774. ) {
  3775. // Database Table Definitions
  3776. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3777. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3778. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3779. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3780. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3781. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3782. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3783. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3784. $userId = intval($userId);
  3785. $limitCondition = null;
  3786. if (isset($from) && isset($numberItems)) {
  3787. $from = intval($from);
  3788. $numberItems = intval($numberItems);
  3789. $limitCondition = "LIMIT $from, $numberItems";
  3790. }
  3791. $column = Database::escape_string($column);
  3792. $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : null;
  3793. $userConditions = '';
  3794. if (!empty($userStatus)) {
  3795. $userConditions .= ' AND u.status = '.intval($userStatus);
  3796. }
  3797. $select = " SELECT DISTINCT u.user_id, u.username, u.lastname, u.firstname, u.email ";
  3798. if ($getOnlyUserId) {
  3799. $select = " SELECT DISTINCT u.user_id";
  3800. }
  3801. $masterSelect = "SELECT DISTINCT * FROM ";
  3802. if ($getCount) {
  3803. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  3804. $select = " SELECT DISTINCT(u.user_id) ";
  3805. }
  3806. if (!is_null($active)) {
  3807. $active = intval($active);
  3808. $userConditions .= " AND u.active = $active ";
  3809. }
  3810. if (!empty($keyword)) {
  3811. $keyword = Database::escape_string($keyword);
  3812. $userConditions .= " AND (
  3813. u.username LIKE '%$keyword%' OR
  3814. u.firstname LIKE '%$keyword%' OR
  3815. u.lastname LIKE '%$keyword%' OR
  3816. u.official_code LIKE '%$keyword%' OR
  3817. u.email LIKE '%$keyword%'
  3818. )";
  3819. }
  3820. if (!empty($lastConnectionDate)) {
  3821. if (isset($_configuration['save_user_last_login']) &&
  3822. $_configuration['save_user_last_login']
  3823. ) {
  3824. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  3825. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  3826. }
  3827. }
  3828. $courseConditions = null;
  3829. $sessionConditionsCoach = null;
  3830. $sessionConditionsTeacher = null;
  3831. $drhConditions = null;
  3832. $teacherSelect = null;
  3833. switch($status) {
  3834. case DRH:
  3835. $drhConditions .= " AND
  3836. friend_user_id = '$userId' AND
  3837. relation_type = '".USER_RELATION_TYPE_RRHH."'
  3838. ";
  3839. break;
  3840. case COURSEMANAGER:
  3841. $drhConditions .= " AND
  3842. friend_user_id = '$userId' AND
  3843. relation_type = '".USER_RELATION_TYPE_RRHH."'
  3844. ";
  3845. $sessionConditionsCoach .= " AND
  3846. (s.id_coach = '$userId')
  3847. ";
  3848. $sessionConditionsTeacher .= " AND
  3849. (scu.status = 2 AND scu.id_user = '$userId')
  3850. ";
  3851. $teacherSelect =
  3852. "UNION ALL (
  3853. $select
  3854. FROM $tbl_user u
  3855. INNER JOIN $tbl_session_rel_user sru ON (sru.id_user = u.user_id)
  3856. WHERE
  3857. sru.id_session IN (
  3858. SELECT DISTINCT(s.id) FROM $tbl_session s INNER JOIN
  3859. $tbl_session_rel_access_url
  3860. WHERE access_url_id = ".api_get_current_access_url_id()."
  3861. $sessionConditionsCoach
  3862. UNION (
  3863. SELECT DISTINCT(s.id) FROM $tbl_session s
  3864. INNER JOIN $tbl_session_rel_access_url url
  3865. ON (url.session_id = s.id)
  3866. INNER JOIN $tbl_session_rel_course_rel_user scu
  3867. ON (scu.id_session = s.id)
  3868. WHERE access_url_id = ".api_get_current_access_url_id()."
  3869. $sessionConditionsTeacher
  3870. )
  3871. )
  3872. $userConditions
  3873. )
  3874. UNION ALL(
  3875. $select
  3876. FROM $tbl_user u
  3877. INNER JOIN $tbl_course_user cu ON (cu.user_id = u.user_id)
  3878. WHERE cu.course_code IN (
  3879. SELECT DISTINCT(course_code) FROM $tbl_course_user
  3880. WHERE user_id = $userId AND status = ".COURSEMANAGER."
  3881. )
  3882. $userConditions
  3883. )"
  3884. ;
  3885. break;
  3886. case STUDENT_BOSS :
  3887. $drhConditions = " AND friend_user_id = $userId AND "
  3888. . "relation_type = " . USER_RELATION_TYPE_BOSS;
  3889. break;
  3890. }
  3891. $join = null;
  3892. $sql = " $masterSelect
  3893. (
  3894. (
  3895. $select
  3896. FROM $tbl_user u
  3897. INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id)
  3898. LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.user_id)
  3899. $join
  3900. WHERE
  3901. access_url_id = ".api_get_current_access_url_id()."
  3902. $drhConditions
  3903. $userConditions
  3904. )
  3905. $teacherSelect
  3906. ) as t1";
  3907. if ($getSql) {
  3908. return $sql;
  3909. }
  3910. if ($getCount) {
  3911. $result = Database::query($sql);
  3912. $row = Database::fetch_array($result);
  3913. return $row['count'];
  3914. }
  3915. $orderBy = null;
  3916. if (api_is_western_name_order()) {
  3917. $orderBy .= " ORDER BY firstname, lastname ";
  3918. } else {
  3919. $orderBy .= " ORDER BY lastname, firstname ";
  3920. }
  3921. if (!empty($column) && !empty($direction)) {
  3922. // Fixing order due the UNIONs
  3923. $column = str_replace('u.', '', $column);
  3924. $orderBy = " ORDER BY $column $direction ";
  3925. }
  3926. $sql .= $orderBy;
  3927. $sql .= $limitCondition;
  3928. $result = Database::query($sql);
  3929. $users = array();
  3930. if (Database::num_rows($result) > 0) {
  3931. while ($row = Database::fetch_array($result)) {
  3932. $users[$row['user_id']] = $row;
  3933. }
  3934. }
  3935. return $users;
  3936. }
  3937. /**
  3938. * Subscribes users to human resource manager (Dashboard feature)
  3939. * @param int hr dept id
  3940. * @param array Users id
  3941. * @param int affected rows
  3942. * */
  3943. public static function suscribe_users_to_hr_manager($hr_dept_id, $users_id)
  3944. {
  3945. return self::subscribeUsersToUser($hr_dept_id, $users_id, USER_RELATION_TYPE_RRHH);
  3946. }
  3947. /**
  3948. * Add subscribed users to a user by relation type
  3949. * @param int $userId The user id
  3950. * @param array $subscribedUsersId The id of suscribed users
  3951. * @param action $relationType The relation type
  3952. */
  3953. public static function subscribeUsersToUser($userId, $subscribedUsersId, $relationType)
  3954. {
  3955. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  3956. $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3957. $userId = intval($userId);
  3958. $relationType = intval($relationType);
  3959. $affectedRows = 0;
  3960. if (api_get_multiple_access_url()) {
  3961. //Deleting assigned users to hrm_id
  3962. $sql = "SELECT s.user_id FROM $userRelUserTable s "
  3963. . "INNER JOIN $userRelAccessUrlTable a ON (a.user_id = s.user_id) "
  3964. . "WHERE friend_user_id = $userId "
  3965. . "AND relation_type = $relationType "
  3966. . "AND access_url_id = " . api_get_current_access_url_id() . "";
  3967. } else {
  3968. $sql = "SELECT user_id FROM $userRelUserTable "
  3969. . "WHERE friend_user_id = $userId "
  3970. . "AND relation_type = $relationType";
  3971. }
  3972. $result = Database::query($sql);
  3973. if (Database::num_rows($result) > 0) {
  3974. while ($row = Database::fetch_array($result)) {
  3975. $sql = "DELETE FROM $userRelUserTable "
  3976. . "WHERE user_id = {$row['user_id']} "
  3977. . "AND friend_user_id = $userId "
  3978. . "AND relation_type = $relationType";
  3979. Database::query($sql);
  3980. }
  3981. }
  3982. // Inserting new user list
  3983. if (is_array($subscribedUsersId)) {
  3984. foreach ($subscribedUsersId as $subscribedUserId) {
  3985. $subscribedUserId = intval($subscribedUserId);
  3986. $sql = "INSERT IGNORE INTO $userRelUserTable(user_id, friend_user_id, relation_type) "
  3987. . "VALUES ($subscribedUserId, $userId, $relationType)";
  3988. Database::query($sql);
  3989. $affectedRows = Database::affected_rows();
  3990. }
  3991. }
  3992. return $affectedRows;
  3993. }
  3994. /**
  3995. * This function check if an user is followed by human resources manager
  3996. * @param int User id
  3997. * @param int Human resources manager
  3998. * @return bool
  3999. */
  4000. public static function is_user_followed_by_drh($user_id, $hr_dept_id)
  4001. {
  4002. // Database table and variables Definitions
  4003. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  4004. $user_id = intval($user_id);
  4005. $hr_dept_id = intval($hr_dept_id);
  4006. $result = false;
  4007. $sql = "SELECT user_id FROM $tbl_user_rel_user
  4008. WHERE
  4009. user_id='$user_id' AND
  4010. friend_user_id='$hr_dept_id' AND
  4011. relation_type = ".USER_RELATION_TYPE_RRHH;
  4012. $rs = Database::query($sql);
  4013. if (Database::num_rows($rs) > 0) {
  4014. $result = true;
  4015. }
  4016. return $result;
  4017. }
  4018. /**
  4019. * get user id of teacher or session administrator
  4020. * @param string The course id
  4021. * @return int The user id
  4022. */
  4023. public static function get_user_id_of_course_admin_or_session_admin($course_id)
  4024. {
  4025. $session = api_get_session_id();
  4026. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4027. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4028. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4029. if ($session == 0 || is_null($session)) {
  4030. $sql = 'SELECT u.user_id FROM '.$table_user.' u
  4031. INNER JOIN '.$table_course_user.' ru ON ru.user_id=u.user_id
  4032. WHERE
  4033. ru.status = 1 AND
  4034. ru.course_code = "'.Database::escape_string($course_id).'" ';
  4035. $rs = Database::query($sql);
  4036. $num_rows = Database::num_rows($rs);
  4037. if ($num_rows == 1) {
  4038. $row = Database::fetch_array($rs);
  4039. return $row['user_id'];
  4040. } else {
  4041. $my_num_rows = $num_rows;
  4042. $my_user_id = Database::result($rs, $my_num_rows - 1, 'user_id');
  4043. return $my_user_id;
  4044. }
  4045. } elseif ($session > 0) {
  4046. $sql = 'SELECT u.user_id FROM '.$table_user.' u
  4047. INNER JOIN '.$table_session_course_user.' sru
  4048. ON sru.id_user=u.user_id
  4049. WHERE
  4050. sru.course_code="'.Database::escape_string($course_id).'" AND
  4051. sru.status=2';
  4052. $rs = Database::query($sql);
  4053. $row = Database::fetch_array($rs);
  4054. return $row['user_id'];
  4055. }
  4056. }
  4057. /**
  4058. * Determines if a user is a gradebook certified
  4059. * @param int The category id of gradebook
  4060. * @param int The user id
  4061. * @return boolean
  4062. */
  4063. public static function is_user_certified($cat_id, $user_id)
  4064. {
  4065. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4066. $sql = 'SELECT path_certificate FROM '.$table_certificate.'
  4067. WHERE
  4068. cat_id="'.intval($cat_id).'" AND
  4069. user_id="'.intval($user_id).'"';
  4070. $rs = Database::query($sql);
  4071. $row = Database::fetch_array($rs);
  4072. if ($row['path_certificate'] == '' || is_null($row['path_certificate'])) {
  4073. return false;
  4074. } else {
  4075. return true;
  4076. }
  4077. }
  4078. /**
  4079. * Gets the info about a gradebook certificate for a user by course
  4080. * @param string The course code
  4081. * @param int The user id
  4082. * @return array if there is not information return false
  4083. */
  4084. public static function get_info_gradebook_certificate($course_code, $user_id)
  4085. {
  4086. $tbl_grade_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4087. $tbl_grade_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  4088. $session_id = api_get_session_id();
  4089. if (empty($session_id)) {
  4090. $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
  4091. } else {
  4092. $session_condition = " AND session_id = $session_id";
  4093. }
  4094. // Getting gradebook score.
  4095. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
  4096. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
  4097. $sql = 'SELECT * FROM '.$tbl_grade_certificate.' WHERE cat_id = (SELECT id FROM '.$tbl_grade_category.'
  4098. WHERE
  4099. course_code = "'.Database::escape_string($course_code).'" '.$session_condition.' LIMIT 1 ) AND
  4100. user_id='.intval($user_id);
  4101. $rs = Database::query($sql);
  4102. if (Database::num_rows($rs) > 0) {
  4103. $row = Database::fetch_array($rs, 'ASSOC');
  4104. $score = $row['score_certificate'];
  4105. $category_id = $row['cat_id'];
  4106. $cat = Category::load($category_id);
  4107. $displayscore = ScoreDisplay::instance();
  4108. if (isset($cat) && $displayscore->is_custom()) {
  4109. $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()), SCORE_DIV_PERCENT_WITH_CUSTOM);
  4110. } else {
  4111. $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()));
  4112. }
  4113. $row['grade'] = $grade;
  4114. return $row;
  4115. }
  4116. return false;
  4117. }
  4118. /**
  4119. * Gets the user path of user certificated
  4120. * @param int The user id
  4121. * @return array containing path_certificate and cat_id
  4122. */
  4123. public static function get_user_path_certificate($user_id)
  4124. {
  4125. $my_certificate = array();
  4126. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  4127. $table_gradebook_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  4128. $session_id = api_get_session_id();
  4129. $user_id = intval($user_id);
  4130. if ($session_id == 0 || is_null($session_id)) {
  4131. $sql_session = 'AND (session_id='.intval($session_id).' OR isnull(session_id)) ';
  4132. } elseif ($session_id > 0) {
  4133. $sql_session = 'AND session_id='.intval($session_id);
  4134. } else {
  4135. $sql_session = '';
  4136. }
  4137. $sql = "SELECT tc.path_certificate,tc.cat_id,tgc.course_code,tgc.name
  4138. FROM $table_certificate tc, $table_gradebook_category tgc
  4139. WHERE tgc.id = tc.cat_id AND tc.user_id='$user_id'
  4140. ORDER BY tc.date_certificate DESC limit 5";
  4141. $rs = Database::query($sql);
  4142. while ($row = Database::fetch_array($rs)) {
  4143. $my_certificate[] = $row;
  4144. }
  4145. return $my_certificate;
  4146. }
  4147. /**
  4148. * This function check if the user is a coach inside session course
  4149. * @param int User id
  4150. * @param string Course code
  4151. * @param int Session id
  4152. * @return bool True if the user is a coach
  4153. *
  4154. */
  4155. public static function is_session_course_coach($user_id, $course_code, $session_id)
  4156. {
  4157. $tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4158. // Protect data
  4159. $user_id = intval($user_id);
  4160. $course_code = Database::escape_string($course_code);
  4161. $session_id = intval($session_id);
  4162. $result = false;
  4163. $sql = "SELECT id_session FROM $tbl_session_course_rel_user
  4164. WHERE
  4165. id_session=$session_id AND
  4166. course_code='$course_code' AND
  4167. id_user = $user_id AND
  4168. status = 2 ";
  4169. $res = Database::query($sql);
  4170. if (Database::num_rows($res) > 0) {
  4171. $result = true;
  4172. }
  4173. return $result;
  4174. }
  4175. /**
  4176. * This function returns an icon path that represents the favicon of the website of which the url given.
  4177. * Defaults to the current Chamilo favicon
  4178. * @param string URL of website where to look for favicon.ico
  4179. * @param string Optional second URL of website where to look for favicon.ico
  4180. * @return string Path of icon to load
  4181. */
  4182. public static function get_favicon_from_url($url1, $url2 = null)
  4183. {
  4184. $icon_link = '';
  4185. $url = $url1;
  4186. if (empty($url1)) {
  4187. $url = $url2;
  4188. if (empty($url)) {
  4189. $url = api_get_access_url(api_get_current_access_url_id());
  4190. $url = $url[0];
  4191. }
  4192. }
  4193. if (!empty($url)) {
  4194. $pieces = parse_url($url);
  4195. $icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
  4196. }
  4197. return $icon_link;
  4198. }
  4199. /**
  4200. *
  4201. * @param int student id
  4202. * @param int years
  4203. * @param bool show warning_message
  4204. * @param bool return_timestamp
  4205. */
  4206. public static function delete_inactive_student($student_id, $years = 2, $warning_message = false, $return_timestamp = false)
  4207. {
  4208. $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  4209. $sql = 'SELECT login_date FROM '.$tbl_track_login.'
  4210. WHERE login_user_id = '.intval($student_id).'
  4211. ORDER BY login_date DESC LIMIT 0,1';
  4212. if (empty($years)) {
  4213. $years = 1;
  4214. }
  4215. $inactive_time = $years * 31536000; //1 year
  4216. $rs = Database::query($sql);
  4217. if (Database::num_rows($rs) > 0) {
  4218. if ($last_login_date = Database::result($rs, 0, 0)) {
  4219. $last_login_date = api_get_local_time($last_login_date, null, date_default_timezone_get());
  4220. if ($return_timestamp) {
  4221. return api_strtotime($last_login_date);
  4222. } else {
  4223. if (!$warning_message) {
  4224. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  4225. } else {
  4226. $timestamp = api_strtotime($last_login_date);
  4227. $currentTimestamp = time();
  4228. //If the last connection is > than 7 days, the text is red
  4229. //345600 = 7 days in seconds 63072000= 2 ans
  4230. // if ($currentTimestamp - $timestamp > 184590 )
  4231. if ($currentTimestamp - $timestamp > $inactive_time && UserManager::delete_user($student_id)) {
  4232. Display :: display_normal_message(get_lang('UserDeleted'));
  4233. echo '<p>', 'id', $student_id, ':', $last_login_date, '</p>';
  4234. }
  4235. }
  4236. }
  4237. }
  4238. }
  4239. return false;
  4240. }
  4241. /**
  4242. * @param FormValidator $form
  4243. * @param $extra_data
  4244. * @param $form_name
  4245. * @param bool $admin_permissions
  4246. * @param null $user_id
  4247. * @return array
  4248. */
  4249. static function set_extra_fields_in_form($form, $extra_data, $form_name, $admin_permissions = false, $user_id = null)
  4250. {
  4251. $user_id = intval($user_id);
  4252. // EXTRA FIELDS
  4253. $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  4254. $jquery_ready_content = null;
  4255. foreach ($extra as $field_details) {
  4256. if (!$admin_permissions) {
  4257. if ($field_details[6] == 0) {
  4258. continue;
  4259. }
  4260. }
  4261. switch ($field_details[2]) {
  4262. case self::USER_FIELD_TYPE_TEXT:
  4263. $form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
  4264. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  4265. $form->applyFilter('extra_'.$field_details[1], 'trim');
  4266. $form->applyFilter('extra_'.$field_details[1], 'html_filter');
  4267. if (!$admin_permissions) {
  4268. if ($field_details[7] == 0) {
  4269. $form->freeze('extra_'.$field_details[1]);
  4270. }
  4271. }
  4272. break;
  4273. case self::USER_FIELD_TYPE_TEXTAREA:
  4274. $form->add_html_editor(
  4275. 'extra_'.$field_details[1],
  4276. $field_details[3],
  4277. false,
  4278. false,
  4279. array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')
  4280. );
  4281. //$form->addElement('textarea', 'extra_'.$field_details[1], $field_details[3], array('size' => 80));
  4282. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  4283. $form->applyFilter('extra_'.$field_details[1], 'trim');
  4284. if (!$admin_permissions) {
  4285. if ($field_details[7] == 0)
  4286. $form->freeze('extra_'.$field_details[1]);
  4287. }
  4288. break;
  4289. case self::USER_FIELD_TYPE_RADIO:
  4290. $group = array();
  4291. foreach ($field_details[9] as $option_id => $option_details) {
  4292. $options[$option_details[1]] = $option_details[2];
  4293. $group[] = $form->createElement(
  4294. 'radio',
  4295. 'extra_'.$field_details[1],
  4296. $option_details[1],
  4297. $option_details[2].'<br />',
  4298. $option_details[1]
  4299. );
  4300. }
  4301. $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
  4302. if (!$admin_permissions) {
  4303. if ($field_details[7] == 0)
  4304. $form->freeze('extra_'.$field_details[1]);
  4305. }
  4306. break;
  4307. case self::USER_FIELD_TYPE_SELECT:
  4308. $get_lang_variables = false;
  4309. if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
  4310. $get_lang_variables = true;
  4311. }
  4312. $options = array();
  4313. foreach ($field_details[9] as $option_id => $option_details) {
  4314. //$options[$option_details[1]] = $option_details[2];
  4315. if ($get_lang_variables) {
  4316. $options[$option_details[1]] = get_lang($option_details[2]);
  4317. } else {
  4318. $options[$option_details[1]] = $option_details[2];
  4319. }
  4320. }
  4321. if ($get_lang_variables) {
  4322. $field_details[3] = get_lang($field_details[3]);
  4323. }
  4324. $form->addElement(
  4325. 'select',
  4326. 'extra_'.$field_details[1],
  4327. $field_details[3],
  4328. $options,
  4329. array('class' => 'chzn-select', 'id' => 'extra_'.$field_details[1])
  4330. );
  4331. if (!$admin_permissions) {
  4332. if ($field_details[7] == 0)
  4333. $form->freeze('extra_'.$field_details[1]);
  4334. }
  4335. break;
  4336. case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
  4337. $options = array();
  4338. foreach ($field_details[9] as $option_id => $option_details) {
  4339. $options[$option_details[1]] = $option_details[2];
  4340. }
  4341. $form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
  4342. if (!$admin_permissions) {
  4343. if ($field_details[7] == 0)
  4344. $form->freeze('extra_'.$field_details[1]);
  4345. }
  4346. break;
  4347. case self::USER_FIELD_TYPE_DATE:
  4348. $form->addElement('date_picker', 'extra_'.$field_details[1], $field_details[3]);
  4349. //$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
  4350. $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
  4351. $form->setDefaults($defaults);
  4352. if (!$admin_permissions) {
  4353. if ($field_details[7] == 0)
  4354. $form->freeze('extra_'.$field_details[1]);
  4355. }
  4356. $form->applyFilter('theme', 'trim');
  4357. break;
  4358. case self::USER_FIELD_TYPE_DATETIME:
  4359. $form->addElement('date_time_picker', 'extra_'.$field_details[1], $field_details[3]);
  4360. //$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
  4361. $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
  4362. $form->setDefaults($defaults);
  4363. if (!$admin_permissions) {
  4364. if ($field_details[7] == 0)
  4365. $form->freeze('extra_'.$field_details[1]);
  4366. }
  4367. $form->applyFilter('theme', 'trim');
  4368. break;
  4369. case self::USER_FIELD_TYPE_DOUBLE_SELECT:
  4370. foreach ($field_details[9] as $key => $element) {
  4371. if ($element[2][0] == '*') {
  4372. $values['*'][$element[0]] = str_replace('*', '', $element[2]);
  4373. } else {
  4374. $values[0][$element[0]] = $element[2];
  4375. }
  4376. }
  4377. $group = '';
  4378. $group[] = & HTML_QuickForm::createElement('select', 'extra_'.$field_details[1], '', $values[0], '');
  4379. $group[] = & HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*', '', $values['*'], '');
  4380. $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
  4381. if (!$admin_permissions) {
  4382. if ($field_details[7] == 0)
  4383. $form->freeze('extra_'.$field_details[1]);
  4384. }
  4385. /* Recoding the selected values for double : if the user has
  4386. selected certain values, we have to assign them to the
  4387. correct select form */
  4388. if (array_key_exists('extra_'.$field_details[1], $extra_data)) {
  4389. // exploding all the selected values (of both select forms)
  4390. $selected_values = explode(';', $extra_data['extra_'.$field_details[1]]);
  4391. $extra_data['extra_'.$field_details[1]] = array();
  4392. // looping through the selected values and assigning the selected values to either the first or second select form
  4393. foreach ($selected_values as $key => $selected_value) {
  4394. if (array_key_exists($selected_value, $values[0])) {
  4395. $extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
  4396. } else {
  4397. $extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
  4398. }
  4399. }
  4400. }
  4401. break;
  4402. case self::USER_FIELD_TYPE_DIVIDER:
  4403. $form->addElement('static', $field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
  4404. break;
  4405. case self::USER_FIELD_TYPE_TAG:
  4406. //the magic should be here
  4407. $user_tags = UserManager::get_user_tags($user_id, $field_details[0]);
  4408. $tag_list = '';
  4409. if (is_array($user_tags) && count($user_tags) > 0) {
  4410. foreach ($user_tags as $tag) {
  4411. $tag_list .= '<option value="'.$tag['tag'].'" class="selected">'.$tag['tag'].'</option>';
  4412. }
  4413. }
  4414. $multi_select = '<select id="extra_'.$field_details[1].'" name="extra_'.$field_details[1].'">
  4415. '.$tag_list.'
  4416. </select>';
  4417. $form->addElement('label', $field_details[3], $multi_select);
  4418. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
  4419. $complete_text = get_lang('StartToType');
  4420. //if cache is set to true the jquery will be called 1 time
  4421. $jquery_ready_content = <<<EOF
  4422. $("#extra_$field_details[1]").fcbkcomplete({
  4423. json_url: "$url?a=search_tags&field_id=$field_details[0]",
  4424. cache: false,
  4425. filter_case: true,
  4426. filter_hide: true,
  4427. complete_text:"$complete_text",
  4428. firstselected: true,
  4429. //onremove: "testme",
  4430. //onselect: "testme",
  4431. filter_selected: true,
  4432. newel: true
  4433. });
  4434. EOF;
  4435. break;
  4436. case self::USER_FIELD_TYPE_TIMEZONE:
  4437. $form->addElement('select', 'extra_'.$field_details[1], $field_details[3], api_get_timezones(), '');
  4438. if ($field_details[7] == 0)
  4439. $form->freeze('extra_'.$field_details[1]);
  4440. break;
  4441. case self::USER_FIELD_TYPE_SOCIAL_PROFILE:
  4442. // get the social network's favicon
  4443. $icon_path = UserManager::get_favicon_from_url($extra_data['extra_'.$field_details[1]], $field_details[4]);
  4444. // special hack for hi5
  4445. $leftpad = '1.7';
  4446. $top = '0.4';
  4447. $domain = parse_url($icon_path, PHP_URL_HOST);
  4448. if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
  4449. $leftpad = '3';
  4450. $top = '0';
  4451. }
  4452. // print the input field
  4453. $form->addElement(
  4454. 'text',
  4455. 'extra_'.$field_details[1],
  4456. $field_details[3],
  4457. array(
  4458. 'size' => 60,
  4459. 'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '
  4460. )
  4461. );
  4462. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  4463. $form->applyFilter('extra_'.$field_details[1], 'trim');
  4464. if ($field_details[7] == 0)
  4465. $form->freeze('extra_'.$field_details[1]);
  4466. break;
  4467. case self::USER_FIELD_TYPE_FILE:
  4468. $extra_field = 'extra_'.$field_details[1];
  4469. $form->addElement('file', $extra_field, $field_details[3], null, '');
  4470. if ($extra_file_list = UserManager::build_user_extra_file_list($user_id, $field_details[1], '', true)) {
  4471. $form->addElement('static', $extra_field . '_list', null, $extra_file_list);
  4472. }
  4473. if ($field_details[7] == 0) {
  4474. $form->freeze($extra_field);
  4475. }
  4476. break;
  4477. case self::USER_FIELD_TYPE_MOBILE_PHONE_NUMBER:
  4478. $form->addElement(
  4479. 'text',
  4480. 'extra_'.$field_details[1],
  4481. $field_details[3]." (".get_lang('CountryDialCode').")",
  4482. array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')
  4483. );
  4484. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  4485. $form->applyFilter('extra_'.$field_details[1], 'trim');
  4486. $form->applyFilter('extra_'.$field_details[1], 'mobile_phone_number_filter');
  4487. $form->addRule(
  4488. 'extra_'.$field_details[1],
  4489. get_lang('MobilePhoneNumberWrong'),
  4490. 'mobile_phone_number'
  4491. );
  4492. if (!$admin_permissions) {
  4493. if ($field_details[7] == 0) {
  4494. $form->freeze('extra_'.$field_details[1]);
  4495. }
  4496. }
  4497. break;
  4498. }
  4499. }
  4500. $return = array();
  4501. $return['jquery_ready_content'] = $jquery_ready_content;
  4502. return $return;
  4503. }
  4504. /**
  4505. * @return array
  4506. */
  4507. static function get_user_field_types()
  4508. {
  4509. $types = array();
  4510. $types[self::USER_FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
  4511. $types[self::USER_FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
  4512. $types[self::USER_FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
  4513. $types[self::USER_FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
  4514. $types[self::USER_FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
  4515. $types[self::USER_FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
  4516. $types[self::USER_FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
  4517. $types[self::USER_FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
  4518. $types[self::USER_FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
  4519. $types[self::USER_FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
  4520. $types[self::USER_FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
  4521. $types[self::USER_FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
  4522. $types[self::USER_FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
  4523. $types[self::USER_FIELD_TYPE_MOBILE_PHONE_NUMBER] = get_lang('FieldTypeMobilePhoneNumber');
  4524. return $types;
  4525. }
  4526. /**
  4527. * @param int $user_id
  4528. */
  4529. static function add_user_as_admin($user_id)
  4530. {
  4531. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  4532. $user_id = intval($user_id);
  4533. if (!self::is_admin($user_id)) {
  4534. $sql = "INSERT INTO $table_admin SET user_id = '".$user_id."'";
  4535. Database::query($sql);
  4536. }
  4537. }
  4538. /**
  4539. * @param int $user_id
  4540. */
  4541. public static function remove_user_admin($user_id)
  4542. {
  4543. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  4544. $user_id = intval($user_id);
  4545. if (self::is_admin($user_id)) {
  4546. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  4547. Database::query($sql);
  4548. }
  4549. }
  4550. /**
  4551. * @param string $from
  4552. * @param string $to
  4553. */
  4554. public static function update_all_user_languages($from, $to)
  4555. {
  4556. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  4557. $from = Database::escape_string($from);
  4558. $to = Database::escape_string($to);
  4559. if (!empty($to) && !empty($from)) {
  4560. $sql = "UPDATE $table_user SET language = '$to'
  4561. WHERE language = '$from'";
  4562. Database::query($sql);
  4563. }
  4564. }
  4565. /**
  4566. * Subscribe users to student boss
  4567. * @param int $bossId The boss id
  4568. * @param array $usersId The users array
  4569. * @return int Affected rows
  4570. */
  4571. public static function subscribeUsersToBoss($bossId, $usersId)
  4572. {
  4573. return self::subscribeUsersToUser($bossId, $usersId, USER_RELATION_TYPE_BOSS);
  4574. }
  4575. /**
  4576. * Get users followed by student boss
  4577. * @param int $userId
  4578. * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
  4579. * @param bool $getOnlyUserId
  4580. * @param bool $getSql
  4581. * @param bool $getCount
  4582. * @param int $from
  4583. * @param int $numberItems
  4584. * @param int $column
  4585. * @param string $direction
  4586. * @param int $active
  4587. * @param string $lastConnectionDate
  4588. * @return array users
  4589. */
  4590. public static function getUsersFollowedByStudentBoss(
  4591. $userId,
  4592. $userStatus = 0,
  4593. $getOnlyUserId = false,
  4594. $getSql = false,
  4595. $getCount = false,
  4596. $from = null,
  4597. $numberItems = null,
  4598. $column = null,
  4599. $direction = null,
  4600. $active = null,
  4601. $lastConnectionDate = null
  4602. ){
  4603. return self::getUsersFollowedByUser(
  4604. $userId, $userStatus, $getOnlyUserId, $getSql, $getCount, $from, $numberItems, $column, $direction,
  4605. $active, $lastConnectionDate, STUDENT_BOSS
  4606. );
  4607. }
  4608. /**
  4609. * Get the teacher (users with COURSEMANGER status) list
  4610. * @return array The list
  4611. */
  4612. public static function getTeachersList()
  4613. {
  4614. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  4615. $resultData = Database::select('user_id, lastname, firstname, username', $userTable, array(
  4616. 'where' => array(
  4617. 'status = ?' => COURSEMANAGER
  4618. )
  4619. ));
  4620. foreach ($resultData as &$teacherData) {
  4621. $teacherData['completeName'] = api_get_person_name($teacherData['firstname'], $teacherData['lastname']);
  4622. }
  4623. return $resultData;
  4624. }
  4625. /**
  4626. * @return array
  4627. */
  4628. public static function getOfficialCodeGrouped()
  4629. {
  4630. $user = Database::get_main_table(TABLE_MAIN_USER);
  4631. $sql = "SELECT DISTINCT official_code
  4632. FROM $user
  4633. GROUP BY official_code";
  4634. $result = Database::query($sql);
  4635. $values = Database::store_result($result, 'ASSOC');
  4636. $result = array();
  4637. foreach ($values as $value) {
  4638. $result[$value['official_code']] = $value['official_code'];
  4639. }
  4640. return $result;
  4641. }
  4642. /**
  4643. * @param string $officialCode
  4644. * @return array
  4645. */
  4646. public static function getUsersByOfficialCode($officialCode)
  4647. {
  4648. $user = Database::get_main_table(TABLE_MAIN_USER);
  4649. $officialCode = Database::escape_string($officialCode);
  4650. $sql = "SELECT DISTINCT user_id
  4651. FROM $user
  4652. WHERE official_code = '$officialCode'
  4653. ";
  4654. $result = Database::query($sql);
  4655. $users = array();
  4656. while ($row = Database::fetch_array($result)) {
  4657. $users[] = $row['user_id'];
  4658. }
  4659. return $users;
  4660. }
  4661. /**
  4662. * Calc the expended time (in seconds) by a user in a course
  4663. * @param int $userId The user id
  4664. * @param string $courseCode The course id
  4665. * @param int $sessionId Optional. The session id
  4666. * @param string $from Optional. From date
  4667. * @param string $until Optional. Until date
  4668. * @return int The time
  4669. */
  4670. public static function getExpendedTimeInCourses($userId, $courseCode, $sessionId = 0, $from = '', $until = '')
  4671. {
  4672. $userId = intval($userId);
  4673. $sessionId = intval($sessionId);
  4674. $trackCourseAccessTable = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  4675. $whereConditions = array(
  4676. 'user_id = ? ' => $userId,
  4677. "AND course_code = '?' " => $courseCode,
  4678. 'AND session_id = ? ' => $sessionId
  4679. );
  4680. if (!empty($from) && !empty($until)) {
  4681. $whereConditions["AND (login_course_date >= '?' "] = $from;
  4682. $whereConditions["AND logout_course_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
  4683. }
  4684. $trackResult = Database::select(
  4685. 'SUM(UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) as total_time',
  4686. $trackCourseAccessTable,
  4687. array(
  4688. 'where' => $whereConditions
  4689. ), 'first'
  4690. );
  4691. if ($trackResult != false) {
  4692. return $trackResult['total_time'] ? $trackResult['total_time'] : 0;
  4693. }
  4694. return 0;
  4695. }
  4696. }