usermanager.lib.php 178 KB

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