usermanager.lib.php 137 KB

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