usermanager.lib.php 137 KB

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