usermanager.lib.php 191 KB

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