usermanager.lib.php 156 KB

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