usermanager.lib.php 140 KB

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