usermanager.lib.php 158 KB

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