usermanager.lib.php 192 KB

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