usermanager.lib.php 94 KB

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