usermanager.lib.php 118 KB

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