usermanager.lib.php 58 KB

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