usermanager.lib.php 189 KB

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