usermanager.lib.php 117 KB

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