usermanager.lib.php 120 KB

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