usermanager.lib.php 137 KB

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