usermanager.lib.php 116 KB

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