usermanager.lib.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  1. <?php // $Id: usermanager.lib.php 20346 2009-05-05 21:12:37Z cfasanando $
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2009 Dokeos SPRL
  6. Copyright (c) 2003 Ghent University (UGent)
  7. Copyright (c) 2001 Universite catholique de Louvain (UCL)
  8. Copyright (c) various contributors
  9. Copyright (c) Bart Mollet, Hogeschool Gent
  10. For a full list of contributors, see "credits.txt".
  11. The full license can be read in "license.txt".
  12. This program is free software; you can redistribute it and/or
  13. modify it under the terms of the GNU General Public License
  14. as published by the Free Software Foundation; either version 2
  15. of the License, or (at your option) any later version.
  16. See the GNU General Public License for more details.
  17. Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
  18. ==============================================================================
  19. */
  20. /**
  21. ==============================================================================
  22. * This library provides functions for user management.
  23. * Include/require it in your code to use its functionality.
  24. *
  25. * @package dokeos.library
  26. ==============================================================================
  27. */
  28. // define constants for user extra field types
  29. define('USER_FIELD_TYPE_TEXT',1);
  30. define('USER_FIELD_TYPE_TEXTAREA',2);
  31. define('USER_FIELD_TYPE_RADIO',3);
  32. define('USER_FIELD_TYPE_SELECT',4);
  33. define('USER_FIELD_TYPE_SELECT_MULTIPLE',5);
  34. define('USER_FIELD_TYPE_DATE',6);
  35. define('USER_FIELD_TYPE_DATETIME',7);
  36. define('USER_FIELD_TYPE_DOUBLE_SELECT',8);
  37. define('USER_FIELD_TYPE_DIVIDER',9);
  38. class UserManager
  39. {
  40. /**
  41. * Creates a new user for the platform
  42. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
  43. * Roan Embrechts <roan_embrechts@yahoo.com>
  44. *
  45. * @param string Firstname
  46. * @param string Lastname
  47. * @param int Status (1 for course tutor, 5 for student, 6 for anonymous)
  48. * @param string e-mail address
  49. * @param string Login
  50. * @param string Password
  51. * @param string Any official code (optional)
  52. * @param int User language (optional)
  53. * @param string Phone number (optional)
  54. * @param string Picture URI (optional)
  55. * @param string Authentication source (optional, defaults to 'platform', dependind on constant)
  56. * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00')
  57. * @param int Whether the account is enabled or disabled by default
  58. * @param int The user ID of the person who registered this user (optional, defaults to null)
  59. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  60. * @return mixed new user id - if the new user creation succeeds, false otherwise
  61. *
  62. * @desc The function tries to retrieve $_user['user_id'] from the global space.
  63. * if it exists, $_user['user_id'] is the creator id If a problem arises,
  64. * it stores the error message in global $api_failureList
  65. */
  66. 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)
  67. {
  68. global $_user, $userPasswordCrypted;
  69. // database table definition
  70. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  71. // default langauge
  72. if ($language=='')
  73. {
  74. $language = api_get_setting('platformLanguage');
  75. }
  76. if ($_user['user_id'])
  77. {
  78. $creator_id = $_user['user_id'];
  79. }
  80. else
  81. {
  82. $creator_id = '';
  83. }
  84. // First check wether the login already exists
  85. if (! UserManager::is_username_available($loginName))
  86. return api_set_failure('login-pass already taken');
  87. //$password = "PLACEHOLDER";
  88. $password = api_get_encrypted_password($password);
  89. //$password = ($userPasswordCrypted ? md5($password) : $password);
  90. $current_date=date('Y-m-d H:i:s',time());
  91. $sql = "INSERT INTO $table_user
  92. SET lastname = '".Database::escape_string(trim($lastName))."',
  93. firstname = '".Database::escape_string(trim($firstName))."',
  94. username = '".Database::escape_string(trim($loginName))."',
  95. status = '".Database::escape_string($status)."',
  96. password = '".Database::escape_string($password)."',
  97. email = '".Database::escape_string($email)."',
  98. official_code = '".Database::escape_string($official_code)."',
  99. picture_uri = '".Database::escape_string($picture_uri)."',
  100. creator_id = '".Database::escape_string($creator_id)."',
  101. auth_source = '".Database::escape_string($auth_source)."',
  102. phone = '".Database::escape_string($phone)."',
  103. language = '".Database::escape_string($language)."',
  104. registration_date = '".$current_date."',
  105. expiration_date = '".Database::escape_string($expiration_date)."',
  106. hr_dept_id = '".Database::escape_string($hr_dept_id)."',
  107. active = '".Database::escape_string($active)."'";
  108. $result = api_sql_query($sql, __FILE__, __LINE__);
  109. if ($result) {
  110. //echo "id returned";
  111. $return=Database::get_last_insert_id();
  112. global $_configuration;
  113. require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
  114. if ($_configuration['multiple_access_urls']==true) {
  115. if (api_get_current_access_url_id()!=-1)
  116. UrlManager::add_user_to_url($return, api_get_current_access_url_id());
  117. else
  118. UrlManager::add_user_to_url($return, 1);
  119. } else {
  120. //we are adding by default the access_url_user table with access_url_id = 1
  121. UrlManager::add_user_to_url($return, 1);
  122. }
  123. } else {
  124. //echo "false - failed" ;
  125. $return=false;
  126. }
  127. if(is_array($extra) AND count($extra)>0) {
  128. $res = true;
  129. foreach($extra as $fname => $fvalue) {
  130. $res = $res && UserManager::update_extra_field($return,$fname,$fvalue);
  131. }
  132. }
  133. return $return;
  134. }
  135. /**
  136. * Can user be deleted?
  137. * This functions checks if there's a course in which the given user is the
  138. * only course administrator. If that is the case, the user can't be
  139. * deleted because the course would remain without a course admin.
  140. * @param int $user_id The user id
  141. * @return boolean true if user can be deleted
  142. */
  143. function can_delete_user($user_id)
  144. {
  145. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  146. $sql = "SELECT * FROM $table_course_user WHERE status = '1' AND user_id = '".$user_id."'";
  147. $res = api_sql_query($sql,__FILE__,__LINE__);
  148. while ($course = Database::fetch_object($res))
  149. {
  150. $sql = "SELECT user_id FROM $table_course_user WHERE status='1' AND course_code ='".$course->course_code."'";
  151. $res2 = api_sql_query($sql,__FILE__,__LINE__);
  152. if (Database::num_rows($res2) == 1)
  153. {
  154. return false;
  155. }
  156. }
  157. return true;
  158. }
  159. /**
  160. * Delete a user from the platform
  161. * @param int $user_id The user id
  162. * @return boolean true if user is succesfully deleted, false otherwise
  163. */
  164. function delete_user($user_id)
  165. {
  166. if (!UserManager :: can_delete_user($user_id))
  167. {
  168. return false;
  169. }
  170. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  171. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  172. $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
  173. $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  174. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  175. $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  176. $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  177. // Unsubscribe the user from all groups in all his courses
  178. $sql = "SELECT * FROM $table_course c, $table_course_user cu WHERE cu.user_id = '".$user_id."' AND c.code = cu.course_code";
  179. $res = api_sql_query($sql,__FILE__,__LINE__);
  180. while ($course = Database::fetch_object($res))
  181. {
  182. $table_group = Database :: get_course_table(TABLE_GROUP_USER, $course->db_name);
  183. $sql = "DELETE FROM $table_group WHERE user_id = '".$user_id."'";
  184. api_sql_query($sql,__FILE__,__LINE__);
  185. }
  186. // Unsubscribe user from all classes
  187. $sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
  188. api_sql_query($sql,__FILE__,__LINE__);
  189. // Unsubscribe user from all courses
  190. $sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
  191. api_sql_query($sql,__FILE__,__LINE__);
  192. // Unsubscribe user from all courses in sessions
  193. $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
  194. api_sql_query($sql,__FILE__,__LINE__);
  195. // Unsubscribe user from all sessions
  196. $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
  197. api_sql_query($sql,__FILE__,__LINE__);
  198. // Delete user picture
  199. $user_info = api_get_user_info($user_id);
  200. if(strlen($user_info['picture_uri']) > 0)
  201. {
  202. $img_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/'.$user_info['picture_uri'];
  203. unlink($img_path);
  204. }
  205. // Delete the personal course categories
  206. $course_cat_table = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  207. $sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
  208. api_sql_query($sql,__FILE__,__LINE__);
  209. // Delete user from database
  210. $sql = "DELETE FROM $table_user WHERE user_id = '".$user_id."'";
  211. api_sql_query($sql,__FILE__,__LINE__);
  212. // Delete user from the admin table
  213. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  214. api_sql_query($sql,__FILE__,__LINE__);
  215. // Delete the personal agenda-items from this user
  216. $agenda_table = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
  217. $sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
  218. api_sql_query($sql,__FILE__,__LINE__);
  219. $gradebook_results_table = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
  220. $sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
  221. api_sql_query($sql, __FILE__, __LINE__);
  222. $user = Database::fetch_array($res);
  223. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  224. $sqlv = "DELETE FROM $t_ufv WHERE user_id = $user_id";
  225. $resv = api_sql_query($sqlv,__FILE__,__LINE__);
  226. global $_configuration;
  227. if ($_configuration['multiple_access_urls']) {
  228. require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
  229. $url_id=1;
  230. if (api_get_current_access_url_id()!=-1)
  231. $url_id=api_get_current_access_url_id();
  232. UrlManager::delete_url_rel_user($user_id,$url_id);
  233. }
  234. return true;
  235. }
  236. /**
  237. * Update user information with new openid
  238. * @param int $user_id
  239. * @param string $openid
  240. * @return boolean true if the user information was updated
  241. */
  242. function update_openid($user_id, $openid)
  243. {
  244. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  245. $sql = "UPDATE $table_user SET
  246. openid='".Database::escape_string($openid)."'";
  247. $sql .= " WHERE user_id='$user_id'";
  248. return api_sql_query($sql,__FILE__,__LINE__);
  249. }
  250. /**
  251. * Update user information
  252. * @param int $user_id
  253. * @param string $firstname
  254. * @param string $lastname
  255. * @param string $username
  256. * @param string $password
  257. * @param string $auth_source
  258. * @param string $email
  259. * @param int $status
  260. * @param string $official_code
  261. * @param string $phone
  262. * @param string $picture_uri
  263. * @param int The user ID of the person who registered this user (optional, defaults to null)
  264. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  265. * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
  266. * @return boolean true if the user information was updated
  267. */
  268. 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')
  269. {
  270. global $userPasswordCrypted;
  271. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  272. $sql = "UPDATE $table_user SET
  273. lastname='".Database::escape_string($lastname)."',
  274. firstname='".Database::escape_string($firstname)."',
  275. username='".Database::escape_string($username)."',
  276. language='".Database::escape_string($language)."',";
  277. if(!is_null($password))
  278. {
  279. //$password = $userPasswordCrypted ? md5($password) : $password;
  280. $password = api_get_encrypted_password($password);
  281. $sql .= " password='".Database::escape_string($password)."',";
  282. }
  283. if(!is_null($auth_source))
  284. {
  285. $sql .= " auth_source='".Database::escape_string($auth_source)."',";
  286. }
  287. $sql .= "
  288. email='".Database::escape_string($email)."',
  289. status='".Database::escape_string($status)."',
  290. official_code='".Database::escape_string($official_code)."',
  291. phone='".Database::escape_string($phone)."',
  292. picture_uri='".Database::escape_string($picture_uri)."',
  293. expiration_date='".Database::escape_string($expiration_date)."',
  294. active='".Database::escape_string($active)."',
  295. hr_dept_id=".intval($hr_dept_id);
  296. if(!is_null($creator_id))
  297. {
  298. $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
  299. }
  300. $sql .= " WHERE user_id='$user_id'";
  301. $return = api_sql_query($sql,__FILE__,__LINE__);
  302. if(is_array($extra) and count($extra)>0)
  303. {
  304. $res = true;
  305. foreach($extra as $fname => $fvalue)
  306. {
  307. $res = $res && UserManager::update_extra_field($user_id,$fname,$fvalue);
  308. }
  309. }
  310. return $return;
  311. }
  312. /**
  313. * Check if a username is available
  314. * @param string the wanted username
  315. * @return boolean true if the wanted username is available
  316. */
  317. function is_username_available($username)
  318. {
  319. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  320. $sql = "SELECT username FROM $table_user WHERE username = '".addslashes($username)."'";
  321. $res = api_sql_query($sql,__FILE__,__LINE__);
  322. return Database::num_rows($res) == 0;
  323. }
  324. /**
  325. * Get a list of users of which the given conditions match with an = 'cond'
  326. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  327. * @param array $order_by a list of fields on which sort
  328. * @return array An array with all users of the platform.
  329. * @todo optional course code parameter, optional sorting parameters...
  330. */
  331. function get_user_list($conditions = array(), $order_by = array()) {
  332. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  333. $return_array = array();
  334. $sql_query = "SELECT * FROM $user_table";
  335. if (count($conditions)>0) {
  336. $sql_query .= ' WHERE ';
  337. foreach ($conditions as $field=>$value) {
  338. $field = Database::escape_string($field);
  339. $value = Database::escape_string($value);
  340. $sql_query .= $field.' = '.$value;
  341. }
  342. }
  343. if (count($order_by)>0) {
  344. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',',$order_by));
  345. }
  346. $sql_result = api_sql_query($sql_query,__FILE__,__LINE__);
  347. while ($result = Database::fetch_array($sql_result)) {
  348. $return_array[] = $result;
  349. }
  350. return $return_array;
  351. }
  352. /**
  353. * Get a list of users of which the given conditions match with a LIKE '%cond%'
  354. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  355. * @param array $order_by a list of fields on which sort
  356. * @return array An array with all users of the platform.
  357. * @todo optional course code parameter, optional sorting parameters...
  358. */
  359. function get_user_list_like($conditions = array(), $order_by = array()) {
  360. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  361. $return_array = array();
  362. $sql_query = "SELECT * FROM $user_table";
  363. if (count($conditions)>0) {
  364. $sql_query .= ' WHERE ';
  365. foreach ($conditions as $field=>$value) {
  366. $field = Database::escape_string($field);
  367. $value = Database::escape_string($value);
  368. $sql_query .= $field.' LIKE \'%'.$value.'%\'';
  369. }
  370. }
  371. if (count($order_by)>0) {
  372. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',',$order_by));
  373. }
  374. $sql_result = api_sql_query($sql_query,__FILE__,__LINE__);
  375. while ($result = Database::fetch_array($sql_result)) {
  376. $return_array[] = $result;
  377. }
  378. return $return_array;
  379. }
  380. /**
  381. * Get user information
  382. * @param string The username
  383. * @return array All user information as an associative array
  384. */
  385. function get_user_info($username)
  386. {
  387. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  388. $sql = "SELECT * FROM $user_table WHERE username='".$username."'";
  389. $res = api_sql_query($sql,__FILE__,__LINE__);
  390. if(Database::num_rows($res)>0)
  391. {
  392. $user = Database::fetch_array($res);
  393. }
  394. else
  395. {
  396. $user = false;
  397. }
  398. return $user;
  399. }
  400. /**
  401. * Get user information
  402. * @param string The id
  403. * @param boolean Whether to return the user's extra fields (defaults to false)
  404. * @return array All user information as an associative array
  405. */
  406. function get_user_info_by_id($user_id,$user_fields=false)
  407. {
  408. $user_id = intval($user_id);
  409. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  410. $sql = "SELECT * FROM $user_table WHERE user_id=".$user_id;
  411. $res = api_sql_query($sql,__FILE__,__LINE__);
  412. if(Database::num_rows($res)>0)
  413. {
  414. $user = Database::fetch_array($res);
  415. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  416. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  417. $sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
  418. $resf = api_sql_query($sqlf,__FILE__,__LINE__);
  419. if(Database::num_rows($resf)>0)
  420. {
  421. while($rowf = Database::fetch_array($resf))
  422. {
  423. $sqlv = "SELECT * FROM $t_ufv WHERE field_id = ".$rowf['id']." AND user_id = ".$user['user_id']." ORDER BY id DESC";
  424. $resv = api_sql_query($sqlv,__FILE__,__LINE__);
  425. if(Database::num_rows($resv)>0)
  426. {
  427. //There should be only one value for a field and a user
  428. $rowv = Database::fetch_array($resv);
  429. $user['extra'][$rowf['field_variable']] = $rowv['field_value'];
  430. }
  431. else
  432. {
  433. $user['extra'][$rowf['field_variable']] = '';
  434. }
  435. }
  436. }
  437. }
  438. else
  439. {
  440. $user = false;
  441. }
  442. return $user;
  443. }
  444. //for survey
  445. function get_teacher_list($course_id, $sel_teacher='')
  446. {
  447. $user_course_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  448. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  449. $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'";
  450. $sql_result = api_sql_query($sql_query,__FILE__,__LINE__);
  451. echo "<select name=\"author\">";
  452. while ($result = Database::fetch_array($sql_result))
  453. {
  454. if($sel_teacher==$result['user_id']) $selected ="selected";
  455. echo "\n<option value=\"".$result['user_id']."\" $selected>".$result['firstname']."</option>";
  456. }
  457. echo "</select>";
  458. }
  459. /**
  460. * Get user picture URL or path from user ID (returns an array).
  461. * The return format is a complete path, enabling recovery of the directory
  462. * with dirname() or the file with basename(). This also works for the
  463. * functions dealing with the user's productions, as they are located in
  464. * the same directory.
  465. * @param integer User ID
  466. * @param string Type of path to return (can be 'none','system','rel','web')
  467. * @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)
  468. * @param bool If we want that the function returns the /main/img/unknown.jpg image set it at true
  469. * @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 array
  470. */
  471. function get_user_picture_path_by_id($id,$type='none',$preview=false,$anonymous=false)
  472. {
  473. if(empty($id) or empty($type))
  474. {
  475. if ($anonymous)
  476. {
  477. $dir='';
  478. switch($type)
  479. {
  480. case 'system': //return the complete path to the file, from root
  481. $dir = api_get_path(SYS_CODE_PATH).'img/';
  482. break;
  483. case 'rel': //return the relative path to the file, from the Dokeos base dir
  484. $dir = api_get_path(REL_CODE_PATH).'img/';
  485. break;
  486. case 'web': //return the complete web URL to the file
  487. $dir = api_get_path(WEB_CODE_PATH).'img/';
  488. break;
  489. case 'none': //return only the picture_uri (as is, without subdir)
  490. default:
  491. break;
  492. }
  493. $file_anonymous='unknown.jpg';
  494. return array('dir'=>$dir,'file'=>$file_anonymous);
  495. }
  496. else
  497. {
  498. return array('dir'=>'','file'=>'');
  499. }
  500. }
  501. $user_id = intval($id);
  502. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  503. $sql = "SELECT picture_uri FROM $user_table WHERE user_id=".$user_id;
  504. $res = api_sql_query($sql,__FILE__,__LINE__);
  505. $user=array();
  506. if(Database::num_rows($res)>0)
  507. {
  508. $user = Database::fetch_array($res);
  509. }
  510. else
  511. {
  512. if ($anonymous)
  513. {
  514. $dir='';
  515. switch($type)
  516. {
  517. case 'system': //return the complete path to the file, from root
  518. $dir = api_get_path(SYS_CODE_PATH).'img/';
  519. break;
  520. case 'rel': //return the relative path to the file, from the Dokeos base dir
  521. $dir = api_get_path(REL_CODE_PATH).'img/';
  522. break;
  523. case 'web': //return the complete web URL to the file
  524. $dir = api_get_path(WEB_CODE_PATH).'img/';
  525. break;
  526. case 'none': //return only the picture_uri (as is, without subdir)
  527. default:
  528. break;
  529. }
  530. $file_anonymous='unknown.jpg';
  531. return array('dir'=>$dir,'file'=>$file_anonymous);
  532. }
  533. else
  534. {
  535. return array('dir'=>'','file'=>'');
  536. }
  537. }
  538. $path = trim($user['picture_uri']);
  539. if (empty($path))
  540. {
  541. if ($anonymous)
  542. {
  543. switch($type)
  544. {
  545. case 'system': //return the complete path to the file, from root
  546. $dir = api_get_path(SYS_CODE_PATH).'img/';
  547. break;
  548. case 'rel': //return the relative path to the file, from the Dokeos base dir
  549. $dir = api_get_path(REL_CODE_PATH).'img/';
  550. break;
  551. case 'web': //return the complete web URL to the file
  552. $dir = api_get_path(WEB_CODE_PATH).'img/';
  553. break;
  554. case 'none': //return only the picture_uri (as is, without subdir)
  555. default:
  556. break;
  557. }
  558. $file_anonymous='unknown.jpg';
  559. return array('dir'=>$dir,'file'=>$file_anonymous);
  560. }
  561. }
  562. $dir = '';
  563. $first = '';
  564. if(api_get_setting('split_users_upload_directory') === 'true')
  565. {
  566. if(!empty($path))
  567. {
  568. $first = substr($path,0,1).'/';
  569. }
  570. elseif($preview==true)
  571. {
  572. $first = substr(''.$user_id,0,1).'/';
  573. }
  574. }
  575. $first .= $user_id.'/';
  576. switch($type)
  577. {
  578. case 'system': //return the complete path to the file, from root
  579. $dir = api_get_path(SYS_CODE_PATH).'upload/users/'.$first;
  580. break;
  581. case 'rel': //return the relative path to the file, from the Dokeos base dir
  582. $dir = api_get_path(REL_CODE_PATH).'upload/users/'.$first;
  583. break;
  584. case 'web': //return the complete web URL to the file
  585. $dir = api_get_path(WEB_CODE_PATH).'upload/users/'.$first;
  586. break;
  587. case 'none': //return only the picture_uri (as is, without subdir)
  588. default:
  589. break;
  590. }
  591. return array('dir'=>$dir,'file'=>$path);
  592. }
  593. /*
  594. -----------------------------------------------------------
  595. PRODUCTIONS FUNCTIONS
  596. -----------------------------------------------------------
  597. */
  598. /**
  599. * Returns an XHTML formatted list of productions for a user, or FALSE if he
  600. * doesn't have any.
  601. *
  602. * If there has been a request to remove a production, the function will return
  603. * without building the list unless forced to do so by the optional second
  604. * parameter. This increases performance by avoiding to read through the
  605. * productions on the filesystem before the removal request has been carried
  606. * out because they'll have to be re-read afterwards anyway.
  607. *
  608. * @param $user_id User id
  609. * @param $force Optional parameter to force building after a removal request
  610. * @return A string containing the XHTML code to dipslay the production list, or FALSE
  611. */
  612. function build_production_list($user_id, $force = false, $showdelete=false)
  613. {
  614. if (!$force && !empty($_POST['remove_production']))
  615. return true; // postpone reading from the filesystem
  616. $productions = UserManager::get_user_productions($user_id);
  617. if (empty($productions))
  618. return false;
  619. $production_path = UserManager::get_user_picture_path_by_id($user_id,'web',true);
  620. $production_dir = $production_path['dir'].$user_id.'/';
  621. $del_image = api_get_path(WEB_CODE_PATH).'img/delete.gif';
  622. $del_text = get_lang('Delete');
  623. $production_list = '';
  624. if (count($productions)>0) {
  625. $production_list = '<ul id="productions">';
  626. foreach ($productions as $file) {
  627. $production_list .= '<li><a href="'.$production_dir.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  628. if ($showdelete) {
  629. $production_list .= '<input type="image" name="remove_production['.urlencode($file).']" src="'.$del_image.'" alt="'.$del_text.'" title="'.$del_text.' '.htmlentities($file).'" onclick="return confirmation(\''.htmlentities($file).'\');" /></li>';
  630. }
  631. }
  632. $production_list .= '</ul>';
  633. }
  634. return $production_list;
  635. }
  636. /**
  637. * Returns an array with the user's productions.
  638. *
  639. * @param $user_id User id
  640. * @return An array containing the user's productions
  641. */
  642. function get_user_productions($user_id)
  643. {
  644. $production_path = UserManager::get_user_picture_path_by_id($user_id,'system',true);
  645. $production_repository = $production_path['dir'].$user_id.'/';
  646. $productions = array();
  647. if (is_dir($production_repository))
  648. {
  649. $handle = opendir($production_repository);
  650. while ($file = readdir($handle))
  651. {
  652. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($production_repository.$file))
  653. continue; // skip current/parent directory and .htaccess
  654. $productions[] = $file;
  655. }
  656. }
  657. return $productions; // can be an empty array
  658. }
  659. /**
  660. * Remove a user production.
  661. *
  662. * @param $user_id User id
  663. * @param $production The production to remove
  664. */
  665. function remove_user_production($user_id, $production)
  666. {
  667. $production_path = UserManager::get_user_picture_path_by_id($user_id,'system',true);
  668. unlink($production_path['dir'].$user_id.'/'.$production);
  669. }
  670. /**
  671. * Update an extra field. This function is called when a user changes his/her profile
  672. * and by consequence fills or edits his/her extra fields.
  673. *
  674. * @param integer Field ID
  675. * @param array Database columns and their new value
  676. * @return boolean true if field updated, false otherwise
  677. */
  678. function update_extra_field($fid,$columns)
  679. {
  680. //TODO check that values added are values proposed for enumerated field types
  681. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  682. $fid = Database::escape_string($fid);
  683. $sqluf = "UPDATE $t_uf SET ";
  684. $known_fields = array('id','field_variable','field_type','field_display_text','field_default_value','field_order','field_visible','field_changeable','field_filter');
  685. $safecolumns = array();
  686. foreach ($columns as $index => $newval) {
  687. if (in_array($index,$known_fields)) {
  688. $safecolumns[$index] = Database::escape_string($newval);
  689. $sqluf .= $index." = '".$safecolumns[$index]."', ";
  690. }
  691. }
  692. $time = time();
  693. $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'";
  694. $resuf = api_sql_query($sqluf,__FILE__,__LINE__);
  695. return $resuf;
  696. }
  697. /**
  698. * Update an extra field value for a given user
  699. * @param integer User ID
  700. * @param string Field variable name
  701. * @param string Field value
  702. * @return boolean true if field updated, false otherwise
  703. */
  704. function update_extra_field_value($user_id,$fname,$fvalue='')
  705. {
  706. //TODO check that values added are values proposed for enumerated field types
  707. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  708. $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  709. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  710. $fname = Database::escape_string($fname);
  711. $fvalues = '';
  712. if(is_array($fvalue))
  713. {
  714. foreach($fvalue as $val)
  715. {
  716. $fvalues .= Database::escape_string($val).';';
  717. }
  718. if(!empty($fvalues))
  719. {
  720. $fvalues = substr($fvalues,0,-1);
  721. }
  722. }
  723. else
  724. {
  725. $fvalues = Database::escape_string($fvalue);
  726. }
  727. $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
  728. $resuf = api_sql_query($sqluf,__FILE__,__LINE__);
  729. if(Database::num_rows($resuf)==1)
  730. { //ok, the field exists
  731. // Check if enumerated field, if the option is available
  732. $rowuf = Database::fetch_array($resuf);
  733. switch($rowuf['field_type'])
  734. {
  735. case 3:
  736. case 4:
  737. case 5:
  738. $sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
  739. $resuo = api_sql_query($sqluo,__FILE__,__LINE__);
  740. $values = split(';',$fvalues);
  741. if(Database::num_rows($resuo)>0)
  742. {
  743. $check = false;
  744. while($rowuo = Database::fetch_array($resuo))
  745. {
  746. if(in_array($rowuo['option_value'],$values))
  747. {
  748. $check = true;
  749. break;
  750. }
  751. }
  752. if($check == false)
  753. {
  754. return false; //option value not found
  755. }
  756. }
  757. else
  758. {
  759. return false; //enumerated type but no option found
  760. }
  761. break;
  762. case 1:
  763. case 2:
  764. default:
  765. break;
  766. }
  767. $tms = time();
  768. $sqlufv = "SELECT * FROM $t_ufv WHERE user_id = $user_id AND field_id = ".$rowuf['id']." ORDER BY id";
  769. $resufv = api_sql_query($sqlufv,__FILE__,__LINE__);
  770. $n = Database::num_rows($resufv);
  771. if($n>1)
  772. {
  773. //problem, we already have to values for this field and user combination - keep last one
  774. while($rowufv = Database::fetch_array($resufv))
  775. {
  776. if($n > 1)
  777. {
  778. $sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
  779. $resd = api_sql_query($sqld,__FILE__,__LINE__);
  780. $n--;
  781. }
  782. $rowufv = Database::fetch_array($resufv);
  783. if($rowufv['field_value'] != $fvalues)
  784. {
  785. $sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
  786. $resu = api_sql_query($sqlu,__FILE__,__LINE__);
  787. return($resu?true:false);
  788. }
  789. return true;
  790. }
  791. }
  792. elseif($n==1)
  793. {
  794. //we need to update the current record
  795. $rowufv = Database::fetch_array($resufv);
  796. if($rowufv['field_value'] != $fvalues)
  797. {
  798. $sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
  799. //error_log('UM::update_extra_field_value: '.$sqlu);
  800. $resu = api_sql_query($sqlu,__FILE__,__LINE__);
  801. return($resu?true:false);
  802. }
  803. return true;
  804. }
  805. else
  806. {
  807. $sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms) " .
  808. "VALUES ($user_id,".$rowuf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
  809. //error_log('UM::update_extra_field_value: '.$sqli);
  810. $resi = api_sql_query($sqli,__FILE__,__LINE__);
  811. return($resi?true:false);
  812. }
  813. }
  814. else
  815. {
  816. return false; //field not found
  817. }
  818. }
  819. /**
  820. * Get an array of extra fieds with field details (type, default value and options)
  821. * @param integer Offset (from which row)
  822. * @param integer Number of items
  823. * @param integer Column on which sorting is made
  824. * @param string Sorting direction
  825. * @param boolean Optional. Whether we get all the fields or just the visible ones
  826. * @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
  827. */
  828. function get_extra_fields($from=0, $number_of_items=0, $column=5, $direction='ASC', $all_visibility=true)
  829. {
  830. $fields = array();
  831. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  832. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  833. $columns = array('id','field_variable','field_type','field_display_text','field_default_value','field_order','field_filter','tms');
  834. $sort_direction = '';
  835. if (in_array(strtoupper($direction),array('ASC','DESC'))) {
  836. $sort_direction = strtoupper($direction);
  837. }
  838. $sqlf = "SELECT * FROM $t_uf ";
  839. if ($all_visibility==false) {
  840. $sqlf .= " WHERE field_visible = 1 ";
  841. }
  842. $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction " ;
  843. if ($number_of_items != 0) {
  844. $sqlf .= " LIMIT ".Database::escape_string($from).','.Database::escape_string($number_of_items);
  845. }
  846. $resf = api_sql_query($sqlf,__FILE__,__LINE__);
  847. if(Database::num_rows($resf)>0) {
  848. while($rowf = Database::fetch_array($resf)) {
  849. $fields[$rowf['id']] = array(
  850. 0=>$rowf['id'],
  851. 1=>$rowf['field_variable'],
  852. 2=>$rowf['field_type'],
  853. //3=>(empty($rowf['field_display_text'])?'':get_lang($rowf['field_display_text'],'')),
  854. //temporarily removed auto-translation. Need update to get_lang() to know if translation exists (todo)
  855. 3=>(empty($rowf['field_display_text'])?'':$rowf['field_display_text']),
  856. 4=>$rowf['field_default_value'],
  857. 5=>$rowf['field_order'],
  858. 6=>$rowf['field_visible'],
  859. 7=>$rowf['field_changeable'],
  860. 8=>$rowf['field_filter'],
  861. 9=>array()
  862. );
  863. $sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id']." ORDER BY option_order ASC";
  864. $reso = api_sql_query($sqlo,__FILE__,__LINE__);
  865. if (Database::num_rows($reso)>0) {
  866. while ($rowo = Database::fetch_array($reso)) {
  867. $fields[$rowf['id']][9][$rowo['id']] = array(
  868. 0=>$rowo['id'],
  869. 1=>$rowo['option_value'],
  870. //2=>(empty($rowo['option_display_text'])?'':get_lang($rowo['option_display_text'],'')),
  871. 2=>(empty($rowo['option_display_text'])?'':$rowo['option_display_text']),
  872. 3=>$rowo['option_order']
  873. );
  874. }
  875. }
  876. }
  877. }
  878. return $fields;
  879. }
  880. /**
  881. * Get the list of options attached to an extra field
  882. * @param string $fieldname the name of the field
  883. * @return array the list of options
  884. */
  885. function get_extra_field_options($field_name)
  886. {
  887. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  888. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  889. $sql = 'SELECT options.*
  890. FROM '.$t_ufo.' options
  891. INNER JOIN '.$t_uf.' fields
  892. ON fields.id = options.field_id
  893. AND fields.field_variable="'.Database::escape_string($field_name).'"';
  894. $rs = api_sql_query($sql, __FILE__, __LINE__);
  895. return api_store_result($rs);
  896. }
  897. /**
  898. * Get the number of extra fields currently recorded
  899. * @param boolean Optional switch. true (default) returns all fields, false returns only visible fields
  900. * @return integer Number of fields
  901. */
  902. function get_number_of_extra_fields($all_visibility=true)
  903. {
  904. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  905. $sqlf = "SELECT * FROM $t_uf ";
  906. if($all_visibility == false)
  907. {
  908. $sqlf .= " WHERE field_visible = 1 ";
  909. }
  910. $sqlf .= " ORDER BY field_order";
  911. $resf = api_sql_query($sqlf,__FILE__,__LINE__);
  912. return Database::num_rows($resf);
  913. }
  914. /**
  915. * Creates a new extra field
  916. * @param string Field's internal variable name
  917. * @param int Field's type
  918. * @param string Field's language var name
  919. * @param string Field's default value
  920. * @param string Optional comma-separated list of options to provide for select and radio
  921. * @return int new user id - if the new user creation succeeds, false otherwise
  922. */
  923. function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions='')
  924. {
  925. // database table definition
  926. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  927. $table_field_options= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  928. // First check wether the login already exists
  929. if (UserManager::is_extra_field_available($fieldvarname))
  930. return api_set_failure('login-pass already taken');
  931. $sql = "SELECT MAX(field_order) FROM $table_field";
  932. $res = api_sql_query($sql,__FILE__,__LINE__);
  933. $order = 0;
  934. if(Database::num_rows($res)>0)
  935. {
  936. $row = Database::fetch_array($res);
  937. $order = $row[0]+1;
  938. }
  939. $time = time();
  940. $sql = "INSERT INTO $table_field
  941. SET field_type = '".Database::escape_string($fieldtype)."',
  942. field_variable = '".Database::escape_string($fieldvarname)."',
  943. field_display_text = '".Database::escape_string($fieldtitle)."',
  944. field_default_value = '".Database::escape_string($fielddefault)."',
  945. field_order = '$order',
  946. tms = FROM_UNIXTIME($time)";
  947. $result = api_sql_query($sql);
  948. if ($result)
  949. {
  950. //echo "id returned";
  951. $return=Database::get_last_insert_id();
  952. }
  953. else
  954. {
  955. //echo "false - failed" ;
  956. return false;
  957. }
  958. 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)))
  959. {
  960. if($fieldtype == USER_FIELD_TYPE_DOUBLE_SELECT)
  961. {
  962. $twolist = explode('|', $fieldoptions);
  963. $counter = 0;
  964. foreach ($twolist as $individual_list)
  965. {
  966. $splitted_individual_list = split(';',$individual_list);
  967. foreach ($splitted_individual_list as $individual_list_option)
  968. {
  969. //echo 'counter:'.$counter;
  970. if ($counter == 0)
  971. {
  972. $list[] = $individual_list_option;
  973. }
  974. else
  975. {
  976. $list[] = str_repeat('*',$counter).$individual_list_option;
  977. }
  978. }
  979. $counter++;
  980. }
  981. }
  982. else
  983. {
  984. $list = split(';',$fieldoptions);
  985. }
  986. foreach($list as $option)
  987. {
  988. $option = Database::escape_string($option);
  989. $sql = "SELECT * FROM $table_field_options WHERE field_id = $return AND option_value = '".$option."'";
  990. $res = api_sql_query($sql,__FILE__,__LINE__);
  991. if(Database::num_rows($res)>0)
  992. {
  993. //the option already exists, do nothing
  994. }
  995. else
  996. {
  997. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = $return";
  998. $res = api_sql_query($sql,__FILE__,__LINE__);
  999. $max = 1;
  1000. if(Database::num_rows($res)>0)
  1001. {
  1002. $row = Database::fetch_array($res);
  1003. $max = $row[0]+1;
  1004. }
  1005. $time = time();
  1006. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ($return,'$option','$option',$max,FROM_UNIXTIME($time))";
  1007. $res = api_sql_query($sql,__FILE__,__LINE__);
  1008. if($res === false)
  1009. {
  1010. $return = false;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. return $return;
  1016. }
  1017. /**
  1018. * Save the changes in the definition of the extra user profile field
  1019. * The function is called after you (as admin) decide to store the changes you have made to one of the fields you defined
  1020. *
  1021. * There is quite some logic in this field
  1022. * 1. store the changes to the field (tupe, name, label, default text)
  1023. * 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
  1024. * the options (and choices) that do no longer have to appear. We cannot remove all options and choices because if you remove them all
  1025. * and simply re-add them all then all the user who have already filled this form will loose their selected value.
  1026. * 3. we add the options that are newly added
  1027. *
  1028. * @example current options are a;b;c and the user changes this to a;b;x (removing c and adding x)
  1029. * we first remove c (and also the entry in the option_value table for the users who have chosen this)
  1030. * we then add x
  1031. * a and b are neither removed nor added
  1032. *
  1033. * @param integer $fieldid the id of the field we are editing
  1034. * @param string $fieldvarname the internal variable name of the field
  1035. * @param int $fieldtype the type of the field
  1036. * @param string $fieldtitle the title of the field
  1037. * @param string $fielddefault the default value of the field
  1038. * @param string $fieldoptions Optional comma-separated list of options to provide for select and radio
  1039. * @return boolean true
  1040. *
  1041. *
  1042. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1043. * @version July 2008
  1044. * @since Dokeos 1.8.6
  1045. */
  1046. function save_extra_field_changes($fieldid, $fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions='')
  1047. {
  1048. // database table definition
  1049. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1050. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1051. $table_field_options_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1052. // we first update the field definition with the new values
  1053. $time = time();
  1054. $sql = "UPDATE $table_field
  1055. SET field_type = '".Database::escape_string($fieldtype)."',
  1056. field_variable = '".Database::escape_string($fieldvarname)."',
  1057. field_display_text = '".Database::escape_string($fieldtitle)."',
  1058. field_default_value = '".Database::escape_string($fielddefault)."',
  1059. tms = FROM_UNIXTIME($time)
  1060. WHERE id = '".Database::escape_string($fieldid)."'";
  1061. $result = api_sql_query($sql,__FILE__,__LINE__);
  1062. // we create an array with all the options (will be used later in the script)
  1063. if ($fieldtype == USER_FIELD_TYPE_DOUBLE_SELECT) {
  1064. $twolist = explode('|', $fieldoptions);
  1065. $counter = 0;
  1066. foreach ($twolist as $individual_list) {
  1067. $splitted_individual_list = split(';',$individual_list);
  1068. foreach ($splitted_individual_list as $individual_list_option) {
  1069. //echo 'counter:'.$counter;
  1070. if ($counter == 0) {
  1071. $list[] = trim($individual_list_option);
  1072. } else {
  1073. $list[] = str_repeat('*',$counter).trim($individual_list_option);
  1074. }
  1075. }
  1076. $counter++;
  1077. }
  1078. }
  1079. else
  1080. {
  1081. $templist = split(';',$fieldoptions);
  1082. $list = array_map('trim', $templist);
  1083. }
  1084. // Remove all the field options (and also the choices of the user) that are NOT in the new list of options
  1085. $sql = "SELECT * FROM $table_field_options WHERE option_value NOT IN ('".implode("','", $list)."') AND field_id = '".Database::escape_string($fieldid)."'";
  1086. $result = api_sql_query($sql,__FILE__,__LINE__);
  1087. $return['deleted_options'] = 0;
  1088. while ($row = Database::fetch_array($result))
  1089. {
  1090. // deleting the option
  1091. $sql_delete_option = "DELETE FROM $table_field_options WHERE id='".Database::escape_string($row['id'])."'";
  1092. $result_delete_option = api_sql_query($sql_delete_option,__FILE__,__LINE__);
  1093. $return['deleted_options']++;
  1094. // deleting the answer of the user who has chosen this option
  1095. $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'])."'";
  1096. $result_delete_option_value = api_sql_query($sql_delete_option_value,__FILE__,__LINE__);
  1097. $return['deleted_option_values'] = $return['deleted_option_values'] + Database::affected_rows();
  1098. }
  1099. // we now try to find the field options that are newly added
  1100. $sql = "SELECT * FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
  1101. $result = api_sql_query($sql,__FILE__,__LINE__);
  1102. while ($row = Database::fetch_array($result))
  1103. {
  1104. // we remove every option that is already in the database from the $list
  1105. if (in_array(trim($row['option_display_text']),$list))
  1106. {
  1107. $key = array_search(trim($row['option_display_text']),$list);
  1108. unset($list[$key]);
  1109. }
  1110. }
  1111. // we store the new field options in the database
  1112. foreach ($list as $key=>$option)
  1113. {
  1114. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
  1115. $res = api_sql_query($sql,__FILE__,__LINE__);
  1116. $max = 1;
  1117. if(Database::num_rows($res)>0)
  1118. {
  1119. $row = Database::fetch_array($res);
  1120. $max = $row[0]+1;
  1121. }
  1122. $time = time();
  1123. $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))";
  1124. $result = api_sql_query($sql,__FILE__,__LINE__);
  1125. }
  1126. return true;
  1127. }
  1128. /**
  1129. * Check if a field is available
  1130. * @param string the wanted fieldname
  1131. * @return boolean true if the wanted username is available
  1132. */
  1133. function is_extra_field_available($fieldname)
  1134. {
  1135. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1136. $sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
  1137. $res = api_sql_query($sql,__FILE__,__LINE__);
  1138. return Database::num_rows($res) > 0;
  1139. }
  1140. /**
  1141. * Gets user extra fields data
  1142. * @param integer User ID
  1143. * @param boolean Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  1144. * @param boolean Whether to return invisible fields as well
  1145. * @param boolean Whether to split multiple-selection fields or not
  1146. * @return array Array of fields => value for the given user
  1147. */
  1148. function get_extra_user_data($user_id, $prefix=false, $all_visibility = true, $splitmultiple=false)
  1149. {
  1150. $extra_data = array();
  1151. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1152. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1153. $user_id = Database::escape_string($user_id);
  1154. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1155. if($all_visibility == false)
  1156. {
  1157. $sql .= " WHERE f.field_visible = 1 ";
  1158. }
  1159. $sql .= " ORDER BY f.field_order";
  1160. $res = api_sql_query($sql,__FILE__,__LINE__);
  1161. if(Database::num_rows($res)>0)
  1162. {
  1163. while($row = Database::fetch_array($res))
  1164. {
  1165. $sqlu = "SELECT field_value as fval " .
  1166. " FROM $t_ufv " .
  1167. " WHERE field_id=".$row['id']."" .
  1168. " AND user_id=".$user_id;
  1169. $resu = api_sql_query($sqlu,__FILE__,__LINE__);
  1170. $fval = '';
  1171. // get default value
  1172. $sql_df = "SELECT field_default_value as fval_df " .
  1173. " FROM $t_uf " .
  1174. " WHERE id=".$row['id'];
  1175. $res_df = api_sql_query($sql_df,__FILE__,__LINE__);
  1176. if(Database::num_rows($resu)>0)
  1177. {
  1178. $rowu = Database::fetch_array($resu);
  1179. $fval = $rowu['fval'];
  1180. if($row['type'] == USER_FIELD_TYPE_SELECT_MULTIPLE)
  1181. {
  1182. $fval = split(';',$rowu['fval']);
  1183. }
  1184. } else {
  1185. $row_df = Database::fetch_array($res_df);
  1186. $fval = $row_df['fval_df'];
  1187. }
  1188. if($prefix)
  1189. {
  1190. if ($row['type'] == USER_FIELD_TYPE_RADIO)
  1191. {
  1192. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  1193. }
  1194. else
  1195. {
  1196. $extra_data['extra_'.$row['fvar']] = $fval;
  1197. }
  1198. }
  1199. else
  1200. {
  1201. if ($row['type'] == USER_FIELD_TYPE_RADIO)
  1202. {
  1203. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  1204. }
  1205. else
  1206. {
  1207. $extra_data[$row['fvar']] = $fval;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. return $extra_data;
  1213. }
  1214. function get_extra_user_data_by_field($user_id, $field_variable, $prefix=false, $all_visibility = true, $splitmultiple=false)
  1215. {
  1216. $extra_data = array();
  1217. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1218. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1219. $user_id = Database::escape_string($user_id);
  1220. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1221. $sql.=" WHERE f.field_variable = '$field_variable' ";
  1222. if($all_visibility == false)
  1223. {
  1224. $sql .= " AND f.field_visible = 1 ";
  1225. }
  1226. $sql .= " ORDER BY f.field_order";
  1227. $res = api_sql_query($sql,__FILE__,__LINE__);
  1228. if(Database::num_rows($res)>0)
  1229. {
  1230. while($row = Database::fetch_array($res))
  1231. {
  1232. $sqlu = "SELECT field_value as fval " .
  1233. " FROM $t_ufv " .
  1234. " WHERE field_id=".$row['id']."" .
  1235. " AND user_id=".$user_id;
  1236. $resu = api_sql_query($sqlu,__FILE__,__LINE__);
  1237. $fval = '';
  1238. if(Database::num_rows($resu)>0)
  1239. {
  1240. $rowu = Database::fetch_array($resu);
  1241. $fval = $rowu['fval'];
  1242. if($row['type'] == USER_FIELD_TYPE_SELECT_MULTIPLE)
  1243. {
  1244. $fval = split(';',$rowu['fval']);
  1245. }
  1246. }
  1247. if($prefix)
  1248. {
  1249. $extra_data['extra_'.$row['fvar']] = $fval;
  1250. }
  1251. else
  1252. {
  1253. $extra_data[$row['fvar']] = $fval;
  1254. }
  1255. }
  1256. }
  1257. return $extra_data;
  1258. }
  1259. /**
  1260. * Get all the extra field information of a certain field (also the options)
  1261. *
  1262. * @param integer $field_name the name of the field we want to know everything of
  1263. * @return array $return containing all th information about the extra profile field
  1264. * @author Julio Montoya
  1265. * @since Dokeos 1.8.6
  1266. */
  1267. function get_extra_field_information_by_name($field_variable)
  1268. {
  1269. // database table definition
  1270. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1271. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1272. // all the information of the field
  1273. $sql = "SELECT * FROM $table_field WHERE field_variable='".Database::escape_string($field_variable)."'";
  1274. $result = api_sql_query($sql,__FILE__,__LINE__);
  1275. $return = Database::fetch_array($result);
  1276. // all the options of the field
  1277. $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($return['id'])."' ORDER BY option_order ASC";
  1278. $result = api_sql_query($sql,__FILE__,__LINE__);
  1279. while ($row = Database::fetch_array($result)) {
  1280. $return['options'][$row['id']] = $row;
  1281. }
  1282. return $return;
  1283. }
  1284. /**
  1285. * Get all the extra field information of a certain field (also the options)
  1286. *
  1287. * @param integer $field_name the name of the field we want to know everything of
  1288. * @return array $return containing all th information about the extra profile field
  1289. * @author Julio Montoya
  1290. * @since Dokeos 1.8.6
  1291. */
  1292. function get_extra_field_information($field_id)
  1293. {
  1294. // database table definition
  1295. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1296. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1297. // all the information of the field
  1298. $sql = "SELECT * FROM $table_field WHERE id='".Database::escape_string($field_id)."'";
  1299. $result = api_sql_query($sql,__FILE__,__LINE__);
  1300. $return = Database::fetch_array($result);
  1301. // all the options of the field
  1302. $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($field_id)."' ORDER BY option_order ASC";
  1303. $result = api_sql_query($sql,__FILE__,__LINE__);
  1304. while ($row = Database::fetch_array($result)) {
  1305. $return['options'][$row['id']] = $row;
  1306. }
  1307. return $return;
  1308. }
  1309. function get_extra_user_data_by_value($field_variable, $field_value, $all_visibility = true)
  1310. {
  1311. $extra_data = array();
  1312. $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1313. $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1314. $table_user_field_options= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1315. $where='';
  1316. /*
  1317. if (is_array($field_variable_array) && is_array($field_value_array)) {
  1318. if (count($field_variable_array) == count($field_value_array)) {
  1319. $field_var_count = count($field_variable_array);
  1320. for ($i = 0; $i<$field_var_count ; $i++) {
  1321. if ($i!=0 && $i!=$field_var_count){
  1322. $where.= ' AND ';
  1323. }
  1324. $where.= "field_variable='".Database::escape_string($field_variable_array[$i])."' AND user_field_options.id='".Database::escape_string($field_value_array[$i])."'";
  1325. }
  1326. }
  1327. }*/
  1328. $where= "field_variable='".Database::escape_string($field_variable)."' AND field_value='".Database::escape_string($field_value)."'";
  1329. $sql = "SELECT user_id FROM $table_user_field user_field INNER JOIN $table_user_field_values user_field_values
  1330. ON (user_field.id = user_field_values.field_id)
  1331. WHERE $where";
  1332. if($all_visibility == true) {
  1333. $sql .= " AND user_field.field_visible = 1 ";
  1334. } else {
  1335. $sql .= " AND user_field.field_visible = 0 ";
  1336. }
  1337. $res = api_sql_query($sql,__FILE__,__LINE__);
  1338. $result_data = array();
  1339. if (Database::num_rows($res)>0) {
  1340. while ($row = Database::fetch_array($res)) {
  1341. $result_data[]=$row['user_id'];
  1342. }
  1343. }
  1344. return $result_data;
  1345. }
  1346. /**
  1347. * Gives a list of [session_id-course_code] => [status] for the current user.
  1348. * @param integer $user_id
  1349. * @return array list of statuses (session_id-course_code => status)
  1350. */
  1351. function get_personal_session_course_list($user_id)
  1352. {
  1353. // Database Table Definitions
  1354. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1355. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1356. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1357. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1358. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  1359. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1360. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  1361. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1362. $user_id = Database::escape_string($user_id);
  1363. //we filter the courses from the URL
  1364. $join_access_url=$where_access_url='';
  1365. global $_configuration;
  1366. if ($_configuration['multiple_access_urls']==true) {
  1367. $access_url_id = api_get_current_access_url_id();
  1368. if($access_url_id!=-1) {
  1369. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1370. $join_access_url= "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  1371. $where_access_url=" AND access_url_id = $access_url_id ";
  1372. }
  1373. }
  1374. // variable initialisation
  1375. $personal_course_list_sql = '';
  1376. $personal_course_list = array();
  1377. //Courses in which we suscribed out of any session
  1378. /*$personal_course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i,
  1379. course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort,
  1380. course_rel_user.user_course_cat user_course_cat
  1381. FROM ".$tbl_course." course,".$main_course_user_table." course_rel_user
  1382. WHERE course.code = course_rel_user.course_code"."
  1383. AND course_rel_user.user_id = '".$user_id."'
  1384. ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC,i";*/
  1385. $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  1386. $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
  1387. FROM ".$tbl_course_user." course_rel_user
  1388. LEFT JOIN ".$tbl_course." course
  1389. ON course.code = course_rel_user.course_code
  1390. LEFT JOIN ".$tbl_user_course_category." user_course_category
  1391. ON course_rel_user.user_course_cat = user_course_category.id
  1392. $join_access_url
  1393. WHERE course_rel_user.user_id = '".$user_id."' $where_access_url
  1394. ORDER BY i, user_course_category.sort, course_rel_user.sort ASC";
  1395. $course_list_sql_result = api_sql_query($personal_course_list_sql, __FILE__, __LINE__);
  1396. //var_dump($course_list_sql_result); exit;
  1397. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1398. $personal_course_list[] = $result_row;
  1399. }
  1400. // get the list of sessions where the user is subscribed as student
  1401. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
  1402. FROM $tbl_session_user, $tbl_session
  1403. WHERE id_session=id AND id_user=$user_id
  1404. AND (date_start <= CURDATE() AND date_end >= CURDATE() OR date_start='0000-00-00')
  1405. ORDER BY date_start, date_end, name";
  1406. $result = api_sql_query($sessions_sql,__FILE__,__LINE__);
  1407. $sessions=api_store_result($result);
  1408. $sessions = array_merge($sessions , api_store_result($result));
  1409. // get the list of sessions where the user is subscribed as coach in a course
  1410. $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)
  1411. FROM $tbl_session as session
  1412. INNER JOIN $tbl_session_course as session_rel_course
  1413. ON session_rel_course.id_session = session.id
  1414. AND session_rel_course.id_coach = $user_id
  1415. WHERE
  1416. ( CURDATE() >= DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY) AND
  1417. CURDATE() <= ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY) OR
  1418. date_start='0000-00-00')
  1419. ORDER BY date_start, date_end, name";
  1420. $result = api_sql_query($sessions_sql,__FILE__,__LINE__);
  1421. $session_is_coach = api_store_result($result);
  1422. $sessions = array_merge($sessions , $session_is_coach);
  1423. // get the list of sessions where the user is subscribed as coach
  1424. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
  1425. FROM $tbl_session as session
  1426. WHERE session.id_coach = $user_id
  1427. AND
  1428. ( CURDATE() >= DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY) AND
  1429. CURDATE() <= ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY) OR
  1430. date_start='0000-00-00')
  1431. ORDER BY date_start, date_end, name";
  1432. $result = api_sql_query($sessions_sql,__FILE__,__LINE__);
  1433. $sessions = array_merge($sessions , api_store_result($result));
  1434. if(api_is_allowed_to_create_course()) {
  1435. foreach($sessions as $enreg) {
  1436. $id_session = $enreg['id'];
  1437. $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
  1438. FROM $tbl_session_course as session_course
  1439. INNER JOIN $tbl_course AS course
  1440. ON course.code = session_course.course_code
  1441. INNER JOIN $tbl_session as session
  1442. ON session.id = session_course.id_session
  1443. LEFT JOIN $tbl_user as user
  1444. ON user.user_id = session_course.id_coach
  1445. WHERE session_course.id_session = $id_session
  1446. AND (session_course.id_coach=$user_id OR session.id_coach=$user_id)
  1447. ORDER BY i";
  1448. $course_list_sql_result = api_sql_query($personal_course_list_sql, __FILE__, __LINE__);
  1449. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1450. $result_row['s'] = 2;
  1451. $key = $result_row['id_session'].' - '.$result_row['k'];
  1452. $personal_course_list[$key] = $result_row;
  1453. }
  1454. }
  1455. }
  1456. foreach($sessions as $enreg) {
  1457. $id_session = $enreg['id'];
  1458. $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')
  1459. FROM $tbl_session_course as session_course
  1460. INNER JOIN $tbl_course AS course
  1461. ON course.code = session_course.course_code
  1462. LEFT JOIN $tbl_user as user
  1463. ON user.user_id = session_course.id_coach
  1464. INNER JOIN $tbl_session_course_user
  1465. ON $tbl_session_course_user.id_session = $id_session
  1466. AND $tbl_session_course_user.id_user = $user_id
  1467. INNER JOIN $tbl_session as session
  1468. ON session_course.id_session = session.id
  1469. WHERE session_course.id_session = $id_session
  1470. ORDER BY i";
  1471. $course_list_sql_result = api_sql_query($personal_course_list_sql, __FILE__, __LINE__);
  1472. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1473. $key = $result_row['id_session'].' - '.$result_row['k'];
  1474. $result_row['s'] = $result_row['14'];
  1475. if(!isset($personal_course_list[$key])) {
  1476. $personal_course_list[$key] = $result_row;
  1477. }
  1478. }
  1479. }
  1480. //print_r($personal_course_list);
  1481. return $personal_course_list;
  1482. }
  1483. /**
  1484. * Get user id from a username
  1485. * @param string Username
  1486. * @return int User ID (or false if not found)
  1487. */
  1488. function get_user_id_from_username($username) {
  1489. $username = Database::escape_string($username);
  1490. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  1491. $sql = "SELECT user_id FROM $t_user WHERE username = '$username'";
  1492. $res = api_sql_query($sql,__FILE__,__LINE__);
  1493. if ($res===false) { return false; }
  1494. if (Database::num_rows($res)!==1) { return false; }
  1495. $row = Database::fetch_array($res);
  1496. return $row['user_id'];
  1497. }
  1498. /**
  1499. * Get the users files upload from his share_folder
  1500. * @param string Username
  1501. * @return int User ID (or false if not found)
  1502. */
  1503. function get_user_upload_files_by_course($user_id, $course, $column=2)
  1504. {
  1505. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  1506. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  1507. $file_list= array();
  1508. $return = '';
  1509. if (is_dir($path)) {
  1510. $handle = opendir($path);
  1511. while ($file = readdir($handle)) {
  1512. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file))
  1513. continue; // skip current/parent directory and .htaccess
  1514. $file_list[] = $file;
  1515. }
  1516. if (count($file_list)>0) {
  1517. $return = $course;
  1518. $return .= '<ul>';
  1519. }
  1520. foreach ($file_list as $file) {
  1521. $return .= '<li><a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  1522. }
  1523. $return .= '</ul>';
  1524. }
  1525. return $return;
  1526. }
  1527. /**
  1528. * Gets the API key (or keys) and return them into an array
  1529. * @param int Optional user id (defaults to the result of api_get_user_id())
  1530. * @result array Non-indexed array containing the list of API keys for this user, or FALSE on error
  1531. */
  1532. function get_api_keys($user_id=null,$api_service='dokeos') {
  1533. if ($user_id != strval(intval($user_id))) return false;
  1534. if (empty($user_id)) { $user_id = api_get_user_id(); }
  1535. if ($user_id === false) return false;
  1536. $service_name=Database::escape_string($api_service);
  1537. if (is_string($service_name)===false) { return false;}
  1538. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1539. $sql = "SELECT id, api_key FROM $t_api WHERE user_id = ".$user_id." AND api_service='".$api_service."';";
  1540. $res = api_sql_query($sql,__FILE__,__LINE__);
  1541. if ($res === false) return false; //error during query
  1542. $num = Database::num_rows($res);
  1543. if ($num == 0) return false;
  1544. $list = array();
  1545. while ($row = Database::fetch_array($res)) {
  1546. $list[$row['id']] = $row['api_key'];
  1547. }
  1548. return $list;
  1549. }
  1550. /**
  1551. * Adds a new API key to the users' account
  1552. * @param int Optional user ID (defaults to the results of api_get_user_id())
  1553. * @return boolean True on success, false on failure
  1554. */
  1555. function add_api_key($user_id=null,$api_service='dokeos') {
  1556. if ($user_id != strval(intval($user_id))) return false;
  1557. if (empty($user_id)) { $user_id = api_get_user_id(); }
  1558. if ($user_id === false) return false;
  1559. $service_name=Database::escape_string($api_service);
  1560. if (is_string($service_name)===false) { return false;}
  1561. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1562. $md5 = md5((time()+($user_id*5))-rand(10000,10000)); //generate some kind of random key
  1563. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  1564. $res = api_sql_query($sql,__FILE__,__LINE__);
  1565. if ($res === false) return false; //error during query
  1566. $num = Database::insert_id();
  1567. if ($num == 0) return false;
  1568. return $num;
  1569. }
  1570. /**
  1571. * Deletes an API key from the user's account
  1572. * @param int API key's internal ID
  1573. * @return boolean True on success, false on failure
  1574. */
  1575. function delete_api_key($key_id) {
  1576. if ($key_id != strval(intval($key_id))) return false;
  1577. if ($key_id === false) return false;
  1578. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1579. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  1580. $res = api_sql_query($sql,__FILE__,__LINE__);
  1581. if ($res === false) return false; //error during query
  1582. $num = Database::num_rows($res);
  1583. if ($num !== 1) return false;
  1584. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  1585. $res = api_sql_query($sql,__FILE__,__LINE__);
  1586. if ($res === false) return false; //error during query
  1587. return true;
  1588. }
  1589. /**
  1590. * Regenerate an API key from the user's account
  1591. * @param int API key's internal ID
  1592. * @param string
  1593. * @return int
  1594. */
  1595. function update_api_key($user_id,$api_service) {
  1596. if ($user_id != strval(intval($user_id))) return false;
  1597. if ($user_id === false) return false;
  1598. $service_name=Database::escape_string($api_service);
  1599. if (is_string($service_name)===false) { return false;}
  1600. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1601. $sql="SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  1602. $res=api_sql_query($sql,__FILE__,__LINE__);
  1603. $num = Database::num_rows($res);
  1604. if ($num==1) {
  1605. $id_key=Database::fetch_array($res,'ASSOC');
  1606. self::delete_api_key($id_key['id']);
  1607. $num=self::add_api_key($user_id,$api_service);
  1608. } elseif ($num==0) {
  1609. $num=self::add_api_key($user_id);
  1610. }
  1611. return $num;
  1612. }
  1613. /**
  1614. * @param int API key's internal ID
  1615. * @param string
  1616. * @return int
  1617. */
  1618. function get_api_key_id($user_id,$api_service) {
  1619. if ($user_id != strval(intval($user_id))) return false;
  1620. if ($user_id === false) return false;
  1621. $service_name=Database::escape_string($api_service);
  1622. if (is_string($service_name)===false) { return false;}
  1623. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1624. $sql="SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  1625. $res=api_sql_query($sql,__FILE__,__LINE__);
  1626. $row=Database::fetch_array($res,'ASSOC');
  1627. return $row['id'];
  1628. }
  1629. /**
  1630. * Subscribes users to the given session and optionally (default) unsubscribes previous users
  1631. * @param int Session ID
  1632. * @param array List of user IDs
  1633. * @param bool Whether to unsubscribe existing users (true, default) or not (false)
  1634. * @return void Nothing, or false on error
  1635. */
  1636. function suscribe_users_to_session($id_session,$UserList,$empty_users=true){
  1637. if ($id_session!= strval(intval($id_session))) return false;
  1638. foreach($UserList as $intUser){
  1639. if ($intUser!= strval(intval($intUser))) return false;
  1640. }
  1641. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1642. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1643. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1644. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1645. $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session'";
  1646. $result = api_sql_query($sql,__FILE__,__LINE__);
  1647. $existingUsers = array();
  1648. while($row = Database::fetch_array($result)){
  1649. $existingUsers[] = $row['id_user'];
  1650. }
  1651. $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'";
  1652. $result=api_sql_query($sql,__FILE__,__LINE__);
  1653. $CourseList=array();
  1654. while($row=Database::fetch_array($result)) {
  1655. $CourseList[]=$row['course_code'];
  1656. }
  1657. foreach ($CourseList as $enreg_course) {
  1658. // for each course in the session
  1659. $nbr_users=0;
  1660. $enreg_course = Database::escape_string($enreg_course);
  1661. // delete existing users
  1662. if ($empty_users!==false) {
  1663. foreach ($existingUsers as $existing_user) {
  1664. if(!in_array($existing_user, $UserList)) {
  1665. $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user'";
  1666. api_sql_query($sql,__FILE__,__LINE__);
  1667. if(Database::affected_rows()) {
  1668. $nbr_users--;
  1669. }
  1670. }
  1671. }
  1672. }
  1673. // insert new users into session_rel_course_rel_user and ignore if they already exist
  1674. foreach ($UserList as $enreg_user) {
  1675. if(!in_array($enreg_user, $existingUsers)) {
  1676. $enreg_user = Database::escape_string($enreg_user);
  1677. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')";
  1678. api_sql_query($insert_sql,__FILE__,__LINE__);
  1679. if(Database::affected_rows()) {
  1680. $nbr_users++;
  1681. }
  1682. }
  1683. }
  1684. // count users in this session-course relation
  1685. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'";
  1686. $rs = api_sql_query($sql, __FILE__, __LINE__);
  1687. list($nbr_users) = Database::fetch_array($rs);
  1688. // update the session-course relation to add the users total
  1689. $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'";
  1690. api_sql_query($update_sql,__FILE__,__LINE__);
  1691. }
  1692. // delete users from the session
  1693. if ($empty_users!==false){
  1694. api_sql_query("DELETE FROM $tbl_session_rel_user WHERE id_session = $id_session",__FILE__,__LINE__);
  1695. }
  1696. // insert missing users into session
  1697. $nbr_users = 0;
  1698. foreach ($UserList as $enreg_user) {
  1699. $enreg_user = Database::escape_string($enreg_user);
  1700. $nbr_users++;
  1701. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$enreg_user')";
  1702. api_sql_query($insert_sql,__FILE__,__LINE__);
  1703. }
  1704. // update number of users in the session
  1705. $nbr_users = count($UserList);
  1706. $update_sql = "UPDATE $tbl_session SET nbr_users= $nbr_users WHERE id='$id_session' ";
  1707. api_sql_query($update_sql,__FILE__,__LINE__);
  1708. }
  1709. /**
  1710. * Checks if a user_id is platform admin
  1711. * @param int user ID
  1712. * @return boolean True if is admin, false otherwise
  1713. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  1714. */
  1715. function is_admin($user_id) {
  1716. if (empty($user_id) or $user_id != strval(intval($user_id))) { return false; }
  1717. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  1718. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  1719. $res = Database::query($sql);
  1720. if (Database::num_rows($res) === 1) {
  1721. return true;
  1722. }
  1723. return false;
  1724. }
  1725. /**
  1726. * Get the total count of users
  1727. * @return mixed Number of users or false on error
  1728. */
  1729. function get_number_of_users() {
  1730. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  1731. $sql = "SELECT count(*) FROM $t_u";
  1732. $res = Database::query($sql);
  1733. if (Database::num_rows($res) === 1) {
  1734. return (int) Database::result($res,0,0);
  1735. }
  1736. return false;
  1737. }
  1738. }