usermanager.lib.php 136 KB

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