usermanager.lib.php 191 KB

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