usermanager.lib.php 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This library provides functions for user management.
  5. * Include/require it in your code to use its functionality.
  6. * @package chamilo.library
  7. * @author Julio Montoya <gugli100@gmail.com> Social network groups added 2009/12
  8. */
  9. /**
  10. * Code
  11. */
  12. /**
  13. * Class
  14. * @package chamilo.include.user
  15. */
  16. class UserManager {
  17. // Constants for user extra field types.
  18. CONST USER_FIELD_TYPE_TEXT = 1;
  19. CONST USER_FIELD_TYPE_TEXTAREA = 2;
  20. CONST USER_FIELD_TYPE_RADIO = 3;
  21. CONST USER_FIELD_TYPE_SELECT = 4;
  22. CONST USER_FIELD_TYPE_SELECT_MULTIPLE = 5;
  23. CONST USER_FIELD_TYPE_DATE = 6;
  24. CONST USER_FIELD_TYPE_DATETIME = 7;
  25. CONST USER_FIELD_TYPE_DOUBLE_SELECT = 8;
  26. CONST USER_FIELD_TYPE_DIVIDER = 9;
  27. CONST USER_FIELD_TYPE_TAG = 10;
  28. CONST USER_FIELD_TYPE_TIMEZONE = 11;
  29. CONST USER_FIELD_TYPE_SOCIAL_PROFILE = 12;
  30. private function __construct () {
  31. }
  32. /**
  33. * Creates a new user for the platform
  34. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
  35. * Roan Embrechts <roan_embrechts@yahoo.com>
  36. *
  37. * @param string Firstname
  38. * @param string Lastname
  39. * @param int Status (1 for course tutor, 5 for student, 6 for anonymous)
  40. * @param string e-mail address
  41. * @param string Login
  42. * @param string Password
  43. * @param string Any official code (optional)
  44. * @param string User language (optional)
  45. * @param string Phone number (optional)
  46. * @param string Picture URI (optional)
  47. * @param string Authentication source (optional, defaults to 'platform', dependind on constant)
  48. * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00')
  49. * @param int Whether the account is enabled or disabled by default
  50. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  51. * @param array Extra fields
  52. * @param string Encrypt method used if password is given encrypted. Set to an empty string by default
  53. * @return mixed new user id - if the new user creation succeeds, false otherwise
  54. *
  55. * @desc The function tries to retrieve $_user['user_id'] from the global space.
  56. * if it exists, $_user['user_id'] is the creator id. If a problem arises,
  57. * it stores the error message in global $api_failureList
  58. */
  59. public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false) {
  60. global $_user, $_configuration;
  61. $original_password = $password;
  62. $access_url_id = 1;
  63. if (api_get_multiple_access_url()) {
  64. $access_url_id = api_get_current_access_url_id();
  65. }
  66. if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
  67. $num = self::get_number_of_users();
  68. if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
  69. return api_set_failure('portal users limit reached');
  70. }
  71. }
  72. if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) {
  73. $num = self::get_number_of_users(1);
  74. if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
  75. return api_set_failure('portal teachers limit reached');
  76. }
  77. }
  78. $firstName = Security::remove_XSS($firstName);
  79. $lastName = Security::remove_XSS($lastName);
  80. $loginName = Security::remove_XSS($loginName);
  81. $phone = Security::remove_XSS($phone);
  82. // database table definition
  83. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  84. //Checking the user language
  85. $languages = api_get_languages();
  86. if (!in_array($language, $languages['folder'])) {
  87. $language = api_get_setting('platformLanguage');
  88. }
  89. if ($_user['user_id']) {
  90. $creator_id = intval($_user['user_id']);
  91. } else {
  92. $creator_id = '';
  93. }
  94. // First check wether the login already exists
  95. if (!self::is_username_available($loginName)) {
  96. return api_set_failure('login-pass already taken');
  97. }
  98. //$password = "PLACEHOLDER";
  99. if ($encrypt_method == '') {
  100. $password = api_get_encrypted_password($password);
  101. } else {
  102. if ($_configuration['password_encryption'] === $encrypt_method ) {
  103. if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
  104. return api_set_failure('encrypt_method invalid');
  105. } else if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
  106. return api_set_failure('encrypt_method invalid');
  107. }
  108. } else {
  109. return api_set_failure('encrypt_method invalid');
  110. }
  111. }
  112. //@todo replace this date with the api_get_utc_date function big problem with users that are already registered
  113. $current_date = date('Y-m-d H:i:s', time());
  114. $sql = "INSERT INTO $table_user
  115. SET lastname = '".Database::escape_string(trim($lastName))."',
  116. firstname = '".Database::escape_string(trim($firstName))."',
  117. username = '".Database::escape_string(trim($loginName))."',
  118. status = '".Database::escape_string($status)."',
  119. password = '".Database::escape_string($password)."',
  120. email = '".Database::escape_string($email)."',
  121. official_code = '".Database::escape_string($official_code)."',
  122. picture_uri = '".Database::escape_string($picture_uri)."',
  123. creator_id = '".Database::escape_string($creator_id)."',
  124. auth_source = '".Database::escape_string($auth_source)."',
  125. phone = '".Database::escape_string($phone)."',
  126. language = '".Database::escape_string($language)."',
  127. registration_date = '".$current_date."',
  128. expiration_date = '".Database::escape_string($expiration_date)."',
  129. hr_dept_id = '".Database::escape_string($hr_dept_id)."',
  130. active = '".Database::escape_string($active)."'";
  131. $result = Database::query($sql);
  132. if ($result) {
  133. //echo "id returned";
  134. $return = Database::insert_id();
  135. if (api_get_multiple_access_url()) {
  136. UrlManager::add_user_to_url($return, api_get_current_access_url_id());
  137. } else {
  138. //we are adding by default the access_url_user table with access_url_id = 1
  139. UrlManager::add_user_to_url($return, 1);
  140. }
  141. if (!empty($email) && $send_mail) {
  142. $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS);
  143. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  144. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  145. $email_admin = api_get_setting('emailAdministrator');
  146. if ($_configuration['multiple_access_urls']) {
  147. $access_url_id = api_get_current_access_url_id();
  148. if ($access_url_id != -1) {
  149. $url = api_get_access_url($access_url_id);
  150. $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('Formula').",\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');
  151. }
  152. } else {
  153. $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('Formula').",\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');
  154. }
  155. /* MANAGE EVENT WITH MAIL */
  156. if (EventsMail::check_if_using_class('user_registration')) {
  157. $values["about_user"] = $return;
  158. $values["password"] = $original_password;
  159. $values["send_to"] = array($return);
  160. $values["prior_lang"] = null;
  161. EventsDispatcher::events('user_registration', $values);
  162. } else {
  163. @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
  164. }
  165. /* ENDS MANAGE EVENT WITH MAIL */
  166. }
  167. // Add event to system log
  168. $user_id_manager = api_get_user_id();
  169. $user_info = api_get_user_info($return);
  170. event_system(LOG_USER_CREATE, LOG_USER_ID, $return, api_get_utc_datetime(), $user_id_manager, null, $user_info);
  171. } else {
  172. //echo "false - failed" ;
  173. $return = false;
  174. }
  175. if (is_array($extra) && count($extra) > 0) {
  176. $res = true;
  177. foreach($extra as $fname => $fvalue) {
  178. $res = $res && self::update_extra_field_value($return, $fname, $fvalue);
  179. }
  180. }
  181. self::update_extra_field_value($return, 'already_logged_in', 'false');
  182. return $return;
  183. }
  184. /**
  185. * Can user be deleted?
  186. * This functions checks if there's a course in which the given user is the
  187. * only course administrator. If that is the case, the user can't be
  188. * deleted because the course would remain without a course admin.
  189. * @param int $user_id The user id
  190. * @return boolean true if user can be deleted
  191. */
  192. public static function can_delete_user($user_id) {
  193. global $_configuration;
  194. if (isset($_configuration['delete_users']) && $_configuration['delete_users'] == false) {
  195. return false;
  196. }
  197. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  198. if ($user_id != strval(intval($user_id))) return false;
  199. if ($user_id === false) return false;
  200. $sql = "SELECT * FROM $table_course_user WHERE status = '1' AND user_id = '".$user_id."'";
  201. $res = Database::query($sql);
  202. while ($course = Database::fetch_object($res)) {
  203. $sql = "SELECT user_id FROM $table_course_user WHERE status='1' AND course_code ='".Database::escape_string($course->course_code)."'";
  204. $res2 = Database::query($sql);
  205. if (Database::num_rows($res2) == 1) {
  206. return false;
  207. }
  208. }
  209. return true;
  210. }
  211. /**
  212. * Delete a user from the platform
  213. * @param int $user_id The user id
  214. * @return boolean true if user is succesfully deleted, false otherwise
  215. */
  216. public static function delete_user($user_id) {
  217. if ($user_id != strval(intval($user_id))) return false;
  218. if ($user_id === false) return false;
  219. if (!self::can_delete_user($user_id)) {
  220. return false;
  221. }
  222. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  223. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  224. $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
  225. $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  226. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  227. $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  228. $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  229. $table_group = Database :: get_course_table(TABLE_GROUP_USER);
  230. // Unsubscribe the user from all groups in all his courses
  231. $sql = "SELECT c.id FROM $table_course c, $table_course_user cu
  232. WHERE cu.user_id = '".$user_id."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c.code = cu.course_code";
  233. $res = Database::query($sql);
  234. while ($course = Database::fetch_object($res)) {
  235. $sql = "DELETE FROM $table_group WHERE c_id = {$course->id} AND user_id = $user_id";
  236. Database::query($sql);
  237. }
  238. // Unsubscribe user from all classes
  239. $sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
  240. Database::query($sql);
  241. // Unsubscribe user from all courses
  242. $sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
  243. Database::query($sql);
  244. // Unsubscribe user from all courses in sessions
  245. $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
  246. Database::query($sql);
  247. // Unsubscribe user from all sessions
  248. $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
  249. Database::query($sql);
  250. // Delete user picture
  251. // TODO: Logic about api_get_setting('split_users_upload_directory') === 'true' , a user has 4 differnt sized photos to be deleted.
  252. $user_info = api_get_user_info($user_id);
  253. if (strlen($user_info['picture_uri']) > 0) {
  254. $img_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/'.$user_info['picture_uri'];
  255. if (file_exists($img_path))
  256. unlink($img_path);
  257. }
  258. // Delete the personal course categories
  259. $course_cat_table = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  260. $sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
  261. Database::query($sql);
  262. // Delete user from database
  263. $sql = "DELETE FROM $table_user WHERE user_id = '".$user_id."'";
  264. Database::query($sql);
  265. // Delete user from the admin table
  266. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  267. Database::query($sql);
  268. // Delete the personal agenda-items from this user
  269. $agenda_table = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
  270. $sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
  271. Database::query($sql);
  272. $gradebook_results_table = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
  273. $sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
  274. Database::query($sql);
  275. $user = Database::fetch_array($res);
  276. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  277. $sqlv = "DELETE FROM $t_ufv WHERE user_id = $user_id";
  278. $resv = Database::query($sqlv);
  279. require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
  280. if (api_get_multiple_access_url()) {
  281. $url_id = api_get_current_access_url_id();
  282. UrlManager::delete_url_rel_user($user_id, $url_id);
  283. } else {
  284. //we delete the user from the url_id =1
  285. UrlManager::delete_url_rel_user($user_id, 1);
  286. }
  287. if (api_get_setting('allow_social_tool')=='true' ) {
  288. require_once api_get_path(LIBRARY_PATH).'group_portal_manager.lib.php';
  289. //Delete user from portal groups
  290. $group_list = GroupPortalManager::get_groups_by_user($user_id);
  291. if (!empty($group_list)) {
  292. foreach($group_list as $group_id => $data) {
  293. GroupPortalManager::delete_user_rel_group($user_id, $group_id);
  294. }
  295. }
  296. //Delete user from friend lists
  297. SocialManager::remove_user_rel_user($user_id, true);
  298. }
  299. // Add event to system log
  300. $user_id_manager = api_get_user_id();
  301. event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info);
  302. event_system(LOG_USER_DELETE, LOG_USER_OBJECT, implode(';',$user_info), api_get_utc_datetime(), $user_id_manager, null, $user_info);
  303. return true;
  304. }
  305. /**
  306. * Deactivate users. Can be called either as:
  307. *
  308. * - UserManager :: delete_users(1, 2, 3);
  309. * - UserManager :: delete_users(array(1, 2, 3));
  310. *
  311. * @param array|int $ids
  312. * @return boolean True if at least one user was successfuly deleted. False otherwise.
  313. * @author Laurent Opprecht
  314. */
  315. static function delete_users($ids = array())
  316. {
  317. $result = false;
  318. $ids = is_array($ids) ? $ids : func_get_args();
  319. $ids = array_map('intval', $ids);
  320. foreach($ids as $id)
  321. {
  322. $deleted = self::delete_user($id);
  323. $result = $deleted || $result;
  324. }
  325. return $result;
  326. }
  327. /**
  328. * Deactivate users. Can be called either as:
  329. *
  330. * - UserManager :: deactivate_users(1, 2, 3);
  331. * - UserManager :: deactivate_users(array(1, 2, 3));
  332. *
  333. * @param array|int $ids
  334. * @return boolean
  335. * @author Laurent Opprecht
  336. */
  337. static function deactivate_users($ids = array())
  338. {
  339. if (empty($ids)) {
  340. return false;
  341. }
  342. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  343. $ids = is_array($ids) ? $ids : func_get_args();
  344. $ids = array_map('intval', $ids);
  345. $ids = implode(',', $ids);
  346. $sql = "UPDATE $table_user SET active = 0 WHERE user_id IN ($ids)";
  347. return Database::query($sql);
  348. }
  349. /**
  350. * Activate users. Can be called either as:
  351. *
  352. * - UserManager :: activate_users(1, 2, 3);
  353. * - UserManager :: activate_users(array(1, 2, 3));
  354. *
  355. * @param array|int $ids
  356. * @return boolean
  357. * @author Laurent Opprecht
  358. */
  359. static function activate_users($ids = array())
  360. {
  361. if (empty($ids)) {
  362. return false;
  363. }
  364. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  365. $ids = is_array($ids) ? $ids : func_get_args();
  366. $ids = array_map('intval', $ids);
  367. $ids = implode(',', $ids);
  368. $sql = "UPDATE $table_user SET active = 1 WHERE user_id IN ($ids)";
  369. return Database::query($sql);
  370. }
  371. /**
  372. * Update user information with new openid
  373. * @param int $user_id
  374. * @param string $openid
  375. * @return boolean true if the user information was updated
  376. */
  377. public static function update_openid($user_id, $openid) {
  378. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  379. if ($user_id != strval(intval($user_id))) return false;
  380. if ($user_id === false) return false;
  381. $sql = "UPDATE $table_user SET
  382. openid='".Database::escape_string($openid)."'";
  383. $sql .= " WHERE user_id='$user_id'";
  384. return Database::query($sql);
  385. }
  386. /**
  387. * Update user information
  388. * @param int $user_id
  389. * @param string $firstname
  390. * @param string $lastname
  391. * @param string $username
  392. * @param string $password
  393. * @param string $auth_source
  394. * @param string $email
  395. * @param int $status
  396. * @param string $official_code
  397. * @param string $phone
  398. * @param string $picture_uri
  399. * @param int The user ID of the person who registered this user (optional, defaults to null)
  400. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  401. * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
  402. * @return boolean true if the user information was updated
  403. */
  404. public static function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, $creator_id = null, $hr_dept_id = 0, $extra = null, $language = 'english', $encrypt_method = '', $send_email = false, $reset_password = 0) {
  405. global $_configuration;
  406. $original_password = $password;
  407. $user_info = api_get_user_info($user_id, false, true);
  408. if ($reset_password == 0) {
  409. $password = null;
  410. $auth_source = $user_info['auth_source'];
  411. } elseif($reset_password == 1) {
  412. $original_password = $password = api_generate_password();
  413. $auth_source = PLATFORM_AUTH_SOURCE;
  414. } elseif($reset_password == 2) {
  415. $password = $password;
  416. $auth_source = PLATFORM_AUTH_SOURCE;
  417. } elseif($reset_password == 3) {
  418. $password = $password;
  419. $auth_source = $auth_source;
  420. }
  421. if ($user_id != strval(intval($user_id))) return false;
  422. if ($user_id === false) return false;
  423. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  424. //Checking the user language
  425. $languages = api_get_languages();
  426. if (!in_array($language, $languages['folder'])) {
  427. $language = api_get_setting('platformLanguage');
  428. }
  429. $sql = "UPDATE $table_user SET
  430. lastname='".Database::escape_string($lastname)."',
  431. firstname='".Database::escape_string($firstname)."',
  432. username='".Database::escape_string($username)."',
  433. language='".Database::escape_string($language)."',";
  434. if (!is_null($password)) {
  435. if ($encrypt_method == '') {
  436. $password = api_get_encrypted_password($password);
  437. } else {
  438. if ($_configuration['password_encryption'] === $encrypt_method ) {
  439. if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
  440. return api_set_failure('encrypt_method invalid');
  441. } else if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
  442. return api_set_failure('encrypt_method invalid');
  443. }
  444. } else {
  445. return api_set_failure('encrypt_method invalid');
  446. }
  447. }
  448. $sql .= " password='".Database::escape_string($password)."',";
  449. }
  450. if (!is_null($auth_source)) {
  451. $sql .= " auth_source='".Database::escape_string($auth_source)."',";
  452. }
  453. $sql .= "
  454. email='".Database::escape_string($email)."',
  455. status='".Database::escape_string($status)."',
  456. official_code='".Database::escape_string($official_code)."',
  457. phone='".Database::escape_string($phone)."',
  458. picture_uri='".Database::escape_string($picture_uri)."',
  459. expiration_date='".Database::escape_string($expiration_date)."',
  460. active='".Database::escape_string($active)."',
  461. hr_dept_id=".intval($hr_dept_id);
  462. if (!is_null($creator_id)) {
  463. $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
  464. }
  465. $sql .= " WHERE user_id='$user_id'";
  466. $return = Database::query($sql);
  467. if (is_array($extra) && count($extra) > 0) {
  468. $res = true;
  469. foreach($extra as $fname => $fvalue) {
  470. $res = $res && self::update_extra_field_value($user_id,$fname,$fvalue);
  471. }
  472. }
  473. if (!empty($email) && $send_email) {
  474. $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
  475. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  476. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  477. $email_admin = api_get_setting('emailAdministrator');
  478. if ($_configuration['multiple_access_urls']) {
  479. $access_url_id = api_get_current_access_url_id();
  480. if ($access_url_id != -1) {
  481. $url = api_get_access_url($access_url_id);
  482. $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('Formula').",\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');
  483. }
  484. } else {
  485. $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('Formula').",\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');
  486. }
  487. @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
  488. }
  489. return $return;
  490. }
  491. /**
  492. * Disables or enables a user
  493. *
  494. * @param int user_id
  495. * @param int Enable or disable
  496. */
  497. private static function change_active_state($user_id, $active) {
  498. $user_id = (int)$user_id;
  499. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  500. $sql = "UPDATE $table_user SET active = '$active' WHERE user_id = '$user_id';";
  501. Database::query($sql);
  502. }
  503. /**
  504. * Disables a user
  505. *
  506. * @param int User id
  507. */
  508. public static function disable($user_id) {
  509. self::change_active_state($user_id, 0);
  510. }
  511. /**
  512. * Enable a user
  513. *
  514. * @param int User id
  515. */
  516. public static function enable($user_id) {
  517. self::change_active_state($user_id, 1);
  518. }
  519. /**
  520. * Returns the user's id based on the original id and field name in the extra fields. Returns 0 if no user was found
  521. *
  522. * @param string Original user id
  523. * @param string Original field name
  524. * @return int User id
  525. */
  526. public static function get_user_id_from_original_id($original_user_id_value, $original_user_id_name) {
  527. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  528. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  529. $sql = "SELECT user_id FROM $t_uf uf INNER JOIN $t_ufv ufv ON ufv.field_id=uf.id WHERE field_variable='$original_user_id_name' AND field_value='$original_user_id_value';";
  530. $res = Database::query($sql);
  531. $row = Database::fetch_object($res);
  532. if ($row) {
  533. return $row->user_id;
  534. } else {
  535. return 0;
  536. }
  537. }
  538. /**
  539. * Check if a username is available
  540. * @param string the wanted username
  541. * @return boolean true if the wanted username is available
  542. */
  543. public static function is_username_available($username) {
  544. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  545. $sql = "SELECT username FROM $table_user WHERE username = '".Database::escape_string($username)."'";
  546. $res = Database::query($sql);
  547. return Database::num_rows($res) == 0;
  548. }
  549. /**
  550. * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
  551. * @param string $firstname The first name of the user.
  552. * @param string $lastname The last name of the user.
  553. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  554. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  555. * @return string Suggests a username that contains only ASCII-letters and digits, without check for uniqueness within the system.
  556. * @author Julio Montoya Armas
  557. * @author Ivan Tcholakov, 2009 - rework about internationalization.
  558. */
  559. public static function create_username($firstname, $lastname, $language = null, $encoding = null) {
  560. if (is_null($encoding)) {
  561. $encoding = api_get_system_encoding();
  562. }
  563. if (is_null($language)) {
  564. $language = api_get_interface_language();
  565. }
  566. $firstname = api_substr(preg_replace(USERNAME_PURIFIER, '', api_transliterate($firstname, '', $encoding)), 0, 1); // The first letter only.
  567. //Looking for a space in the lastname
  568. $pos = api_strpos($lastname, ' ');
  569. if ($pos !== false ) {
  570. $lastname = api_substr($lastname, 0, $pos);
  571. }
  572. $lastname = preg_replace(USERNAME_PURIFIER, '', api_transliterate($lastname, '', $encoding));
  573. //$username = api_is_western_name_order(null, $language) ? $firstname.$lastname : $lastname.$firstname;
  574. $username = $firstname.$lastname;
  575. if (empty($username)) {
  576. $username = 'user';
  577. }
  578. return strtolower(substr($username, 0, USERNAME_MAX_LENGTH - 3));
  579. }
  580. /**
  581. * Creates a unique username, using:
  582. * 1. the first name and the last name of a user;
  583. * 2. an already created username but not checked for uniqueness yet.
  584. * @param string $firstname The first name of a given user. If the second parameter $lastname is NULL, then this
  585. * parameter is treated as username which is to be checked for uniqueness and to be modified when it is necessary.
  586. * @param string $lastname The last name of the user.
  587. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  588. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  589. * @return string Returns a username that contains only ASCII-letters and digits, and that is unique within the system.
  590. * Note: When the method is called several times with same parameters, its results look like the following sequence: ivan, ivan2, ivan3, ivan4, ...
  591. * @author Ivan Tcholakov, 2009
  592. */
  593. public static function create_unique_username($firstname, $lastname = null, $language = null, $encoding = null) {
  594. if (is_null($lastname)) {
  595. // In this case the actual input parameter $firstname should contain ASCII-letters and digits only.
  596. // For making this method tolerant of mistakes, let us transliterate and purify the suggested input username anyway.
  597. // So, instead of the sentence $username = $firstname; we place the following:
  598. $username = strtolower(preg_replace(USERNAME_PURIFIER, '', api_transliterate($firstname, '', $encoding)));
  599. } else {
  600. $username = self::create_username($firstname, $lastname, $language, $encoding);
  601. }
  602. if (!self::is_username_available($username)) {
  603. $i = 2;
  604. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string)$i)).$i;
  605. while (!self::is_username_available($temp_username)) {
  606. $i++;
  607. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string)$i)).$i;
  608. }
  609. $username = $temp_username;
  610. }
  611. return $username;
  612. }
  613. /**
  614. * Modifies a given username accordingly to the specification for valid characters and length.
  615. * @param $username string The input username.
  616. * @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.
  617. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  618. * @return string The resulting purified username.
  619. */
  620. public function purify_username($username, $strict = false, $encoding = null) {
  621. if ($strict) {
  622. // 1. Conversion of unacceptable letters (latinian letters with accents for example) into ASCII letters in order they not to be totally removed.
  623. // 2. Applying the strict purifier.
  624. // 3. Length limitation.
  625. $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);
  626. return $toreturn;
  627. }
  628. // 1. Applying the shallow purifier.
  629. // 2. Length limitation.
  630. return substr(preg_replace(USERNAME_PURIFIER_SHALLOW, '', $username), 0, USERNAME_MAX_LENGTH);
  631. }
  632. /**
  633. * Checks whether the user id exists in the database
  634. *
  635. * @param int User id
  636. * @return bool True if user id was found, false otherwise
  637. */
  638. public static function is_user_id_valid($user_id) {
  639. $user_id = (int)$user_id;
  640. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  641. $sql = "SELECT user_id FROM $table_user WHERE user_id = '".$user_id."'";
  642. $res = Database::query($sql);
  643. $num_rows = Database::num_rows($res);
  644. if($num_rows == 0) {
  645. return false;
  646. } else {
  647. return true;
  648. }
  649. }
  650. /**
  651. * Checks whether a given username matches to the specification strictly. The empty username is assumed here as invalid.
  652. * Mostly this function is to be used in the user interface built-in validation routines for providing feedback while usernames are enterd manually.
  653. * @param string $username The input username.
  654. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  655. * @return bool Returns TRUE if the username is valid, FALSE otherwise.
  656. */
  657. public function is_username_valid($username, $encoding = null) {
  658. return !empty($username) && $username == self::purify_username($username, true);
  659. }
  660. /**
  661. * Checks whether a username is empty. If the username contains whitespace characters, such as spaces, tabulators, newlines, etc.,
  662. * it is assumed as empty too. This function is safe for validation unpurified data (during importing).
  663. * @param string $username The given username.
  664. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  665. */
  666. public static function is_username_empty($username) {
  667. return (strlen(self::purify_username($username, false)) == 0);
  668. }
  669. /**
  670. * Checks whether a username is too long or not.
  671. * @param string $username The given username, it should contain only ASCII-letters and digits.
  672. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  673. */
  674. public static function is_username_too_long($username) {
  675. return (strlen($username) > USERNAME_MAX_LENGTH);
  676. }
  677. public static function get_user_list_by_ids($ids = array(), $active = null)
  678. {
  679. if(empty($ids)) {
  680. return array();
  681. }
  682. $ids = is_array($ids) ? $ids : array($ids);
  683. $ids = array_map('intval', $ids);
  684. $ids = implode(',', $ids);
  685. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  686. $sql = "SELECT * FROM $tbl_user WHERE user_id IN ($ids)";
  687. if(!is_null($active)) {
  688. $sql .= ' AND active=' . ($active ? '1' : '0');
  689. }
  690. $rs = Database::query($sql);
  691. $result = array();
  692. while ($row = Database::fetch_array($rs)) {
  693. $result[] = $row;
  694. }
  695. return $result;
  696. }
  697. /**
  698. * Get a list of users of which the given conditions match with an = 'cond'
  699. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  700. * @param array $order_by a list of fields on which sort
  701. * @return array An array with all users of the platform.
  702. * @todo optional course code parameter, optional sorting parameters...
  703. */
  704. public static function get_user_list($conditions = array(), $order_by = array(), $limit_from = false, $limit_to = false) {
  705. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  706. $return_array = array();
  707. $sql_query = "SELECT * FROM $user_table";
  708. if (count($conditions) > 0) {
  709. $sql_query .= ' WHERE ';
  710. foreach ($conditions as $field => $value) {
  711. $field = Database::escape_string($field);
  712. $value = Database::escape_string($value);
  713. $sql_query .= "$field = '$value'";
  714. }
  715. }
  716. if (count($order_by) > 0) {
  717. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by));
  718. }
  719. if (is_numeric($limit_from) && is_numeric($limit_from)) {
  720. $limit_from = intval($limit_from);
  721. $limit_to = intval($limit_to);
  722. $sql_query .= " LIMIT $limit_from, $limit_to";
  723. }
  724. $sql_result = Database::query($sql_query);
  725. while ($result = Database::fetch_array($sql_result)) {
  726. $return_array[] = $result;
  727. }
  728. return $return_array;
  729. }
  730. /**
  731. * Get a list of users of which the given conditions match with a LIKE '%cond%'
  732. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  733. * @param array $order_by a list of fields on which sort
  734. * @return array An array with all users of the platform.
  735. * @todo optional course code parameter, optional sorting parameters...
  736. */
  737. public static function get_user_list_like($conditions = array(), $order_by = array(), $simple_like = false, $condition = 'AND') {
  738. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  739. $return_array = array();
  740. $sql_query = "SELECT * FROM $user_table";
  741. if (count($conditions) > 0) {
  742. $sql_query .= ' WHERE ';
  743. $temp_conditions = array();
  744. foreach ($conditions as $field => $value) {
  745. $field = Database::escape_string($field);
  746. $value = Database::escape_string($value);
  747. if ($simple_like) {
  748. $temp_conditions[]= $field." LIKE '$value%'";
  749. } else {
  750. $temp_conditions[]= $field.' LIKE \'%'.$value.'%\'';
  751. }
  752. }
  753. if (!empty($temp_conditions)) {
  754. $sql_query .= implode(' '.$condition.' ', $temp_conditions);
  755. }
  756. }
  757. if (count($order_by) > 0) {
  758. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by));
  759. }
  760. $sql_result = Database::query($sql_query);
  761. while ($result = Database::fetch_array($sql_result)) {
  762. $return_array[] = $result;
  763. }
  764. return $return_array;
  765. }
  766. /**
  767. * Get user information
  768. * @param string The username
  769. * @return array All user information as an associative array
  770. */
  771. public static function get_user_info($username) {
  772. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  773. $username = Database::escape_string($username);
  774. $sql = "SELECT * FROM $user_table WHERE username='".$username."'";
  775. $res = Database::query($sql);
  776. if (Database::num_rows($res) > 0) {
  777. return Database::fetch_array($res);
  778. }
  779. return false;
  780. }
  781. /**
  782. * Get user information
  783. * @param string The id
  784. * @param boolean Whether to return the user's extra fields (defaults to false)
  785. * @return array All user information as an associative array
  786. */
  787. public static function get_user_info_by_id($user_id, $user_fields = false) {
  788. $user_id = intval($user_id);
  789. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  790. $sql = "SELECT * FROM $user_table WHERE user_id=".$user_id;
  791. $res = Database::query($sql);
  792. if (Database::num_rows($res) > 0) {
  793. $user = Database::fetch_array($res);
  794. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  795. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  796. $sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
  797. $resf = Database::query($sqlf);
  798. if (Database::num_rows($resf) > 0) {
  799. while ($rowf = Database::fetch_array($resf)) {
  800. $sqlv = "SELECT * FROM $t_ufv WHERE field_id = ".$rowf['id']." AND user_id = ".$user['user_id']." ORDER BY id DESC";
  801. $resv = Database::query($sqlv);
  802. if (Database::num_rows($resv) > 0) {
  803. //There should be only one value for a field and a user
  804. $rowv = Database::fetch_array($resv);
  805. $user['extra'][$rowf['field_variable']] = $rowv['field_value'];
  806. } else {
  807. $user['extra'][$rowf['field_variable']] = '';
  808. }
  809. }
  810. }
  811. return $user;
  812. }
  813. return false;
  814. }
  815. /** Get the teacher list
  816. * @param int the course ID
  817. * @param array Content the list ID of user_id selected
  818. */
  819. //for survey
  820. // 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?
  821. public static function get_teacher_list($course_id, $sel_teacher = '') {
  822. $user_course_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  823. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  824. $course_id = Database::escape_string($course_id);
  825. $sql_query = "SELECT * FROM $user_table a, $user_course_table b where a.user_id=b.user_id AND b.status=1 AND b.course_code='$course_id'";
  826. $sql_result = Database::query($sql_query);
  827. echo "<select name=\"author\">";
  828. while ($result = Database::fetch_array($sql_result)) {
  829. if ($sel_teacher == $result['user_id']) $selected ="selected";
  830. echo "\n<option value=\"".$result['user_id']."\" $selected>".$result['firstname']."</option>";
  831. }
  832. echo "</select>";
  833. }
  834. /**
  835. * Get user picture URL or path from user ID (returns an array).
  836. * The return format is a complete path, enabling recovery of the directory
  837. * with dirname() or the file with basename(). This also works for the
  838. * functions dealing with the user's productions, as they are located in
  839. * the same directory.
  840. * @param integer User ID
  841. * @param string Type of path to return (can be 'none', 'system', 'rel', 'web')
  842. * @param bool Whether we want to have the directory name returned 'as if' there was a file or not (in the case we want to know which directory to create - otherwise no file means no split subdir)
  843. * @param bool If we want that the function returns the /main/img/unknown.jpg image set it at true
  844. * @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
  845. */
  846. public static function get_user_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false) {
  847. switch ($type) {
  848. case 'system': // Base: absolute system path.
  849. $base = api_get_path(SYS_CODE_PATH);
  850. break;
  851. case 'rel': // Base: semi-absolute web path (no server base).
  852. $base = api_get_path(REL_CODE_PATH);
  853. break;
  854. case 'web': // Base: absolute web path.
  855. $base = api_get_path(WEB_CODE_PATH);
  856. break;
  857. case 'none':
  858. default: // Base: empty, the result path below will be relative.
  859. $base = '';
  860. }
  861. if (empty($id) || empty($type)) {
  862. return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
  863. }
  864. $user_id = intval($id);
  865. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  866. $sql = "SELECT picture_uri FROM $user_table WHERE user_id=".$user_id;
  867. $res = Database::query($sql);
  868. if (!Database::num_rows($res)) {
  869. return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
  870. }
  871. $user = Database::fetch_array($res);
  872. $picture_filename = trim($user['picture_uri']);
  873. if (api_get_setting('split_users_upload_directory') === 'true') {
  874. if (!empty($picture_filename) or $preview) {
  875. $dir = $base.'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
  876. } else {
  877. $dir = $base.'upload/users/'.$user_id.'/';
  878. }
  879. } else {
  880. $dir = $base.'upload/users/'.$user_id.'/';
  881. }
  882. if (empty($picture_filename) && $anonymous) {
  883. return array('dir' => $base.'img/', 'file' => 'unknown.jpg');
  884. }
  885. return array('dir' => $dir, 'file' => $picture_filename);
  886. }
  887. /**
  888. * Creates new user pfotos in various sizes of a user, or deletes user pfotos.
  889. * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php
  890. * @param int $user_id The user internal identitfication number.
  891. * @param string $file The common file name for the newly created pfotos.
  892. * It will be checked and modified for compatibility with the file system.
  893. * If full name is provided, path component is ignored.
  894. * If an empty name is provided, then old user photos are deleted only,
  895. * @see UserManager::delete_user_picture() as the prefered way for deletion.
  896. * @param string $source_file The full system name of the image from which user photos will be created.
  897. * @return string/bool Returns the resulting common file name of created images which usually should be stored in database.
  898. * When deletion is recuested returns empty string. In case of internal error or negative validation returns FALSE.
  899. */
  900. public static function update_user_picture($user_id, $file = null, $source_file = null) {
  901. if (empty($user_id)) {
  902. return false;
  903. }
  904. $delete = empty($file);
  905. if (empty($source_file)) {
  906. $source_file = $file;
  907. }
  908. // Configuration options about user photos.
  909. require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
  910. // User-reserved directory where photos have to be placed.
  911. $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
  912. $path = $path_info['dir'];
  913. // If this directory does not exist - we create it.
  914. if (!file_exists($path)) {
  915. @mkdir($path, api_get_permissions_for_new_directories(), true);
  916. }
  917. // The old photos (if any).
  918. $old_file = $path_info['file'];
  919. // Let us delete them.
  920. if (!empty($old_file)) {
  921. if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
  922. $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
  923. @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
  924. @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
  925. @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
  926. @rename($path.$old_file, $path.$prefix.$old_file);
  927. } else {
  928. @unlink($path.'small_'.$old_file);
  929. @unlink($path.'medium_'.$old_file);
  930. @unlink($path.'big_'.$old_file);
  931. @unlink($path.$old_file);
  932. }
  933. }
  934. // Exit if only deletion has been requested. Return an empty picture name.
  935. if ($delete) {
  936. return '';
  937. }
  938. // Validation 2.
  939. $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
  940. $file = str_replace('\\', '/', $file);
  941. $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
  942. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  943. if (!in_array($extension, $allowed_types)) {
  944. return false;
  945. }
  946. // This is the common name for the new photos.
  947. if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
  948. $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
  949. $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
  950. $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
  951. } else {
  952. $filename = replace_dangerous_char($filename);
  953. if (PREFIX_IMAGE_FILENAME_WITH_UID) {
  954. $filename = uniqid('').'_'.$filename;
  955. }
  956. // We always prefix user photos with user ids, so on setting
  957. // api_get_setting('split_users_upload_directory') === 'true'
  958. // the correspondent directories to be found successfully.
  959. $filename = $user_id.'_'.$filename;
  960. }
  961. // Storing the new photos in 4 versions with various sizes.
  962. $small = self::resize_picture($source_file, 22);
  963. $medium = self::resize_picture($source_file, 85);
  964. $normal = self::resize_picture($source_file, 200);
  965. $big = new Image($source_file); // This is the original picture.
  966. $ok = false;
  967. $ok = $small->send_image($path.'small_'.$filename) &&
  968. $medium->send_image($path.'medium_'.$filename) &&
  969. $normal->send_image($path.$filename) &&
  970. $big->send_image( $path.'big_'.$filename);
  971. return $ok ? $filename : false;
  972. }
  973. /**
  974. * Deletes user pfotos.
  975. * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php
  976. * @param int $user_id The user internal identitfication number.
  977. * @return string/bool Returns empty string on success, FALSE on error.
  978. */
  979. public static function delete_user_picture($user_id) {
  980. return self::update_user_picture($user_id);
  981. }
  982. /* PRODUCTIONS FUNCTIONS */
  983. /**
  984. * Returns an XHTML formatted list of productions for a user, or FALSE if he
  985. * doesn't have any.
  986. *
  987. * If there has been a request to remove a production, the function will return
  988. * without building the list unless forced to do so by the optional second
  989. * parameter. This increases performance by avoiding to read through the
  990. * productions on the filesystem before the removal request has been carried
  991. * out because they'll have to be re-read afterwards anyway.
  992. *
  993. * @param $user_id User id
  994. * @param $force Optional parameter to force building after a removal request
  995. * @return A string containing the XHTML code to dipslay the production list, or FALSE
  996. */
  997. public static function build_production_list($user_id, $force = false, $showdelete = false) {
  998. if (!$force && !empty($_POST['remove_production'])) {
  999. return true; // postpone reading from the filesystem
  1000. }
  1001. $productions = self::get_user_productions($user_id);
  1002. if (empty($productions)) {
  1003. return false;
  1004. }
  1005. $production_path = self::get_user_picture_path_by_id($user_id, 'web', true);
  1006. $production_dir = $production_path['dir'].$user_id.'/';
  1007. $del_image = api_get_path(WEB_CODE_PATH).'img/delete.gif';
  1008. $del_text = get_lang('Delete');
  1009. $production_list = '';
  1010. if (count($productions) > 0) {
  1011. $production_list = '<ul id="productions">';
  1012. foreach ($productions as $file) {
  1013. $production_list .= '<li><a href="'.$production_dir.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  1014. if ($showdelete) {
  1015. $production_list .= '<input 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>';
  1016. }
  1017. }
  1018. $production_list .= '</ul>';
  1019. }
  1020. return $production_list;
  1021. }
  1022. /**
  1023. * Returns an array with the user's productions.
  1024. *
  1025. * @param $user_id User id
  1026. * @return An array containing the user's productions
  1027. */
  1028. public static function get_user_productions($user_id) {
  1029. $production_path = self::get_user_picture_path_by_id($user_id, 'system', true);
  1030. $production_repository = $production_path['dir'].$user_id.'/';
  1031. $productions = array();
  1032. if (is_dir($production_repository)) {
  1033. $handle = opendir($production_repository);
  1034. while ($file = readdir($handle)) {
  1035. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($production_repository.$file)) {
  1036. continue; // skip current/parent directory and .htaccess
  1037. }
  1038. if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) {
  1039. // User's photos should not be listed as productions.
  1040. continue;
  1041. }
  1042. $productions[] = $file;
  1043. }
  1044. }
  1045. return $productions; // can be an empty array
  1046. }
  1047. /**
  1048. * Remove a user production.
  1049. *
  1050. * @param $user_id User id
  1051. * @param $production The production to remove
  1052. */
  1053. public static function remove_user_production($user_id, $production) {
  1054. $production_path = self::get_user_picture_path_by_id($user_id, 'system', true);
  1055. $production_file = $production_path['dir'].$user_id.'/'.$production;
  1056. if (is_file($production_file)) {
  1057. unlink($production_file);
  1058. return true;
  1059. }
  1060. return false;
  1061. }
  1062. /**
  1063. * Update an extra field. This function is called when a user changes his/her profile
  1064. * and by consequence fills or edits his/her extra fields.
  1065. *
  1066. * @param integer Field ID
  1067. * @param array Database columns and their new value
  1068. * @return boolean true if field updated, false otherwise
  1069. */
  1070. public static function update_extra_field($fid, $columns) {
  1071. //TODO check that values added are values proposed for enumerated field types
  1072. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1073. $fid = Database::escape_string($fid);
  1074. $sqluf = "UPDATE $t_uf SET ";
  1075. $known_fields = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter');
  1076. $safecolumns = array();
  1077. foreach ($columns as $index => $newval) {
  1078. if (in_array($index, $known_fields)) {
  1079. $safecolumns[$index] = Database::escape_string($newval);
  1080. $sqluf .= $index." = '".$safecolumns[$index]."', ";
  1081. }
  1082. }
  1083. $time = time();
  1084. $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'";
  1085. $resuf = Database::query($sqluf);
  1086. return $resuf;
  1087. }
  1088. /**
  1089. * Update an extra field value for a given user
  1090. * @param integer User ID
  1091. * @param string Field variable name
  1092. * @param string Field value
  1093. * @return boolean true if field updated, false otherwise
  1094. */
  1095. public static function update_extra_field_value($user_id, $fname, $fvalue = '') {
  1096. //TODO check that values added are values proposed for enumerated field types
  1097. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1098. $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1099. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1100. $fname = Database::escape_string($fname);
  1101. if ($user_id != strval(intval($user_id))) return false;
  1102. if ($user_id === false) return false;
  1103. $fvalues = '';
  1104. //echo '<pre>'; print_r($fvalue);
  1105. if (is_array($fvalue)) {
  1106. foreach($fvalue as $val) {
  1107. $fvalues .= Database::escape_string($val).';';
  1108. }
  1109. if (!empty($fvalues)) {
  1110. $fvalues = substr($fvalues, 0, -1);
  1111. }
  1112. } else {
  1113. $fvalues = Database::escape_string($fvalue);
  1114. }
  1115. $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
  1116. $resuf = Database::query($sqluf);
  1117. if (Database::num_rows($resuf) == 1) {
  1118. //ok, the field exists
  1119. // Check if enumerated field, if the option is available
  1120. $rowuf = Database::fetch_array($resuf);
  1121. switch ($rowuf['field_type']) {
  1122. case self::USER_FIELD_TYPE_TAG :
  1123. //4. Tags are process here comes from main/auth/profile.php
  1124. UserManager::process_tags(explode(';', $fvalues), $user_id, $rowuf['id']);
  1125. return true;
  1126. break;
  1127. case self::USER_FIELD_TYPE_RADIO:
  1128. case self::USER_FIELD_TYPE_SELECT:
  1129. case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
  1130. $sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
  1131. $resuo = Database::query($sqluo);
  1132. $values = split(';',$fvalues);
  1133. if (Database::num_rows($resuo) > 0) {
  1134. $check = false;
  1135. while ($rowuo = Database::fetch_array($resuo)) {
  1136. if (in_array($rowuo['option_value'], $values)) {
  1137. $check = true;
  1138. break;
  1139. }
  1140. }
  1141. if (!$check) {
  1142. return false; //option value not found
  1143. }
  1144. } else {
  1145. return false; //enumerated type but no option found
  1146. }
  1147. break;
  1148. case 1:
  1149. case 2:
  1150. default:
  1151. break;
  1152. }
  1153. $tms = time();
  1154. $sqlufv = "SELECT * FROM $t_ufv WHERE user_id = $user_id AND field_id = ".$rowuf['id']." ORDER BY id";
  1155. $resufv = Database::query($sqlufv);
  1156. $n = Database::num_rows($resufv);
  1157. if ($n > 1) {
  1158. //problem, we already have to values for this field and user combination - keep last one
  1159. while ($rowufv = Database::fetch_array($resufv)) {
  1160. if ($n > 1) {
  1161. $sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
  1162. Database::query($sqld);
  1163. $n--;
  1164. }
  1165. $rowufv = Database::fetch_array($resufv);
  1166. if ($rowufv['field_value'] != $fvalues) {
  1167. $sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
  1168. $resu = Database::query($sqlu);
  1169. return($resu ? true : false);
  1170. }
  1171. return true;
  1172. }
  1173. } elseif ($n == 1) {
  1174. //we need to update the current record
  1175. $rowufv = Database::fetch_array($resufv);
  1176. if ($rowufv['field_value'] != $fvalues) {
  1177. // If the new field is empty, delete it
  1178. if ($fvalues == '') {
  1179. $sql_query = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'].";";
  1180. } else {
  1181. // Otherwise update it
  1182. $sql_query = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
  1183. }
  1184. $resu = Database::query($sql_query);
  1185. return($resu ? true : false);
  1186. }
  1187. return true;
  1188. } else {
  1189. $sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms) " .
  1190. "VALUES ($user_id,".$rowuf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
  1191. //error_log('UM::update_extra_field_value: '.$sqli);
  1192. $resi = Database::query($sqli);
  1193. return($resi ? true : false);
  1194. }
  1195. } else {
  1196. return false; //field not found
  1197. }
  1198. }
  1199. /**
  1200. * Get an array of extra fieds with field details (type, default value and options)
  1201. * @param integer Offset (from which row)
  1202. * @param integer Number of items
  1203. * @param integer Column on which sorting is made
  1204. * @param string Sorting direction
  1205. * @param boolean Optional. Whether we get all the fields or just the visible ones
  1206. * @param int Optional. Whether we get all the fields with field_filter 1 or 0 or everything
  1207. * @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
  1208. */
  1209. public static function get_extra_fields($from = 0, $number_of_items = 0, $column = 5, $direction = 'ASC', $all_visibility = true, $field_filter = null) {
  1210. $fields = array();
  1211. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1212. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1213. $columns = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_filter', 'tms');
  1214. $column = intval($column);
  1215. $sort_direction = '';
  1216. if (in_array(strtoupper($direction), array('ASC', 'DESC'))) {
  1217. $sort_direction = strtoupper($direction);
  1218. }
  1219. $sqlf = "SELECT * FROM $t_uf WHERE 1 = 1 ";
  1220. if (!$all_visibility) {
  1221. $sqlf .= " AND field_visible = 1 ";
  1222. }
  1223. if (!is_null($field_filter)) {
  1224. $field_filter = intval($field_filter);
  1225. $sqlf .= " AND field_filter = $field_filter ";
  1226. }
  1227. $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction " ;
  1228. if ($number_of_items != 0) {
  1229. $sqlf .= " LIMIT ".Database::escape_string($from).','.Database::escape_string($number_of_items);
  1230. }
  1231. $resf = Database::query($sqlf);
  1232. if (Database::num_rows($resf) > 0) {
  1233. while($rowf = Database::fetch_array($resf)) {
  1234. $fields[$rowf['id']] = array(
  1235. 0 => $rowf['id'],
  1236. 1 => $rowf['field_variable'],
  1237. 2 => $rowf['field_type'],
  1238. //3 => (empty($rowf['field_display_text']) ? '' : get_lang($rowf['field_display_text'], '')),
  1239. // Temporarily removed auto-translation. Need update to get_lang() to know if translation exists (todo)
  1240. // Ivan, 15-SEP-2009: get_lang() has been modified accordingly in order this issue to be solved.
  1241. 3 => (empty($rowf['field_display_text']) ? '' : $rowf['field_display_text']),
  1242. 4 => $rowf['field_default_value'],
  1243. 5 => $rowf['field_order'],
  1244. 6 => $rowf['field_visible'],
  1245. 7 => $rowf['field_changeable'],
  1246. 8 => $rowf['field_filter'],
  1247. 9 => array()
  1248. );
  1249. $sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id']." ORDER BY option_order ASC";
  1250. $reso = Database::query($sqlo);
  1251. if (Database::num_rows($reso) > 0) {
  1252. while ($rowo = Database::fetch_array($reso)) {
  1253. $fields[$rowf['id']][9][$rowo['id']] = array(
  1254. 0 => $rowo['id'],
  1255. 1 => $rowo['option_value'],
  1256. //2 => (empty($rowo['option_display_text']) ? '' : get_lang($rowo['option_display_text'], '')),
  1257. 2 => (empty($rowo['option_display_text']) ? '' : $rowo['option_display_text']),
  1258. 3 => $rowo['option_order']
  1259. );
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return $fields;
  1265. }
  1266. /**
  1267. * Get the list of options attached to an extra field
  1268. * @param string $fieldname the name of the field
  1269. * @return array the list of options
  1270. */
  1271. public static function get_extra_field_options($field_name) {
  1272. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1273. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1274. $sql = 'SELECT options.*
  1275. FROM '.$t_ufo.' options
  1276. INNER JOIN '.$t_uf.' fields
  1277. ON fields.id = options.field_id
  1278. AND fields.field_variable="'.Database::escape_string($field_name).'"';
  1279. $rs = Database::query($sql);
  1280. return Database::store_result($rs);
  1281. }
  1282. /**
  1283. * Get the number of extra fields currently recorded
  1284. * @param boolean Optional switch. true (default) returns all fields, false returns only visible fields
  1285. * @return integer Number of fields
  1286. */
  1287. public static function get_number_of_extra_fields($all_visibility = true) {
  1288. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1289. $sqlf = "SELECT * FROM $t_uf ";
  1290. if (!$all_visibility) {
  1291. $sqlf .= " WHERE field_visible = 1 ";
  1292. }
  1293. $sqlf .= " ORDER BY field_order";
  1294. $resf = Database::query($sqlf);
  1295. return Database::num_rows($resf);
  1296. }
  1297. /**
  1298. * Creates a new extra field
  1299. * @param string Field's internal variable name
  1300. * @param int Field's type
  1301. * @param string Field's language var name
  1302. * @param string Field's default value
  1303. * @param string Optional comma-separated list of options to provide for select and radio
  1304. * @return int new user id - if the new user creation succeeds, false otherwise
  1305. */
  1306. public static function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
  1307. // database table definition
  1308. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1309. $table_field_options= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1310. // First check wether the login already exists
  1311. if (self::is_extra_field_available($fieldvarname)) {
  1312. return api_set_failure('login-pass already taken');
  1313. }
  1314. $sql = "SELECT MAX(field_order) FROM $table_field";
  1315. $res = Database::query($sql);
  1316. $order = 0;
  1317. if (Database::num_rows($res) > 0) {
  1318. $row = Database::fetch_array($res);
  1319. $order = $row[0]+1;
  1320. }
  1321. $time = time();
  1322. $sql = "INSERT INTO $table_field
  1323. SET field_type = '".Database::escape_string($fieldtype)."',
  1324. field_variable = '".Database::escape_string($fieldvarname)."',
  1325. field_display_text = '".Database::escape_string($fieldtitle)."',
  1326. field_default_value = '".Database::escape_string($fielddefault)."',
  1327. field_order = '$order',
  1328. tms = FROM_UNIXTIME($time)";
  1329. $result = Database::query($sql);
  1330. if ($result) {
  1331. //echo "id returned";
  1332. $return = Database::insert_id();
  1333. } else {
  1334. //echo "false - failed" ;
  1335. return false;
  1336. }
  1337. 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))) {
  1338. if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
  1339. $twolist = explode('|', $fieldoptions);
  1340. $counter = 0;
  1341. foreach ($twolist as $individual_list) {
  1342. $splitted_individual_list = split(';', $individual_list);
  1343. foreach ($splitted_individual_list as $individual_list_option) {
  1344. //echo 'counter:'.$counter;
  1345. if ($counter == 0) {
  1346. $list[] = $individual_list_option;
  1347. } else {
  1348. $list[] = str_repeat('*', $counter).$individual_list_option;
  1349. }
  1350. }
  1351. $counter++;
  1352. }
  1353. } else {
  1354. $list = split(';', $fieldoptions);
  1355. }
  1356. foreach ($list as $option) {
  1357. $option = Database::escape_string($option);
  1358. $sql = "SELECT * FROM $table_field_options WHERE field_id = $return AND option_value = '".$option."'";
  1359. $res = Database::query($sql);
  1360. if (Database::num_rows($res) > 0) {
  1361. //the option already exists, do nothing
  1362. } else {
  1363. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = $return";
  1364. $res = Database::query($sql);
  1365. $max = 1;
  1366. if (Database::num_rows($res) > 0) {
  1367. $row = Database::fetch_array($res);
  1368. $max = $row[0] + 1;
  1369. }
  1370. $time = time();
  1371. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ($return,'$option','$option',$max,FROM_UNIXTIME($time))";
  1372. $res = Database::query($sql);
  1373. if ($res === false) {
  1374. $return = false;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. return $return;
  1380. }
  1381. /**
  1382. * Save the changes in the definition of the extra user profile field
  1383. * The function is called after you (as admin) decide to store the changes you have made to one of the fields you defined
  1384. *
  1385. * There is quite some logic in this field
  1386. * 1. store the changes to the field (tupe, name, label, default text)
  1387. * 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
  1388. * the options (and choices) that do no longer have to appear. We cannot remove all options and choices because if you remove them all
  1389. * and simply re-add them all then all the user who have already filled this form will loose their selected value.
  1390. * 3. we add the options that are newly added
  1391. *
  1392. * <code> current options are a;b;c and the user changes this to a;b;x (removing c and adding x)
  1393. * we first remove c (and also the entry in the option_value table for the users who have chosen this)
  1394. * we then add x
  1395. * a and b are neither removed nor added
  1396. * </code>
  1397. * @param integer $fieldid the id of the field we are editing
  1398. * @param string $fieldvarname the internal variable name of the field
  1399. * @param int $fieldtype the type of the field
  1400. * @param string $fieldtitle the title of the field
  1401. * @param string $fielddefault the default value of the field
  1402. * @param string $fieldoptions Optional comma-separated list of options to provide for select and radio
  1403. * @return boolean true
  1404. *
  1405. *
  1406. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1407. * @version July 2008
  1408. * @since Dokeos 1.8.6
  1409. */
  1410. public static function save_extra_field_changes($fieldid, $fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
  1411. // database table definition
  1412. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1413. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1414. $table_field_options_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1415. // we first update the field definition with the new values
  1416. $time = time();
  1417. $sql = "UPDATE $table_field
  1418. SET field_type = '".Database::escape_string($fieldtype)."',
  1419. field_variable = '".Database::escape_string($fieldvarname)."',
  1420. field_display_text = '".Database::escape_string($fieldtitle)."',
  1421. field_default_value = '".Database::escape_string($fielddefault)."',
  1422. tms = FROM_UNIXTIME($time)
  1423. WHERE id = '".Database::escape_string($fieldid)."'";
  1424. $result = Database::query($sql);
  1425. // we create an array with all the options (will be used later in the script)
  1426. if ($fieldtype == self::USER_FIELD_TYPE_DOUBLE_SELECT) {
  1427. $twolist = explode('|', $fieldoptions);
  1428. $counter = 0;
  1429. foreach ($twolist as $individual_list) {
  1430. $splitted_individual_list = split(';', $individual_list);
  1431. foreach ($splitted_individual_list as $individual_list_option) {
  1432. //echo 'counter:'.$counter;
  1433. if ($counter == 0) {
  1434. $list[] = trim($individual_list_option);
  1435. } else {
  1436. $list[] = str_repeat('*', $counter).trim($individual_list_option);
  1437. }
  1438. }
  1439. $counter++;
  1440. }
  1441. } else {
  1442. $templist = split(';', $fieldoptions);
  1443. $list = array_map('trim', $templist);
  1444. }
  1445. // Remove all the field options (and also the choices of the user) that are NOT in the new list of options
  1446. $sql = "SELECT * FROM $table_field_options WHERE option_value NOT IN ('".implode("','", $list)."') AND field_id = '".Database::escape_string($fieldid)."'";
  1447. $result = Database::query($sql);
  1448. $return['deleted_options'] = 0;
  1449. while ($row = Database::fetch_array($result)) {
  1450. // deleting the option
  1451. $sql_delete_option = "DELETE FROM $table_field_options WHERE id='".Database::escape_string($row['id'])."'";
  1452. Database::query($sql_delete_option);
  1453. $return['deleted_options']++;
  1454. // deleting the answer of the user who has chosen this option
  1455. $sql_delete_option_value = "DELETE FROM $table_field_options_values WHERE field_id = '".Database::escape_string($fieldid)."' AND field_value = '".Database::escape_string($row['option_value'])."'";
  1456. Database::query($sql_delete_option_value);
  1457. $return['deleted_option_values'] = $return['deleted_option_values'] + Database::affected_rows();
  1458. }
  1459. // we now try to find the field options that are newly added
  1460. $sql = "SELECT * FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
  1461. $result = Database::query($sql);
  1462. while ($row = Database::fetch_array($result)) {
  1463. // we remove every option that is already in the database from the $list
  1464. if (in_array(trim($row['option_display_text']), $list)) {
  1465. $key = array_search(trim($row['option_display_text']), $list);
  1466. unset($list[$key]);
  1467. }
  1468. }
  1469. // we store the new field options in the database
  1470. foreach ($list as $key => $option) {
  1471. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
  1472. $res = Database::query($sql);
  1473. $max = 1;
  1474. if (Database::num_rows($res) > 0) {
  1475. $row = Database::fetch_array($res);
  1476. $max = $row[0] + 1;
  1477. }
  1478. $time = time();
  1479. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ('".Database::escape_string($fieldid)."','".Database::escape_string($option)."','".Database::escape_string($option)."',$max,FROM_UNIXTIME($time))";
  1480. $result = Database::query($sql);
  1481. }
  1482. return true;
  1483. }
  1484. /**
  1485. * Check if a field is available
  1486. * @param string the wanted fieldname
  1487. * @return boolean true if the wanted username is available
  1488. */
  1489. public static function is_extra_field_available($fieldname) {
  1490. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1491. $sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
  1492. $res = Database::query($sql);
  1493. return Database::num_rows($res) > 0;
  1494. }
  1495. /**
  1496. * Gets user extra fields data
  1497. * @param integer User ID
  1498. * @param boolean Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  1499. * @param boolean Whether to return invisible fields as well
  1500. * @param boolean Whether to split multiple-selection fields or not
  1501. * @return array Array of fields => value for the given user
  1502. */
  1503. public static function get_extra_user_data($user_id, $prefix = false, $all_visibility = true, $splitmultiple = false, $field_filter = null) {
  1504. // A sanity check.
  1505. if (empty($user_id)) {
  1506. $user_id = 0;
  1507. } else {
  1508. if ($user_id != strval(intval($user_id))) return array();
  1509. }
  1510. $extra_data = array();
  1511. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1512. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1513. $user_id = Database::escape_string($user_id);
  1514. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1515. $filter_cond = '';
  1516. if (!$all_visibility) {
  1517. if (isset($field_filter)) {
  1518. $field_filter = intval($field_filter);
  1519. $filter_cond .= " AND field_filter = $field_filter ";
  1520. }
  1521. $sql .= " WHERE f.field_visible = 1 $filter_cond ";
  1522. } else {
  1523. if (isset($field_filter)) {
  1524. $field_filter = intval($field_filter);
  1525. $sql .= " WHERE field_filter = $field_filter ";
  1526. }
  1527. }
  1528. $sql .= " ORDER BY f.field_order";
  1529. $res = Database::query($sql);
  1530. if (Database::num_rows($res) > 0) {
  1531. while ($row = Database::fetch_array($res)) {
  1532. if ($row['type'] == self::USER_FIELD_TYPE_TAG) {
  1533. $tags = self::get_user_tags_to_string($user_id,$row['id'],false);
  1534. $extra_data['extra_'.$row['fvar']] = $tags;
  1535. } else {
  1536. $sqlu = "SELECT field_value as fval FROM $t_ufv WHERE field_id=".$row['id']." AND user_id = ".$user_id;
  1537. $resu = Database::query($sqlu);
  1538. $fval = '';
  1539. // get default value
  1540. $sql_df = "SELECT field_default_value as fval_df " .
  1541. " FROM $t_uf " .
  1542. " WHERE id=".$row['id'];
  1543. $res_df = Database::query($sql_df);
  1544. if (Database::num_rows($resu) > 0) {
  1545. $rowu = Database::fetch_array($resu);
  1546. $fval = $rowu['fval'];
  1547. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  1548. $fval = split(';',$rowu['fval']);
  1549. }
  1550. } else {
  1551. $row_df = Database::fetch_array($res_df);
  1552. $fval = $row_df['fval_df'];
  1553. }
  1554. // We get here (and fill the $extra_data array) even if there is no user with data (we fill it with default values)
  1555. if ($prefix) {
  1556. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  1557. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  1558. } else {
  1559. $extra_data['extra_'.$row['fvar']] = $fval;
  1560. }
  1561. } else {
  1562. if ($row['type'] == self::USER_FIELD_TYPE_RADIO) {
  1563. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  1564. } else {
  1565. $extra_data[$row['fvar']] = $fval;
  1566. }
  1567. }
  1568. }
  1569. }
  1570. }
  1571. return $extra_data;
  1572. }
  1573. /** Get extra user data by field
  1574. * @param int user ID
  1575. * @param string the internal variable name of the field
  1576. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  1577. */
  1578. public static function get_extra_user_data_by_field($user_id, $field_variable, $prefix = false, $all_visibility = true, $splitmultiple = false) {
  1579. // A sanity check.
  1580. if (empty($user_id)) {
  1581. $user_id = 0;
  1582. } else {
  1583. if ($user_id != strval(intval($user_id))) return array();
  1584. }
  1585. $extra_data = array();
  1586. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1587. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1588. $user_id = Database::escape_string($user_id);
  1589. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1590. $sql .= " WHERE f.field_variable = '$field_variable' ";
  1591. if (!$all_visibility) {
  1592. $sql .= " AND f.field_visible = 1 ";
  1593. }
  1594. $sql .= " ORDER BY f.field_order";
  1595. $res = Database::query($sql);
  1596. if (Database::num_rows($res) > 0) {
  1597. while ($row = Database::fetch_array($res)) {
  1598. $sqlu = "SELECT field_value as fval " .
  1599. " FROM $t_ufv " .
  1600. " WHERE field_id=".$row['id']."" .
  1601. " AND user_id=".$user_id;
  1602. $resu = Database::query($sqlu);
  1603. $fval = '';
  1604. if (Database::num_rows($resu) > 0) {
  1605. $rowu = Database::fetch_array($resu);
  1606. $fval = $rowu['fval'];
  1607. if ($row['type'] == self::USER_FIELD_TYPE_SELECT_MULTIPLE) {
  1608. $fval = split(';',$rowu['fval']);
  1609. }
  1610. }
  1611. if ($prefix) {
  1612. $extra_data['extra_'.$row['fvar']] = $fval;
  1613. } else {
  1614. $extra_data[$row['fvar']] = $fval;
  1615. }
  1616. }
  1617. }
  1618. return $extra_data;
  1619. }
  1620. /**
  1621. * Get the extra field information for a certain field (the options as well)
  1622. * @param int The name of the field we want to know everything about
  1623. * @return array Array containing all the information about the extra profile field (first level of array contains field details, then 'options' sub-array contains options details, as returned by the database)
  1624. * @author Julio Montoya
  1625. * @since Dokeos 1.8.6
  1626. */
  1627. public static function get_extra_field_information_by_name($field_variable, $fuzzy = false) {
  1628. // database table definition
  1629. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1630. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1631. // all the information of the field
  1632. $sql = "SELECT * FROM $table_field WHERE field_variable='".Database::escape_string($field_variable)."'";
  1633. $result = Database::query($sql);
  1634. $return = Database::fetch_array($result);
  1635. // all the options of the field
  1636. $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($return['id'])."' ORDER BY option_order ASC";
  1637. $result = Database::query($sql);
  1638. while ($row = Database::fetch_array($result)) {
  1639. $return['options'][$row['id']] = $row;
  1640. }
  1641. return $return;
  1642. }
  1643. public static function get_all_extra_field_by_type($field_type) {
  1644. // database table definition
  1645. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1646. // all the information of the field
  1647. $sql = "SELECT * FROM $table_field WHERE field_type='".Database::escape_string($field_type)."'";
  1648. $result = Database::query($sql);
  1649. $return = array();
  1650. while ($row = Database::fetch_array($result)) {
  1651. $return[] = $row['id'];
  1652. }
  1653. return $return;
  1654. }
  1655. /**
  1656. * Get all the extra field information of a certain field (also the options)
  1657. *
  1658. * @param int $field_name the name of the field we want to know everything of
  1659. * @return array $return containing all th information about the extra profile field
  1660. * @author Julio Montoya
  1661. * @since Dokeos 1.8.6
  1662. */
  1663. public static function get_extra_field_information($field_id) {
  1664. // database table definition
  1665. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1666. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1667. // all the information of the field
  1668. $sql = "SELECT * FROM $table_field WHERE id='".Database::escape_string($field_id)."'";
  1669. $result = Database::query($sql);
  1670. $return = Database::fetch_array($result);
  1671. // all the options of the field
  1672. $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($field_id)."' ORDER BY option_order ASC";
  1673. $result = Database::query($sql);
  1674. while ($row = Database::fetch_array($result)) {
  1675. $return['options'][$row['id']] = $row;
  1676. }
  1677. return $return;
  1678. }
  1679. /** Get extra user data by value
  1680. * @param string the internal variable name of the field
  1681. * @param string the internal value of the field
  1682. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  1683. */
  1684. public static function get_extra_user_data_by_value($field_variable, $field_value, $all_visibility = true) {
  1685. $extra_data = array();
  1686. $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1687. $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1688. $table_user_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1689. $where = '';
  1690. /*
  1691. if (is_array($field_variable_array) && is_array($field_value_array)) {
  1692. if (count($field_variable_array) == count($field_value_array)) {
  1693. $field_var_count = count($field_variable_array);
  1694. for ($i = 0; $i < $field_var_count; $i++) {
  1695. if ($i != 0 && $i != $field_var_count) {
  1696. $where.= ' AND ';
  1697. }
  1698. $where.= "field_variable='".Database::escape_string($field_variable_array[$i])."' AND user_field_options.id='".Database::escape_string($field_value_array[$i])."'";
  1699. }
  1700. }
  1701. }*/
  1702. $where = "field_variable='".Database::escape_string($field_variable)."' AND field_value='".Database::escape_string($field_value)."'";
  1703. $sql = "SELECT user_id FROM $table_user_field user_field INNER JOIN $table_user_field_values user_field_values
  1704. ON (user_field.id = user_field_values.field_id)
  1705. WHERE $where";
  1706. if ($all_visibility) {
  1707. $sql .= " AND user_field.field_visible = 1 ";
  1708. } else {
  1709. $sql .= " AND user_field.field_visible = 0 ";
  1710. }
  1711. $res = Database::query($sql);
  1712. $result_data = array();
  1713. if (Database::num_rows($res) > 0) {
  1714. while ($row = Database::fetch_array($res)) {
  1715. $result_data[] = $row['user_id'];
  1716. }
  1717. }
  1718. return $result_data;
  1719. }
  1720. /**
  1721. * Get extra user data by field variable
  1722. * @param string field variable
  1723. * @return array data
  1724. */
  1725. public static function get_extra_user_data_by_field_variable($field_variable) {
  1726. $tbl_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1727. $extra_information_by_variable = self::get_extra_field_information_by_name($field_variable);
  1728. $field_id = intval($extra_information_by_variable['id']);
  1729. $data = array();
  1730. $sql = "SELECT * FROM $tbl_user_field_values WHERE field_id='$field_id'";
  1731. $rs = Database::query($sql);
  1732. if (Database::num_rows($rs) > 0) {
  1733. while ($row = Database::fetch_array($rs)) {
  1734. $user_id = $row['user_id'];
  1735. $data[$user_id] = $row;
  1736. }
  1737. }
  1738. return $data;
  1739. }
  1740. /**
  1741. * Gives a list of [session_category][session_id] for the current user.
  1742. * @param integer $user_id
  1743. * @param boolean whether to fill the first element or not (to give space for courses out of categories)
  1744. * @param boolean optional true if limit time from session is over, false otherwise
  1745. * @return array list of statuses [session_category][session_id]
  1746. * @todo ensure multiple access urls are managed correctly
  1747. */
  1748. public static function get_sessions_by_category ($user_id, $fill_first = false, $is_time_over = false, $sort_by_session_name = false) {
  1749. // Database Table Definitions
  1750. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  1751. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1752. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1753. if ($user_id != strval(intval($user_id))) return array();
  1754. $categories = array();
  1755. $names = array();
  1756. if ($fill_first) {
  1757. $categories[0] = array();
  1758. }
  1759. // Get the list of sessions where the user is subscribed as student
  1760. $condition_date_end = "";
  1761. if ($is_time_over) {
  1762. $condition_date_end = " AND date_end < CURDATE() AND date_end != '0000-00-00' ";
  1763. } else {
  1764. $condition_date_end = " AND (date_end >= CURDATE() OR date_end = '0000-00-00') ";
  1765. }
  1766. $sessions_sql = "SELECT DISTINCT id, session_category_id, session.name
  1767. FROM $tbl_session_user, $tbl_session
  1768. WHERE id_session=id AND id_user=$user_id $condition_date_end
  1769. ORDER BY session_category_id, date_start, date_end";
  1770. $result = Database::query($sessions_sql);
  1771. if (Database::num_rows($result) > 0) {
  1772. while ($row = Database::fetch_array($result)) {
  1773. $categories[$row['session_category_id']][] = $row['id'];
  1774. $names[$row['id']] = $row['name'];
  1775. }
  1776. }
  1777. // Get the list of sessions where the user is subscribed as coach in a
  1778. // course, from table session_rel_course_rel_user
  1779. $sessions_sql = "SELECT DISTINCT id, session_category_id, session.name
  1780. FROM $tbl_session as session INNER JOIN $tbl_session_course_user as session_rel_course_user
  1781. ON session_rel_course_user.id_session = session.id AND
  1782. session_rel_course_user.id_user = $user_id AND
  1783. session_rel_course_user.status = 2 $condition_date_end
  1784. ORDER BY session_category_id, date_start, date_end";
  1785. $result = Database::query($sessions_sql);
  1786. if (Database::num_rows($result)>0) {
  1787. while ($row = Database::fetch_array($result)) {
  1788. $categories[$row['session_category_id']][] = $row['id'];
  1789. $names[$row['id']] = $row['name'];
  1790. }
  1791. }
  1792. // Get the list of sessions where the user is subscribed as a session coach
  1793. $sessions_sql = "SELECT DISTINCT id, session_category_id, session.name FROM $tbl_session as session
  1794. WHERE session.id_coach = $user_id $condition_date_end
  1795. ORDER BY session_category_id, date_start, date_end";
  1796. $result = Database::query($sessions_sql);
  1797. if (Database::num_rows($result)>0) {
  1798. while ($row = Database::fetch_array($result)) {
  1799. $categories[$row['session_category_id']][] = $row['id'];
  1800. $names[$row['id']] = $row['name'];
  1801. }
  1802. }
  1803. if ($sort_by_session_name) {
  1804. // reorder sessions alphabetically inside categories
  1805. if (!empty($categories)) {
  1806. foreach ($categories as $cat_id => $category) {
  1807. // inside each category, prepare a new empty array to sort sessions
  1808. $new_cat = array();
  1809. if (is_array($category) && !empty($category)) {
  1810. foreach ($category as $session) {
  1811. $new_cat[$names[$session]] = $session;
  1812. }
  1813. uksort($new_cat, 'strnatcmp');
  1814. $categories[$cat_id] = $new_cat;
  1815. }
  1816. }
  1817. }
  1818. }
  1819. return $categories;
  1820. }
  1821. /**
  1822. * Gives a list of [session_id-course_code] => [status] for the current user.
  1823. * @param integer $user_id
  1824. * @return array list of statuses (session_id-course_code => status)
  1825. */
  1826. public static function get_personal_session_course_list($user_id) {
  1827. // Database Table Definitions
  1828. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1829. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1830. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1831. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1832. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  1833. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1834. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1835. if ($user_id != strval(intval($user_id))) return array();
  1836. //we filter the courses from the URL
  1837. $join_access_url = $where_access_url = '';
  1838. if (api_get_multiple_access_url()) {
  1839. $access_url_id = api_get_current_access_url_id();
  1840. if ($access_url_id != -1) {
  1841. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1842. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  1843. $where_access_url = " AND access_url_id = $access_url_id ";
  1844. }
  1845. }
  1846. //Courses in which we suscribed out of any session
  1847. $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  1848. $personal_course_list_sql = "SELECT course.code, course_rel_user.status course_rel_status, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
  1849. FROM ".$tbl_course_user." course_rel_user
  1850. LEFT JOIN ".$tbl_course." course
  1851. ON course.code = course_rel_user.course_code
  1852. LEFT JOIN ".$tbl_user_course_category." user_course_category
  1853. ON course_rel_user.user_course_cat = user_course_category.id
  1854. $join_access_url
  1855. WHERE course_rel_user.user_id = '".$user_id."' AND
  1856. course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH." $where_access_url
  1857. ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
  1858. $course_list_sql_result = Database::query($personal_course_list_sql);
  1859. $personal_course_list = array();
  1860. if (Database::num_rows($course_list_sql_result) > 0 ) {
  1861. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  1862. $course_info = api_get_course_info($result_row['code']);
  1863. $result_row['course_info'] = $course_info;
  1864. $personal_course_list[] = $result_row;
  1865. }
  1866. }
  1867. // get the list of sessions where the user is subscribed as student
  1868. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
  1869. FROM $tbl_session_user, $tbl_session
  1870. WHERE id_session=id AND
  1871. id_user=$user_id AND
  1872. relation_type<>".SESSION_RELATION_TYPE_RRHH." AND
  1873. (date_start <= CURDATE() AND date_end >= CURDATE() OR date_start='0000-00-00')
  1874. ORDER BY date_start, date_end, name";
  1875. $result = Database::query($sessions_sql);
  1876. $sessions = Database::store_result($result, 'ASSOC');
  1877. // get the list of sessions where the user is subscribed as student where visibility = SESSION_VISIBLE_READ_ONLY = 1 SESSION_VISIBLE = 2
  1878. $sessions_out_date_sql = "SELECT DISTINCT id, name, date_start, date_end
  1879. FROM $tbl_session_user, $tbl_session
  1880. WHERE id_session=id AND id_user=$user_id AND
  1881. relation_type<>".SESSION_RELATION_TYPE_RRHH." AND
  1882. (date_end <= CURDATE() AND date_end<>'0000-00-00') AND (visibility = ".SESSION_VISIBLE_READ_ONLY." || visibility = ".SESSION_VISIBLE.")
  1883. ORDER BY date_start, date_end, name";
  1884. $result_out_date = Database::query($sessions_out_date_sql);
  1885. $sessions_out_date = Database::store_result($result_out_date, 'ASSOC');
  1886. $sessions = array_merge($sessions , $sessions_out_date);
  1887. // get the list of sessions where the user is subscribed as coach in a course
  1888. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end, DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY), ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY)
  1889. FROM $tbl_session as session
  1890. INNER JOIN $tbl_session_course_user as session_rel_course_user
  1891. ON session_rel_course_user.id_session = session.id
  1892. AND session_rel_course_user.id_user = $user_id AND session_rel_course_user.status = 2
  1893. WHERE (
  1894. CURDATE() >= DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY) AND
  1895. CURDATE() <= ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY) OR
  1896. date_start='0000-00-00'
  1897. )
  1898. ORDER BY date_start, date_end, name";
  1899. $result = Database::query($sessions_sql);
  1900. $session_is_coach = Database::store_result($result, 'ASSOC');
  1901. $sessions = array_merge($sessions, $session_is_coach);
  1902. // get the list of sessions where the user is subscribed as coach
  1903. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
  1904. FROM $tbl_session as session
  1905. WHERE session.id_coach = $user_id
  1906. AND (CURDATE() >= DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY)
  1907. AND CURDATE() <= ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY)
  1908. OR date_start='0000-00-00')
  1909. ORDER BY date_start, date_end, name";
  1910. $result = Database::query($sessions_sql);
  1911. $sessions = array_merge($sessions, Database::store_result($result,'ASSOC'));
  1912. if (api_is_allowed_to_create_course()) {
  1913. foreach($sessions as $enreg) {
  1914. $id_session = $enreg['id'];
  1915. $personal_course_list_sql = "SELECT DISTINCT course.code k, course.title i,
  1916. ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t, email, course.course_language l, 1 sort,
  1917. category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name
  1918. FROM $tbl_session_course_user as session_course_user
  1919. INNER JOIN $tbl_course AS course
  1920. ON course.code = session_course_user.course_code
  1921. INNER JOIN $tbl_session as session
  1922. ON session.id = session_course_user.id_session
  1923. LEFT JOIN $tbl_user as user
  1924. ON user.user_id = session_course_user.id_user
  1925. WHERE session_course_user.id_session = $id_session
  1926. AND ((session_course_user.id_user=$user_id AND session_course_user.status = 2) OR session.id_coach=$user_id)
  1927. ORDER BY i";
  1928. $course_list_sql_result = Database::query($personal_course_list_sql);
  1929. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  1930. $result_row['course_info'] = api_get_course_info($result_row['code']);
  1931. $key = $result_row['id_session'].' - '.$result_row['code'];
  1932. $personal_course_list[$key] = $result_row;
  1933. }
  1934. }
  1935. }
  1936. foreach ($sessions as $enreg) {
  1937. $id_session = $enreg['id'];
  1938. // this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
  1939. $personal_course_list_sql = "SELECT DISTINCT course.code k, course.title i, CONCAT(user.lastname,' ',user.firstname) t, email,
  1940. course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, " .
  1941. "IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5')
  1942. FROM $tbl_session_course_user as session_course_user
  1943. INNER JOIN $tbl_course AS course
  1944. ON course.code = session_course_user.course_code AND session_course_user.id_session = $id_session
  1945. INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
  1946. LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
  1947. WHERE session_course_user.id_user = $user_id ORDER BY i";
  1948. $course_list_sql_result = Database::query($personal_course_list_sql);
  1949. while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
  1950. $result_row['course_info'] = api_get_course_info($result_row['code']);
  1951. $key = $result_row['id_session'].' - '.$result_row['k'];
  1952. if (!isset($personal_course_list[$key])) {
  1953. $personal_course_list[$key] = $result_row;
  1954. }
  1955. }
  1956. }
  1957. return $personal_course_list;
  1958. }
  1959. /**
  1960. * Gives a list of courses for the given user in the given session
  1961. * @param integer $user_id
  1962. * @return array list of statuses (session_id-course_code => status)
  1963. */
  1964. public static function get_courses_list_by_session($user_id, $session_id) {
  1965. // Database Table Definitions
  1966. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1967. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1968. $user_id = intval($user_id);
  1969. $session_id = intval($session_id);
  1970. //we filter the courses from the URL
  1971. $join_access_url=$where_access_url='';
  1972. if (api_get_multiple_access_url()) {
  1973. $access_url_id = api_get_current_access_url_id();
  1974. if ($access_url_id != -1) {
  1975. $tbl_url_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1976. $join_access_url= " , $tbl_url_session url_rel_session ";
  1977. $where_access_url=" AND access_url_id = $access_url_id AND url_rel_session.session_id = $session_id ";
  1978. }
  1979. }
  1980. // variable initialisation
  1981. $personal_course_list_sql = '';
  1982. $personal_course_list = array();
  1983. $courses = array();
  1984. // this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
  1985. $personal_course_list_sql = "SELECT DISTINCT scu.course_code as code FROM $tbl_session_course_user as scu $join_access_url
  1986. WHERE scu.id_user = $user_id AND scu.id_session = $session_id $where_access_url
  1987. ORDER BY code";
  1988. $course_list_sql_result = Database::query($personal_course_list_sql);
  1989. if (Database::num_rows($course_list_sql_result) > 0) {
  1990. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1991. $result_row['status'] = 5;
  1992. if (!in_array($result_row['code'], $courses)) {
  1993. $personal_course_list[] = $result_row;
  1994. $courses[] = $result_row['code'];
  1995. }
  1996. }
  1997. }
  1998. if (api_is_allowed_to_create_course()) {
  1999. $personal_course_list_sql = "SELECT DISTINCT scu.course_code as code FROM $tbl_session_course_user as scu, $tbl_session as s $join_access_url
  2000. WHERE s.id = $session_id AND scu.id_session = s.id AND ((scu.id_user=$user_id AND scu.status=2) OR s.id_coach = $user_id)
  2001. $where_access_url
  2002. ORDER BY code";
  2003. $course_list_sql_result = Database::query($personal_course_list_sql);
  2004. if (Database::num_rows($course_list_sql_result)>0) {
  2005. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  2006. $result_row['status'] = 2;
  2007. if (!in_array($result_row['code'],$courses)) {
  2008. $personal_course_list[] = $result_row;
  2009. $courses[] = $result_row['code'];
  2010. }
  2011. }
  2012. }
  2013. }
  2014. if (api_is_drh()) {
  2015. $session_list = SessionManager::get_sessions_followed_by_drh($user_id);
  2016. $session_list = array_keys($session_list);
  2017. if (in_array($session_id, $session_list)) {
  2018. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  2019. if (!empty($course_list)) {
  2020. foreach ($course_list as $course) {
  2021. $personal_course_list[] = $course;
  2022. }
  2023. }
  2024. }
  2025. }
  2026. return $personal_course_list;
  2027. }
  2028. /**
  2029. * Get user id from a username
  2030. * @param string Username
  2031. * @return int User ID (or false if not found)
  2032. */
  2033. public static function get_user_id_from_username($username) {
  2034. if (empty($username)) {
  2035. return false;
  2036. }
  2037. $username = Database::escape_string($username);
  2038. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  2039. $sql = "SELECT user_id FROM $t_user WHERE username = '$username'";
  2040. $res = Database::query($sql);
  2041. if ($res === false) { return false; }
  2042. if (Database::num_rows($res) !== 1) { return false; }
  2043. $row = Database::fetch_array($res);
  2044. return $row['user_id'];
  2045. }
  2046. /**
  2047. * Get the users files upload from his share_folder
  2048. * @param string User ID
  2049. * @param string course directory
  2050. * @param string resourcetype: images, all
  2051. * @return int User ID (or false if not found)
  2052. */
  2053. public static function get_user_upload_files_by_course($user_id, $course, $resourcetype='all') {
  2054. $return = '';
  2055. if (!empty($user_id) && !empty($course)) {
  2056. $user_id = intval($user_id);
  2057. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  2058. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  2059. $file_list = array();
  2060. if (is_dir($path)) {
  2061. $handle = opendir($path);
  2062. while ($file = readdir($handle)) {
  2063. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
  2064. continue; // skip current/parent directory and .htaccess
  2065. }
  2066. $file_list[] = $file;
  2067. }
  2068. if (count($file_list) > 0) {
  2069. $return = $course;
  2070. $return .= '<ul>';
  2071. }
  2072. foreach ($file_list as $file) {
  2073. if($resourcetype=="all")
  2074. {
  2075. $return .= '<li><a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  2076. }
  2077. elseif($resourcetype=="images")
  2078. {
  2079. //get extension
  2080. $ext = explode('.', $file);
  2081. if($ext[1]=='jpg' || $ext[1]=='jpeg'|| $ext[1]=='png' || $ext[1]=='gif' || $ext[1]=='bmp' || $ext[1]=='tif')
  2082. {
  2083. $return .= '<li style="display:inline;"><a href="'.$web_path.urlencode($file).'" target="_blank"><img src="'.$web_path.urlencode($file).'" width="80" height="60"></a>';
  2084. }
  2085. }
  2086. }
  2087. if (count($file_list) > 0) {
  2088. $return .= '</ul>';
  2089. }
  2090. }
  2091. }
  2092. return $return;
  2093. }
  2094. /**
  2095. * Gets the API key (or keys) and return them into an array
  2096. * @param int Optional user id (defaults to the result of api_get_user_id())
  2097. * @return array Non-indexed array containing the list of API keys for this user, or FALSE on error
  2098. */
  2099. public static function get_api_keys($user_id = null, $api_service = 'dokeos') {
  2100. if ($user_id != strval(intval($user_id))) return false;
  2101. if (empty($user_id)) { $user_id = api_get_user_id(); }
  2102. if ($user_id === false) return false;
  2103. $service_name = Database::escape_string($api_service);
  2104. if (is_string($service_name) === false) { return false;}
  2105. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2106. $sql = "SELECT * FROM $t_api WHERE user_id = $user_id AND api_service='$api_service';";
  2107. $res = Database::query($sql);
  2108. if ($res === false) return false; //error during query
  2109. $num = Database::num_rows($res);
  2110. if ($num == 0) return false;
  2111. $list = array();
  2112. while ($row = Database::fetch_array($res)) {
  2113. $list[$row['id']] = $row['api_key'];
  2114. }
  2115. return $list;
  2116. }
  2117. /**
  2118. * Adds a new API key to the users' account
  2119. * @param int Optional user ID (defaults to the results of api_get_user_id())
  2120. * @return boolean True on success, false on failure
  2121. */
  2122. public static function add_api_key($user_id = null, $api_service = 'dokeos') {
  2123. if ($user_id != strval(intval($user_id))) return false;
  2124. if (empty($user_id)) { $user_id = api_get_user_id(); }
  2125. if ($user_id === false) return false;
  2126. $service_name = Database::escape_string($api_service);
  2127. if (is_string($service_name) === false) { return false; }
  2128. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2129. $md5 = md5((time() + ($user_id * 5)) - rand(10000, 10000)); //generate some kind of random key
  2130. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  2131. $res = Database::query($sql);
  2132. if ($res === false) return false; //error during query
  2133. $num = Database::insert_id();
  2134. return ($num == 0) ? false : $num;
  2135. }
  2136. /**
  2137. * Deletes an API key from the user's account
  2138. * @param int API key's internal ID
  2139. * @return boolean True on success, false on failure
  2140. */
  2141. public static function delete_api_key($key_id) {
  2142. if ($key_id != strval(intval($key_id))) return false;
  2143. if ($key_id === false) return false;
  2144. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2145. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  2146. $res = Database::query($sql);
  2147. if ($res === false) return false; //error during query
  2148. $num = Database::num_rows($res);
  2149. if ($num !== 1) return false;
  2150. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  2151. $res = Database::query($sql);
  2152. if ($res === false) return false; //error during query
  2153. return true;
  2154. }
  2155. /**
  2156. * Regenerate an API key from the user's account
  2157. * @param int user ID (defaults to the results of api_get_user_id())
  2158. * @param string API key's internal ID
  2159. * @return int num
  2160. */
  2161. public static function update_api_key($user_id, $api_service) {
  2162. if ($user_id != strval(intval($user_id))) return false;
  2163. if ($user_id === false) return false;
  2164. $service_name = Database::escape_string($api_service);
  2165. if (is_string($service_name) === false) { return false; }
  2166. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2167. $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  2168. $res = Database::query($sql);
  2169. $num = Database::num_rows($res);
  2170. if ($num == 1) {
  2171. $id_key = Database::fetch_array($res, 'ASSOC');
  2172. self::delete_api_key($id_key['id']);
  2173. $num = self::add_api_key($user_id, $api_service);
  2174. } elseif ($num == 0) {
  2175. $num = self::add_api_key($user_id);
  2176. }
  2177. return $num;
  2178. }
  2179. /**
  2180. * @param int user ID (defaults to the results of api_get_user_id())
  2181. * @param string API key's internal ID
  2182. * @return int row ID, or return false if not found
  2183. */
  2184. public static function get_api_key_id($user_id, $api_service) {
  2185. if ($user_id != strval(intval($user_id))) return false;
  2186. if ($user_id === false) return false;
  2187. if (empty($api_service)) return false;
  2188. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  2189. $service_name = Database::escape_string($api_service);
  2190. $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  2191. $res = Database::query($sql);
  2192. if (Database::num_rows($res)<1) {
  2193. return false;
  2194. }
  2195. $row = Database::fetch_array($res, 'ASSOC');
  2196. return $row['id'];
  2197. }
  2198. /**
  2199. * Checks if a user_id is platform admin
  2200. * @param int user ID
  2201. * @return boolean True if is admin, false otherwise
  2202. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  2203. */
  2204. public static function is_admin($user_id) {
  2205. if (empty($user_id) or $user_id != strval(intval($user_id))) { return false; }
  2206. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  2207. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  2208. $res = Database::query($sql);
  2209. return Database::num_rows($res) === 1;
  2210. }
  2211. /**
  2212. * Get the total count of users
  2213. * @param int Status of users to be counted
  2214. * @param int Access URL ID (optional)
  2215. * @return mixed Number of users or false on error
  2216. */
  2217. public static function get_number_of_users($status=0, $access_url_id=null) {
  2218. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  2219. $t_a = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2220. $sql = "SELECT count(*) FROM $t_u u";
  2221. $sql2 = '';
  2222. if (is_int($status) && $status>0) {
  2223. $sql2 .= " WHERE u.status = $status ";
  2224. }
  2225. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  2226. $sql .= ", $t_a a ";
  2227. $sql2 .= " AND a.access_url_id = $access_url_id AND u.user_id = a.user_id ";
  2228. }
  2229. $sql = $sql.$sql2;
  2230. $res = Database::query($sql);
  2231. if (Database::num_rows($res) === 1) {
  2232. return (int) Database::result($res, 0, 0);
  2233. }
  2234. return false;
  2235. }
  2236. /**
  2237. * Resize a picture
  2238. *
  2239. * @param string file picture
  2240. * @param int size in pixels
  2241. * @todo move this function somewhere else image.lib?
  2242. * @return obj image object
  2243. */
  2244. public static function resize_picture($file, $max_size_for_picture) {
  2245. $temp = null;
  2246. if (file_exists($file)) {
  2247. $temp = new Image($file);
  2248. $image_size = $temp->get_image_size($file);
  2249. $width = $image_size['width'];
  2250. $height = $image_size['height'];
  2251. if ($width >= $height) {
  2252. if ($width >= $max_size_for_picture) {
  2253. // scale height
  2254. $new_height = round($height * ($max_size_for_picture / $width));
  2255. $temp->resize($max_size_for_picture, $new_height, 0);
  2256. }
  2257. } else { // height > $width
  2258. if ($height >= $max_size_for_picture) {
  2259. // scale width
  2260. $new_width = round($width * ($max_size_for_picture / $height));
  2261. $temp->resize($new_width, $max_size_for_picture, 0);
  2262. }
  2263. }
  2264. }
  2265. return $temp;
  2266. }
  2267. /**
  2268. * Gets the current user image
  2269. * @param string user id
  2270. * @param string picture user name
  2271. * @param string height
  2272. * @param string picture size it can be USER_IMAGE_SIZE_SMALL, USER_IMAGE_SIZE_MEDIUM, USER_IMAGE_SIZE_BIG or USER_IMAGE_SIZE_ORIGINAL
  2273. * @param string style css
  2274. * @return array with the file and the style of an image i.e $array['file'] $array['style']
  2275. */
  2276. public static function get_picture_user($user_id, $picture_file, $height, $size_picture = USER_IMAGE_SIZE_MEDIUM , $style = '') {
  2277. $picture = array();
  2278. $picture['style'] = $style;
  2279. if ($picture_file == 'unknown.jpg') {
  2280. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/'.$picture_file;
  2281. return $picture;
  2282. }
  2283. switch ($size_picture) {
  2284. case USER_IMAGE_SIZE_ORIGINAL :
  2285. $size_picture = '';
  2286. break;
  2287. case USER_IMAGE_SIZE_BIG :
  2288. $size_picture = 'big_';
  2289. break;
  2290. case USER_IMAGE_SIZE_MEDIUM :
  2291. $size_picture = 'medium_';
  2292. break;
  2293. case USER_IMAGE_SIZE_SMALL :
  2294. $size_picture = 'small_';
  2295. break;
  2296. default:
  2297. $size_picture = 'medium_';
  2298. }
  2299. $image_array_sys = self::get_user_picture_path_by_id($user_id, 'system', false, true);
  2300. $image_array = self::get_user_picture_path_by_id($user_id, 'web', false, true);
  2301. $file = $image_array_sys['dir'].$size_picture.$picture_file;
  2302. if (file_exists($file)) {
  2303. $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
  2304. $picture['style'] = '';
  2305. if ($height > 0) {
  2306. $dimension = api_getimagesize($picture['file']);
  2307. $margin = (($height - $dimension['width']) / 2);
  2308. //@ todo the padding-top should not be here
  2309. $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension['width'].'px; height:'.$dimension['height'].'px;" ';
  2310. $picture['original_height'] = $dimension['width'];
  2311. $picture['original_width'] = $dimension['height'];
  2312. }
  2313. } else {
  2314. $file = $image_array_sys['dir'].$picture_file;
  2315. if (file_exists($file) && !is_dir($file)) {
  2316. $picture['file'] = $image_array['dir'].$picture_file;
  2317. } else {
  2318. switch ($size_picture) {
  2319. case 'big_' :
  2320. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break;
  2321. case 'medium_' :
  2322. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_50_50.jpg'; break;
  2323. case 'small_' :
  2324. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break;
  2325. default:
  2326. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; break;
  2327. }
  2328. }
  2329. }
  2330. return $picture;
  2331. }
  2332. /**
  2333. * @author Isaac flores <isaac.flores@dokeos.com>
  2334. * @param string The email administrator
  2335. * @param integer The user id
  2336. * @param string The message title
  2337. * @param string The content message
  2338. */
  2339. public static function send_message_in_outbox($email_administrator, $user_id, $title, $content) {
  2340. $table_message = Database::get_main_table(TABLE_MESSAGE);
  2341. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2342. $title = api_utf8_decode($title);
  2343. $content = api_utf8_decode($content);
  2344. $email_administrator = Database::escape_string($email_administrator);
  2345. //message in inbox
  2346. $sql_message_outbox = 'SELECT user_id from '.$table_user.' WHERE email="'.$email_administrator.'" ';
  2347. //$num_row_query = Database::num_rows($sql_message_outbox);
  2348. $res_message_outbox = Database::query($sql_message_outbox);
  2349. $array_users_administrator = array();
  2350. while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) {
  2351. $array_users_administrator[] = $row_message_outbox['user_id'];
  2352. }
  2353. //allow to insert messages in outbox
  2354. for ($i = 0; $i < count($array_users_administrator); $i++) {
  2355. $sql_insert_outbox = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
  2356. " VALUES (".
  2357. "'".(int)$user_id."', '".(int)($array_users_administrator[$i])."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
  2358. ")";
  2359. $rs = Database::query($sql_insert_outbox);
  2360. }
  2361. }
  2362. /*
  2363. *
  2364. * USER TAGS
  2365. *
  2366. * Intructions to create a new user tag by Julio Montoya <gugli100@gmail.com>
  2367. *
  2368. * 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.
  2369. * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags.
  2370. * 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
  2371. * 4. Tags are independent this means that tags can't be shared between tags + book + hobbies.
  2372. * 5. Test and enjoy.
  2373. *
  2374. */
  2375. /**
  2376. * Gets the tags of a specific field_id
  2377. *
  2378. * @param int field_id
  2379. * @param string how we are going to result value in array or in a string (json)
  2380. * @return mixed
  2381. * @since Nov 2009
  2382. * @version 1.8.6.2
  2383. */
  2384. public static function get_tags($tag, $field_id, $return_format='json',$limit=10) {
  2385. // database table definition
  2386. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2387. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2388. $field_id = intval($field_id);
  2389. $limit = intval($limit);
  2390. $tag = trim(Database::escape_string($tag));
  2391. // all the information of the field
  2392. $sql = "SELECT id, tag from $table_user_tag
  2393. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit";
  2394. $result = Database::query($sql);
  2395. $return = array();
  2396. if (Database::num_rows($result)>0) {
  2397. while ($row = Database::fetch_array($result,'ASSOC')) {
  2398. $return[] = array('caption'=>$row['tag'], 'value'=>$row['tag']);
  2399. }
  2400. }
  2401. if ($return_format=='json') {
  2402. $return = json_encode($return);
  2403. }
  2404. return $return;
  2405. }
  2406. public static function get_top_tags($field_id, $limit=100) {
  2407. // database table definition
  2408. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2409. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2410. $field_id = intval($field_id);
  2411. $limit = intval($limit);
  2412. // all the information of the field
  2413. $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv INNER JOIN $table_user_tag ut ON(ut.id = uv.tag_id)
  2414. WHERE field_id = $field_id GROUP BY tag_id ORDER BY count DESC LIMIT $limit";
  2415. $result = Database::query($sql);
  2416. $return = array();
  2417. if (Database::num_rows($result)>0) {
  2418. while ($row = Database::fetch_array($result,'ASSOC')) {
  2419. $return[] = $row;
  2420. }
  2421. }
  2422. return $return;
  2423. }
  2424. /**
  2425. * Get user's tags
  2426. * @param int field_id
  2427. * @param int user_id
  2428. * @return array
  2429. */
  2430. public static function get_user_tags($user_id,$field_id) {
  2431. // database table definition
  2432. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2433. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2434. $field_id = intval($field_id);
  2435. $user_id = intval($user_id);
  2436. // all the information of the field
  2437. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID)
  2438. WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag";
  2439. $result = Database::query($sql);
  2440. $return = array();
  2441. if (Database::num_rows($result)> 0) {
  2442. while ($row = Database::fetch_array($result,'ASSOC')) {
  2443. $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']);
  2444. }
  2445. }
  2446. return $return;
  2447. }
  2448. /**
  2449. * Get user's tags
  2450. * @param int user_id
  2451. * @param int field_id
  2452. * @param bool show links or not
  2453. * @return array
  2454. */
  2455. public static function get_user_tags_to_string($user_id,$field_id,$show_links=true) {
  2456. // database table definition
  2457. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2458. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2459. $field_id = intval($field_id);
  2460. $user_id = intval($user_id);
  2461. // all the information of the field
  2462. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID)
  2463. WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag";
  2464. $result = Database::query($sql);
  2465. $return = array();
  2466. if (Database::num_rows($result)> 0) {
  2467. while ($row = Database::fetch_array($result,'ASSOC')) {
  2468. $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']);
  2469. }
  2470. }
  2471. $user_tags = $return;
  2472. $tag_tmp = array();
  2473. foreach ($user_tags as $tag) {
  2474. if ($show_links) {
  2475. $tag_tmp[] = '<a href="'.api_get_path(WEB_PATH).'main/search/?q='.$tag['tag'].'">'.$tag['tag'].'</a>';
  2476. } else {
  2477. $tag_tmp[] = $tag['tag'];
  2478. }
  2479. }
  2480. if (is_array($user_tags) && count($user_tags)>0) {
  2481. $return = implode(', ',$tag_tmp);
  2482. } else {
  2483. return '';
  2484. }
  2485. return $return;
  2486. }
  2487. /**
  2488. * Get the tag id
  2489. * @param int tag
  2490. * @param int field_id
  2491. * @return int returns 0 if fails otherwise the tag id
  2492. */
  2493. public function get_tag_id($tag, $field_id) {
  2494. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2495. $tag = Database::escape_string($tag);
  2496. $field_id = intval($field_id);
  2497. //with COLLATE latin1_bin to select query in a case sensitive mode
  2498. $sql = "SELECT id FROM $table_user_tag WHERE tag COLLATE latin1_bin LIKE '$tag' AND field_id = $field_id";
  2499. $result = Database::query($sql);
  2500. if (Database::num_rows($result)>0) {
  2501. $row = Database::fetch_array($result,'ASSOC');
  2502. return $row['id'];
  2503. } else {
  2504. return 0;
  2505. }
  2506. }
  2507. /**
  2508. * Get the tag id
  2509. * @param int tag
  2510. * @param int field_id
  2511. * @return int 0 if fails otherwise the tag id
  2512. */
  2513. public function get_tag_id_from_id($tag_id, $field_id) {
  2514. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2515. $tag_id = intval($tag_id);
  2516. $field_id = intval($field_id);
  2517. $sql = "SELECT id FROM $table_user_tag WHERE id = '$tag_id' AND field_id = $field_id";
  2518. $result = Database::query($sql);
  2519. if (Database::num_rows($result)>0) {
  2520. $row = Database::fetch_array($result,'ASSOC');
  2521. return $row['id'];
  2522. } else {
  2523. return false;
  2524. }
  2525. }
  2526. /**
  2527. * Adds a user-tag value
  2528. * @param mixed tag
  2529. * @param int The user id
  2530. * @param int field id of the tag
  2531. * @return bool
  2532. */
  2533. public function add_tag($tag, $user_id, $field_id) {
  2534. // database table definition
  2535. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2536. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2537. $tag = Database::escape_string($tag);
  2538. $tag = trim($tag);
  2539. $user_id = intval($user_id);
  2540. $field_id = intval($field_id);
  2541. $tag_id = UserManager::get_tag_id($tag,$field_id);
  2542. /* IMPORTANT
  2543. * @todo we don't create tags with numbers
  2544. *
  2545. */
  2546. if (is_numeric($tag)) {
  2547. //the form is sending an id this means that the user select it from the list so it MUST exists
  2548. /*$new_tag_id = UserManager::get_tag_id_from_id($tag,$field_id);
  2549. if ($new_tag_id !== false) {
  2550. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id";
  2551. $result = Database::query($sql);
  2552. $last_insert_id = $new_tag_id;
  2553. } else {
  2554. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  2555. $result = Database::query($sql);
  2556. $last_insert_id = Database::get_last_insert_id();
  2557. }*/
  2558. } else {
  2559. //this is a new tag
  2560. if ($tag_id == 0) {
  2561. //the tag doesn't exist
  2562. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  2563. $result = Database::query($sql);
  2564. $last_insert_id = Database::get_last_insert_id();
  2565. } else {
  2566. //the tag exists we update it
  2567. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $tag_id";
  2568. $result = Database::query($sql);
  2569. $last_insert_id = $tag_id;
  2570. }
  2571. }
  2572. if (!empty($last_insert_id) && ($last_insert_id!=0)) {
  2573. //we insert the relationship user-tag
  2574. $sql_select ="SELECT tag_id FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $last_insert_id ";
  2575. $result = Database::query($sql_select);
  2576. //if the relationship does not exist we create it
  2577. if (Database::num_rows($result)==0) {
  2578. $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
  2579. $result = Database::query($sql);
  2580. }
  2581. }
  2582. }
  2583. /**
  2584. * Deletes an user tag
  2585. * @param int user id
  2586. * @param int field id
  2587. *
  2588. */
  2589. public function delete_user_tags($user_id, $field_id) {
  2590. // database table definition
  2591. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2592. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2593. $tags = UserManager::get_user_tags($user_id, $field_id);
  2594. //echo '<pre>';var_dump($tags);
  2595. if(is_array($tags) && count($tags)>0) {
  2596. foreach ($tags as $key=>$tag) {
  2597. if ($tag['count']>'0') {
  2598. $sql = "UPDATE $table_user_tag SET count = count - 1 WHERE id = $key ";
  2599. $result = Database::query($sql);
  2600. }
  2601. $sql = "DELETE FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $key";
  2602. $result = Database::query($sql);
  2603. }
  2604. }
  2605. }
  2606. /**
  2607. * Process the tag list comes from the UserManager::update_extra_field_value() function
  2608. * @param array the tag list that will be added
  2609. * @param int user id
  2610. * @param int field id
  2611. * @return bool
  2612. */
  2613. public function process_tags($tags, $user_id, $field_id) {
  2614. //We loop the tags and add it to the DB
  2615. if (is_array($tags)) {
  2616. foreach($tags as $tag) {
  2617. UserManager::add_tag($tag, $user_id, $field_id);
  2618. }
  2619. } else {
  2620. UserManager::add_tag($tags,$user_id, $field_id);
  2621. }
  2622. return true;
  2623. }
  2624. /**
  2625. * Returns a list of all admninistrators
  2626. * @author jmontoya
  2627. * @return array
  2628. */
  2629. public function get_all_administrators() {
  2630. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2631. $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  2632. $sql = "SELECT user_id, username, firstname, lastname, email from $table_user as u, $table_admin as a WHERE u.user_id=a.user_id";
  2633. $result = Database::query($sql);
  2634. $return = array();
  2635. if (Database::num_rows($result)> 0) {
  2636. while ($row = Database::fetch_array($result,'ASSOC')) {
  2637. $return[$row['user_id']] = $row;
  2638. }
  2639. }
  2640. return $return;
  2641. }
  2642. /**
  2643. * Searchs an user (tags, firstname, lastname and email )
  2644. * @param string the tag
  2645. * @param int field id of the tag
  2646. * @param int where to start in the query
  2647. * @param int number of items
  2648. * @return array
  2649. */
  2650. public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10) {
  2651. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  2652. $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
  2653. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2654. $tag = Database::escape_string($tag);
  2655. $field_id = intval($field_id);
  2656. $from = intval($from);
  2657. $number_of_items = intval($number_of_items);
  2658. $where_field = "";
  2659. if ($field_id != 0) {
  2660. $where_field = " field_id = $field_id AND ";
  2661. }
  2662. // all the information of the field
  2663. $sql = "SELECT u.user_id,u.username,firstname, lastname, email, tag, picture_uri FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.id)
  2664. INNER JOIN $user_table u ON(uv.user_id =u.user_id)
  2665. WHERE $where_field tag LIKE '$tag%' ORDER BY tag";
  2666. $sql .= " LIMIT $from,$number_of_items";
  2667. $result = Database::query($sql);
  2668. $return = array();
  2669. if (Database::num_rows($result) > 0) {
  2670. while ($row = Database::fetch_array($result,'ASSOC')) {
  2671. if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
  2672. $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'] , api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'] , array('class'=>'tag'));
  2673. } else {
  2674. $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class'=>'tag'));
  2675. }
  2676. $return[$row['user_id']] = $row;
  2677. }
  2678. }
  2679. $keyword = $tag;
  2680. $sql = "SELECT u.user_id, u.username, firstname, lastname, email, picture_uri FROM $user_table u";
  2681. if (api_get_multiple_access_url()) {
  2682. $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2683. $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
  2684. }
  2685. if (isset ($keyword)) {
  2686. $keyword = Database::escape_string($keyword);
  2687. //OR u.official_code LIKE '%".$keyword."%'
  2688. // OR u.email LIKE '%".$keyword."%'
  2689. $sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%' OR u.username LIKE '%".$keyword."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$keyword."%' OR concat(u.lastname,' ',u.firstname) LIKE '%".$keyword."%' )";
  2690. }
  2691. $keyword_active = true;
  2692. //only active users
  2693. if ($keyword_active) {
  2694. $sql .= " AND u.active='1'";
  2695. }
  2696. //avoid anonymous
  2697. $sql .= " AND u.status <> 6 ";
  2698. // adding the filter to see the user's only of the current access_url
  2699. if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
  2700. $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
  2701. }
  2702. $direction = 'ASC';
  2703. if (!in_array($direction, array('ASC','DESC'))) {
  2704. $direction = 'ASC';
  2705. }
  2706. //$column = intval($column);
  2707. $from = intval($from);
  2708. $number_of_items = intval($number_of_items);
  2709. //$sql .= " ORDER BY col$column $direction ";
  2710. $sql .= " LIMIT $from,$number_of_items";
  2711. $res = Database::query($sql);
  2712. if (Database::num_rows($res)> 0) {
  2713. while ($row = Database::fetch_array($res,'ASSOC')) {
  2714. if (!in_array($row['user_id'], array_keys($return))) {
  2715. $return[$row['user_id']] = $row;
  2716. }
  2717. }
  2718. }
  2719. return $return;
  2720. }
  2721. /**
  2722. * Show the search form
  2723. * @param string the value of the search box
  2724. *
  2725. */
  2726. public static function get_search_form($query) {
  2727. return '
  2728. <form method="GET" class="well form-search" action="'.api_get_path(WEB_PATH).'main/social/search.php">
  2729. <input placeholder="'.get_lang('UsersGroups').'" type="text" class="input-medium" value="'.api_htmlentities(Security::remove_XSS($query)).'" name="q"/> &nbsp;
  2730. <button class="btn" type="submit" value="search">'.get_lang('Search').'</button>
  2731. </form>';
  2732. }
  2733. /**
  2734. * Shows the user menu
  2735. */
  2736. public static function show_menu(){
  2737. echo '<div class="actions">';
  2738. echo '<a href="/main/auth/profile.php">'. Display::return_icon('profile.png').' '.get_lang('PersonalData').'</a>';
  2739. echo '<a href="/main/messages/inbox.php">'. Display::return_icon('inbox.png').' '. get_lang('Inbox').'</a>';
  2740. echo '<a href="/main/messages/outbox.php">'.Display::return_icon('outbox.png').' '. get_lang('Outbox').'</a>';
  2741. echo '<span style="float:right; padding-top:7px;">'.
  2742. '<a href="/main/auth/profile.php?show=1">'.Display::return_icon('edit.gif').' '.get_lang('Configuration').'</a>';
  2743. '</span>';
  2744. echo '</div>';
  2745. }
  2746. /**
  2747. * Gives a list of course auto-register (field special_course)
  2748. * @return array list of course
  2749. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>
  2750. * @deprecated this function is never use in chamilo, use CourseManager::get_special_course_list
  2751. * @since Dokeos 1.8.6.2
  2752. */
  2753. public static function get_special_course_list() {
  2754. // Database Table Definitions
  2755. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2756. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  2757. $tbl_course_field = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
  2758. $tbl_course_field_value = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  2759. $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  2760. //we filter the courses from the URL
  2761. $join_access_url=$where_access_url='';
  2762. if (api_get_multiple_access_url()) {
  2763. $access_url_id = api_get_current_access_url_id();
  2764. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2765. $join_access_url= "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  2766. $where_access_url=" AND access_url_id = $access_url_id ";
  2767. }
  2768. // Filter special courses
  2769. $sql_special_course = "SELECT course_code FROM $tbl_course_field_value tcfv INNER JOIN $tbl_course_field tcf ON " .
  2770. " tcfv.field_id = tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
  2771. $special_course_result = Database::query($sql_special_course);
  2772. $code_special_courses = '';
  2773. if(Database::num_rows($special_course_result)>0) {
  2774. $special_course_list = array();
  2775. while ($result_row = Database::fetch_array($special_course_result)) {
  2776. $special_course_list[] = '"'.$result_row['course_code'].'"';
  2777. }
  2778. $code_special_courses = ' course.code IN ('.join($special_course_list, ',').') ';
  2779. }
  2780. // variable initialisation
  2781. $course_list_sql = '';
  2782. $course_list = array();
  2783. if(!empty($code_special_courses)){
  2784. $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
  2785. FROM ".$tbl_course_user." course_rel_user
  2786. LEFT JOIN ".$tbl_course." course
  2787. ON course.code = course_rel_user.course_code
  2788. LEFT JOIN ".$tbl_user_course_category." user_course_category
  2789. ON course_rel_user.user_course_cat = user_course_category.id
  2790. $join_access_url
  2791. WHERE $code_special_courses $where_access_url
  2792. GROUP BY course.code
  2793. ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC";
  2794. $course_list_sql_result = Database::query($course_list_sql);
  2795. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  2796. $course_list[] = $result_row;
  2797. }
  2798. }
  2799. return $course_list;
  2800. }
  2801. /**
  2802. * Allow to register contact to social network
  2803. * @param int user friend id
  2804. * @param int user id
  2805. * @param int relation between users see constants definition
  2806. */
  2807. public static function relate_users ($friend_id,$my_user_id,$relation_type) {
  2808. $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
  2809. $friend_id = intval($friend_id);
  2810. $my_user_id = intval($my_user_id);
  2811. $relation_type = intval($relation_type);
  2812. $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.' ';
  2813. $result = Database::query($sql);
  2814. $row = Database :: fetch_array($result, 'ASSOC');
  2815. $current_date=date('Y-m-d H:i:s');
  2816. if ($row['count'] == 0) {
  2817. $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.'");';
  2818. Database::query($sql_i);
  2819. return true;
  2820. } else {
  2821. $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.' ';
  2822. $result = Database::query($sql);
  2823. $row = Database :: fetch_array($result, 'ASSOC');
  2824. if ($row['count'] == 1) {
  2825. //only for the case of a RRHH
  2826. if ($row['relation_type'] != $relation_type && $relation_type == USER_RELATION_TYPE_RRHH) {
  2827. $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.'");';
  2828. } else {
  2829. $sql_i = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.$relation_type.' WHERE friend_user_id=' . $friend_id.' AND user_id='.$my_user_id;
  2830. }
  2831. Database::query($sql_i);
  2832. return true;
  2833. } else {
  2834. return false;
  2835. }
  2836. }
  2837. }
  2838. /**
  2839. * Deletes a contact
  2840. * @param int user friend id
  2841. * @param bool true will delete ALL friends relationship from $friend_id
  2842. * @author isaac flores paz <isaac.flores@dokeos.com>
  2843. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  2844. */
  2845. public static function remove_user_rel_user ($friend_id, $real_removed = false, $with_status_condition = '') {
  2846. $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
  2847. $tbl_my_message = Database :: get_main_table(TABLE_MAIN_MESSAGE);
  2848. $friend_id = intval($friend_id);
  2849. if ($real_removed) {
  2850. //Delete user friend
  2851. /*
  2852. $sql_delete_relationship1 = 'UPDATE ' . $tbl_my_friend .' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE friend_user_id='.$friend_id;
  2853. $sql_delete_relationship2 = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id;
  2854. Database::query($sql_delete_relationship1);
  2855. Database::query($sql_delete_relationship2);*/
  2856. $extra_condition = '';
  2857. if ($with_status_condition != '') {
  2858. $extra_condition = ' AND relation_type = '.intval($with_status_condition);
  2859. }
  2860. $sql_delete_relationship1 = 'DELETE FROM ' . $tbl_my_friend .' WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND friend_user_id='.$friend_id.' '.$extra_condition;
  2861. $sql_delete_relationship2 = 'DELETE FROM ' . $tbl_my_friend . ' WHERE relation_type <> '.USER_RELATION_TYPE_RRHH.' AND user_id=' . $friend_id.' '.$extra_condition;
  2862. Database::query($sql_delete_relationship1);
  2863. Database::query($sql_delete_relationship2);
  2864. } else {
  2865. $user_id = api_get_user_id();
  2866. $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;
  2867. $result = Database::query($sql);
  2868. $row = Database :: fetch_array($result, 'ASSOC');
  2869. if ($row['count'] == 1) {
  2870. //Delete user rel user
  2871. $sql_i = 'UPDATE ' . $tbl_my_friend .' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id='.$user_id.' AND friend_user_id='.$friend_id;
  2872. $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" ';
  2873. //Delete user
  2874. $sql_ij = 'UPDATE ' . $tbl_my_friend . ' SET relation_type='.USER_RELATION_TYPE_DELETED.' WHERE user_id=' . $friend_id.' AND friend_user_id='.$user_id;
  2875. $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" ';
  2876. Database::query($sql_i);
  2877. Database::query($sql_j);
  2878. Database::query($sql_ij);
  2879. Database::query($sql_ji);
  2880. }
  2881. }
  2882. }
  2883. /**
  2884. * get users folloewd by human resource manager
  2885. * @param int hr_dept id
  2886. * @param int user status (optional)
  2887. * @return array users
  2888. */
  2889. public static function get_users_followed_by_drh($hr_dept_id, $user_status = 0) {
  2890. // Database Table Definitions
  2891. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2892. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  2893. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2894. $hr_dept_id = intval($hr_dept_id);
  2895. $assigned_users_to_hrm = array();
  2896. $condition_status = '';
  2897. if (!empty($user_status)) {
  2898. $status = intval($status);
  2899. $condition_status = ' AND u.status = '.$user_status;
  2900. }
  2901. if (api_get_multiple_access_url()) {
  2902. $sql = "SELECT u.user_id, u.username, u.lastname, u.firstname, u.email FROM $tbl_user u
  2903. INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id) LEFT JOIN $tbl_user_rel_access_url a
  2904. ON (a.user_id = u.user_id)
  2905. WHERE friend_user_id = '$hr_dept_id' AND relation_type = '".USER_RELATION_TYPE_RRHH."' $condition_status AND access_url_id = ".api_get_current_access_url_id()."
  2906. ";
  2907. } else {
  2908. $sql = "SELECT u.user_id, u.username, u.lastname, u.firstname, u.email FROM $tbl_user u
  2909. INNER JOIN $tbl_user_rel_user uru ON uru.user_id = u.user_id AND friend_user_id = '$hr_dept_id' AND relation_type = '".USER_RELATION_TYPE_RRHH."' $condition_status
  2910. ";
  2911. }
  2912. $rs_assigned_users = Database::query($sql);
  2913. if (Database::num_rows($rs_assigned_users) > 0) {
  2914. while ($row_assigned_users = Database::fetch_array($rs_assigned_users)) {
  2915. $assigned_users_to_hrm[$row_assigned_users['user_id']] = $row_assigned_users;
  2916. }
  2917. }
  2918. return $assigned_users_to_hrm;
  2919. }
  2920. /**
  2921. * Subscribes users to human resource manager (Dashboard feature)
  2922. * @param int hr dept id
  2923. * @param array Users id
  2924. * @param int affected rows
  2925. **/
  2926. public static function suscribe_users_to_hr_manager($hr_dept_id, $users_id) {
  2927. // Database Table Definitions
  2928. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2929. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  2930. $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2931. $hr_dept_id = intval($hr_dept_id);
  2932. $affected_rows = 0;
  2933. if (api_get_multiple_access_url()) {
  2934. //Deleting assigned users to hrm_id
  2935. $sql = "SELECT s.user_id FROM $tbl_user_rel_user s INNER JOIN $tbl_user_rel_access_url a ON (a.user_id = s.user_id) WHERE friend_user_id = $hr_dept_id AND relation_type = '".USER_RELATION_TYPE_RRHH."' AND access_url_id = ".api_get_current_access_url_id()."";
  2936. } else {
  2937. $sql = "SELECT user_id FROM $tbl_user_rel_user WHERE friend_user_id = $hr_dept_id AND relation_type = '".USER_RELATION_TYPE_RRHH."' ";
  2938. }
  2939. $result = Database::query($sql);
  2940. if (Database::num_rows($result) > 0) {
  2941. while ($row = Database::fetch_array($result)) {
  2942. $sql = "DELETE FROM $tbl_user_rel_user WHERE user_id = '{$row['user_id']}' AND friend_user_id = $hr_dept_id AND relation_type = '".USER_RELATION_TYPE_RRHH."' ";
  2943. Database::query($sql);
  2944. }
  2945. }
  2946. // inserting new user list
  2947. if (is_array($users_id)) {
  2948. foreach ($users_id as $user_id) {
  2949. $user_id = intval($user_id);
  2950. $insert_sql = "INSERT IGNORE INTO $tbl_user_rel_user(user_id, friend_user_id, relation_type) VALUES('$user_id', $hr_dept_id, '".USER_RELATION_TYPE_RRHH."')";
  2951. Database::query($insert_sql);
  2952. $affected_rows = Database::affected_rows();
  2953. }
  2954. }
  2955. return $affected_rows;
  2956. }
  2957. /**
  2958. * This function check if an user is followed by human resources manager
  2959. * @param int User id
  2960. * @param int Human resources manager
  2961. * @return bool
  2962. */
  2963. public static function is_user_followed_by_drh($user_id, $hr_dept_id) {
  2964. // Database table and variables Definitions
  2965. $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  2966. $user_id = intval($user_id);
  2967. $hr_dept_id = intval($hr_dept_id);
  2968. $result = false;
  2969. $sql = "SELECT user_id FROM $tbl_user_rel_user WHERE user_id='$user_id' AND friend_user_id='$hr_dept_id' AND relation_type = ".USER_RELATION_TYPE_RRHH." ";
  2970. $rs = Database::query($sql);
  2971. if (Database::num_rows($rs) > 0) {
  2972. $result = true;
  2973. }
  2974. return $result;
  2975. }
  2976. /**
  2977. * get user id of teacher or session administrator
  2978. * @param string The course id
  2979. * @return int The user id
  2980. */
  2981. public function get_user_id_of_course_admin_or_session_admin ($course_id) {
  2982. $session=api_get_session_id();
  2983. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2984. $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2985. $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2986. if ($session==0 || is_null($session)) {
  2987. $sql='SELECT u.user_id FROM '.$table_user.' u
  2988. INNER JOIN '.$table_course_user.' ru ON ru.user_id=u.user_id
  2989. WHERE ru.status=1 AND ru.course_code="'.Database::escape_string($course_id).'" ';
  2990. $rs=Database::query($sql);
  2991. $num_rows=Database::num_rows($rs);
  2992. if ($num_rows==1) {
  2993. $row=Database::fetch_array($rs);
  2994. return $row['user_id'];
  2995. } else {
  2996. $my_num_rows=$num_rows;
  2997. $my_user_id=Database::result($rs,$my_num_rows-1,'user_id');
  2998. return $my_user_id;
  2999. }
  3000. } elseif ($session>0) {
  3001. $sql='SELECT u.user_id FROM '.$table_user.' u
  3002. INNER JOIN '.$table_session_course_user.' sru
  3003. ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" ';
  3004. $rs=Database::query($sql);
  3005. $row=Database::fetch_array($rs);
  3006. return $row['user_id'];
  3007. }
  3008. }
  3009. /**
  3010. * Determines if a user is a gradebook certified
  3011. * @param int The category id of gradebook
  3012. * @param int The user id
  3013. * @return boolean
  3014. */
  3015. public function is_user_certified($cat_id,$user_id) {
  3016. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  3017. $sql = 'SELECT path_certificate FROM '.$table_certificate.' WHERE cat_id="'.Database::escape_string($cat_id).'" AND user_id="'.Database::escape_string($user_id).'" ';
  3018. $rs = Database::query($sql);
  3019. $row = Database::fetch_array($rs);
  3020. if ($row['path_certificate']=='' || is_null($row['path_certificate'])) {
  3021. return false;
  3022. } else {
  3023. return true;
  3024. }
  3025. }
  3026. /**
  3027. * Gets the info about a gradebook certificate for a user by course
  3028. * @param string The course code
  3029. * @param int The user id
  3030. * @return array if there is not information return false
  3031. */
  3032. public function get_info_gradebook_certificate($course_code, $user_id) {
  3033. $tbl_grade_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  3034. $tbl_grade_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  3035. $session_id = api_get_session_id();
  3036. if (empty($session_id)) {
  3037. $session_condition = ' AND (session_id = "" OR session_id = 0 OR session_id IS NULL )';
  3038. } else {
  3039. $session_condition = " AND session_id = $session_id";
  3040. }
  3041. //Getting gradebook score
  3042. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
  3043. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
  3044. $sql = 'SELECT * FROM '.$tbl_grade_certificate.' WHERE cat_id = (SELECT id FROM '.$tbl_grade_category.' WHERE course_code = "'.Database::escape_string($course_code).'" '.$session_condition.' LIMIT 1 ) AND user_id='.Database::escape_string($user_id);
  3045. $rs = Database::query($sql);
  3046. if (Database::num_rows($rs) > 0) {
  3047. $row = Database::fetch_array($rs,'ASSOC');
  3048. $score = $row['score_certificate'];
  3049. $category_id = $row['cat_id'];
  3050. $cat = Category::load($category_id);
  3051. $displayscore = ScoreDisplay::instance();
  3052. $grade = '';
  3053. if (isset($cat) && $displayscore->is_custom()) {
  3054. $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()), SCORE_DIV_PERCENT_WITH_CUSTOM);
  3055. } else {
  3056. $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()));
  3057. }
  3058. $row['grade'] = $grade;
  3059. return $row;
  3060. }
  3061. return false;
  3062. }
  3063. /**
  3064. * Gets the user path of user certificated
  3065. * @param int The user id
  3066. * @return array containing path_certificate and cat_id
  3067. */
  3068. public function get_user_path_certificate($user_id) {
  3069. $my_certificate = array();
  3070. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  3071. $table_gradebook_category = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  3072. $session_id = api_get_session_id();
  3073. $user_id = intval($user_id);
  3074. if ($session_id==0 || is_null($session_id)) {
  3075. $sql_session='AND (session_id='.Database::escape_string($session_id).' OR isnull(session_id)) ';
  3076. } elseif ($session_id>0) {
  3077. $sql_session='AND session_id='.Database::escape_string($session_id);
  3078. } else {
  3079. $sql_session='';
  3080. }
  3081. $sql= "SELECT tc.path_certificate,tc.cat_id,tgc.course_code,tgc.name FROM $table_certificate tc, $table_gradebook_category tgc
  3082. WHERE tgc.id = tc.cat_id AND tc.user_id='$user_id' ORDER BY tc.date_certificate DESC limit 5";
  3083. $rs=Database::query($sql);
  3084. while ($row=Database::fetch_array($rs)) {
  3085. $my_certificate[]=$row;
  3086. }
  3087. return $my_certificate;
  3088. }
  3089. /**
  3090. * This function check if the user is a coach inside session course
  3091. * @param int User id
  3092. * @param string Course code
  3093. * @param int Session id
  3094. * @return bool True if the user is a coach
  3095. *
  3096. */
  3097. public function is_session_course_coach($user_id, $course_code, $session_id) {
  3098. $tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3099. // Protect data
  3100. $user_id = intval($user_id);
  3101. $course_code = Database::escape_string($course_code);
  3102. $session_id = intval($session_id);
  3103. $result = false;
  3104. $sql = "SELECT id_session FROM $tbl_session_course_rel_user WHERE id_session=$session_id AND course_code='$course_code' AND id_user = $user_id AND status=2 ";
  3105. $res = Database::query($sql);
  3106. if (Database::num_rows($res) > 0) {
  3107. $result = true;
  3108. }
  3109. return $result;
  3110. }
  3111. /**
  3112. * This function returns an icon path that represents the favicon of the website of which the url given. Defaults to the current Chamilo favicon
  3113. * @param string URL of website where to look for favicon.ico
  3114. * @param string Optional second URL of website where to look for favicon.ico
  3115. * @return string Path of icon to load
  3116. */
  3117. public function get_favicon_from_url($url1, $url2 = null) {
  3118. $icon_link = '';
  3119. $url = $url1;
  3120. if (empty($url1)) {
  3121. $url = $url2;
  3122. if (empty($url)) {
  3123. $url = api_get_access_url(api_get_current_access_url_id());
  3124. $url = $url[0];
  3125. }
  3126. }
  3127. if (!empty($url)) {
  3128. $pieces = parse_url($url);
  3129. $icon_link = $pieces['scheme'].'://'.$pieces['host'].'/favicon.ico';
  3130. }
  3131. return $icon_link;
  3132. }
  3133. /**
  3134. *
  3135. * @param int student id
  3136. * @param int years
  3137. * @param bool show warning_message
  3138. * @param bool return_timestamp
  3139. */
  3140. public static function delete_inactive_student($student_id, $years = 2, $warning_message = false, $return_timestamp = false) {
  3141. $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  3142. $sql = 'SELECT login_date FROM ' . $tbl_track_login . ' WHERE login_user_id = ' . intval($student_id) . ' ORDER BY login_date DESC LIMIT 0,1';
  3143. if (empty($years)) {
  3144. $years = 1;
  3145. }
  3146. $inactive_time = $years * 31536000; //1 year
  3147. $rs = Database::query($sql);
  3148. if (Database::num_rows($rs)>0) {
  3149. if ($last_login_date = Database::result($rs, 0, 0)) {
  3150. $last_login_date = api_get_local_time($last_login_date, null, date_default_timezone_get());
  3151. if ($return_timestamp) {
  3152. return api_strtotime($last_login_date);
  3153. } else {
  3154. if (!$warning_message) {
  3155. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  3156. } else {
  3157. $timestamp = api_strtotime($last_login_date);
  3158. $currentTimestamp = time();
  3159. //If the last connection is > than 7 days, the text is red
  3160. //345600 = 7 days in seconds 63072000= 2 ans
  3161. // if ($currentTimestamp - $timestamp > 184590 )
  3162. if ($currentTimestamp - $timestamp > $inactive_time && UserManager::delete_user($student_id )) {
  3163. Display :: display_normal_message(get_lang('UserDeleted'));
  3164. //avec validation:
  3165. // $result .= '<a href="user_list.php?action=delete_user&amp;user_id='.$student_id.'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
  3166. echo '<p>','id',$student_id ,':',$last_login_date,'</p>';
  3167. }
  3168. }
  3169. }
  3170. }
  3171. }
  3172. return false;
  3173. }
  3174. function set_extra_fields_in_form($form, $extra_data, $form_name, $admin_permissions = false) {
  3175. $user_id = intval($user_id);
  3176. // EXTRA FIELDS
  3177. $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  3178. $jquery_ready_content = null;
  3179. foreach ($extra as $field_details) {
  3180. if (!$admin_permissions) {
  3181. if ($field_details[6] == 0) {
  3182. continue;
  3183. }
  3184. }
  3185. switch($field_details[2]) {
  3186. case self::USER_FIELD_TYPE_TEXT:
  3187. $form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
  3188. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  3189. $form->applyFilter('extra_'.$field_details[1], 'trim');
  3190. if (!$admin_permissions) {
  3191. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3192. }
  3193. break;
  3194. case self::USER_FIELD_TYPE_TEXTAREA:
  3195. $form->add_html_editor('extra_'.$field_details[1], $field_details[3], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
  3196. //$form->addElement('textarea', 'extra_'.$field_details[1], $field_details[3], array('size' => 80));
  3197. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  3198. $form->applyFilter('extra_'.$field_details[1], 'trim');
  3199. if (!$admin_permissions) {
  3200. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3201. }
  3202. break;
  3203. case self::USER_FIELD_TYPE_RADIO:
  3204. $group = array();
  3205. foreach ($field_details[9] as $option_id => $option_details) {
  3206. $options[$option_details[1]] = $option_details[2];
  3207. $group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
  3208. }
  3209. $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
  3210. if (!$admin_permissions) {
  3211. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3212. }
  3213. break;
  3214. case self::USER_FIELD_TYPE_SELECT:
  3215. $get_lang_variables = false;
  3216. if (in_array($field_details[1], array('mail_notify_message','mail_notify_invitation', 'mail_notify_group_message'))) {
  3217. $get_lang_variables = true;
  3218. }
  3219. $options = array();
  3220. foreach($field_details[9] as $option_id => $option_details) {
  3221. //$options[$option_details[1]] = $option_details[2];
  3222. if ($get_lang_variables) {
  3223. $options[$option_details[1]] = get_lang($option_details[2]);
  3224. }
  3225. }
  3226. if ($get_lang_variables) {
  3227. $field_details[3] = get_lang($field_details[3]);
  3228. }
  3229. $form->addElement('select','extra_'.$field_details[1], $field_details[3], $options, array('class'=>'chzn-select', 'id'=>'extra_'.$field_details[1]));
  3230. if (!$admin_permissions) {
  3231. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3232. }
  3233. break;
  3234. case self::USER_FIELD_TYPE_SELECT_MULTIPLE:
  3235. $options = array();
  3236. foreach ($field_details[9] as $option_id => $option_details) {
  3237. $options[$option_details[1]] = $option_details[2];
  3238. }
  3239. $form->addElement('select','extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
  3240. if (!$admin_permissions) {
  3241. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3242. }
  3243. break;
  3244. case self::USER_FIELD_TYPE_DATE:
  3245. $form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => $form_name));
  3246. $form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
  3247. $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
  3248. $form -> setDefaults($defaults);
  3249. if (!$admin_permissions) {
  3250. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3251. }
  3252. $form->applyFilter('theme', 'trim');
  3253. break;
  3254. case self::USER_FIELD_TYPE_DATETIME:
  3255. $form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3], array('form_name' => $form_name));
  3256. $form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
  3257. $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
  3258. $form -> setDefaults($defaults);
  3259. if (!$admin_permissions) {
  3260. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3261. }
  3262. $form->applyFilter('theme', 'trim');
  3263. break;
  3264. case self::USER_FIELD_TYPE_DOUBLE_SELECT:
  3265. foreach ($field_details[9] as $key => $element) {
  3266. if ($element[2][0] == '*') {
  3267. $values['*'][$element[0]] = str_replace('*', '', $element[2]);
  3268. } else {
  3269. $values[0][$element[0]] = $element[2];
  3270. }
  3271. }
  3272. $group = '';
  3273. $group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1], '', $values[0], '');
  3274. $group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*', '', $values['*'], '');
  3275. $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
  3276. if (!$admin_permissions) {
  3277. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3278. }
  3279. // recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
  3280. if (key_exists('extra_'.$field_details[1], $extra_data)) {
  3281. // exploding all the selected values (of both select forms)
  3282. $selected_values = explode(';', $extra_data['extra_'.$field_details[1]]);
  3283. $extra_data['extra_'.$field_details[1]] = array();
  3284. // looping through the selected values and assigning the selected values to either the first or second select form
  3285. foreach ($selected_values as $key => $selected_value) {
  3286. if (key_exists($selected_value,$values[0])) {
  3287. $extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
  3288. } else {
  3289. $extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
  3290. }
  3291. }
  3292. }
  3293. break;
  3294. case self::USER_FIELD_TYPE_DIVIDER:
  3295. $form->addElement('static', $field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
  3296. break;
  3297. case self::USER_FIELD_TYPE_TAG:
  3298. //the magic should be here
  3299. $user_tags = UserManager::get_user_tags(api_get_user_id(),$field_details[0]);
  3300. $tag_list = '';
  3301. if (is_array($user_tags) && count($user_tags)> 0) {
  3302. foreach ($user_tags as $tag) {
  3303. $tag_list .= '<option value="'.$tag['tag'].'" class="selected">'.$tag['tag'].'</option>';
  3304. }
  3305. }
  3306. $multi_select = '<select id="extra_'.$field_details[1].'" name="extra_'.$field_details[1].'">
  3307. '.$tag_list.'
  3308. </select>';
  3309. $form->addElement('label',$field_details[3], $multi_select);
  3310. $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php';
  3311. $complete_text = get_lang('StartToType');
  3312. //if cache is set to true the jquery will be called 1 time
  3313. $jquery_ready_content = <<<EOF
  3314. $("#extra_$field_details[1]").fcbkcomplete({
  3315. json_url: "$url?a=search_tags&field_id=$field_details[0]",
  3316. cache: false,
  3317. filter_case: true,
  3318. filter_hide: true,
  3319. complete_text:"$complete_text",
  3320. firstselected: true,
  3321. //onremove: "testme",
  3322. //onselect: "testme",
  3323. filter_selected: true,
  3324. newel: true
  3325. });
  3326. EOF;
  3327. break;
  3328. case self::USER_FIELD_TYPE_TIMEZONE:
  3329. $form->addElement('select', 'extra_'.$field_details[1], $field_details[3], api_get_timezones(), '');
  3330. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3331. break;
  3332. case self::USER_FIELD_TYPE_SOCIAL_PROFILE:
  3333. // get the social network's favicon
  3334. $icon_path = UserManager::get_favicon_from_url($extra_data['extra_'.$field_details[1]], $field_details[4]);
  3335. // special hack for hi5
  3336. $leftpad = '1.7'; $top = '0.4'; $domain = parse_url($icon_path, PHP_URL_HOST); if ($domain == 'www.hi5.com' or $domain == 'hi5.com') { $leftpad = '3'; $top = '0';}
  3337. // print the input field
  3338. $form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 60, 'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '));
  3339. $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
  3340. $form->applyFilter('extra_'.$field_details[1], 'trim');
  3341. if ($field_details[7] == 0) $form->freeze('extra_'.$field_details[1]);
  3342. break;
  3343. }
  3344. }
  3345. $return = array();
  3346. $return['jquery_ready_content'] = $jquery_ready_content;
  3347. return $return;
  3348. }
  3349. function get_user_field_types() {
  3350. $types = array();
  3351. $types[self::USER_FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
  3352. $types[self::USER_FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
  3353. $types[self::USER_FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
  3354. $types[self::USER_FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
  3355. $types[self::USER_FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
  3356. $types[self::USER_FIELD_TYPE_DATE] = get_lang('FieldTypeDate');
  3357. $types[self::USER_FIELD_TYPE_DATETIME] = get_lang('FieldTypeDatetime');
  3358. $types[self::USER_FIELD_TYPE_DOUBLE_SELECT] = get_lang('FieldTypeDoubleSelect');
  3359. $types[self::USER_FIELD_TYPE_DIVIDER] = get_lang('FieldTypeDivider');
  3360. $types[self::USER_FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
  3361. $types[self::USER_FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
  3362. $types[self::USER_FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
  3363. }
  3364. function add_user_as_admin($user_id) {
  3365. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  3366. $user_id = intval($user_id);
  3367. if (!self::is_admin($user_id)) {
  3368. $sql = "INSERT INTO $table_admin SET user_id = '".$user_id."'";
  3369. Database::query($sql);
  3370. }
  3371. }
  3372. function remove_user_admin($user_id) {
  3373. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  3374. $user_id = intval($user_id);
  3375. if (self::is_admin($user_id)) {
  3376. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  3377. Database::query($sql);
  3378. }
  3379. }
  3380. }