usermanager.lib.php 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522
  1. <?php // $Id: usermanager.lib.php 22378 2009-07-26 19:58:38Z yannoo $
  2. /* For licensing terms, see /dokeos_license.txt */
  3. /**
  4. ==============================================================================
  5. * This library provides functions for user management.
  6. * Include/require it in your code to use its functionality.
  7. *
  8. * @package dokeos.library
  9. ==============================================================================
  10. */
  11. // Constants for user extra field types.
  12. define('USER_FIELD_TYPE_TEXT', 1);
  13. define('USER_FIELD_TYPE_TEXTAREA', 2);
  14. define('USER_FIELD_TYPE_RADIO',3);
  15. define('USER_FIELD_TYPE_SELECT',4);
  16. define('USER_FIELD_TYPE_SELECT_MULTIPLE', 5);
  17. define('USER_FIELD_TYPE_DATE', 6);
  18. define('USER_FIELD_TYPE_DATETIME', 7);
  19. define('USER_FIELD_TYPE_DOUBLE_SELECT', 8);
  20. define('USER_FIELD_TYPE_DIVIDER', 9);
  21. define('USER_FIELD_TYPE_TAG', 10);
  22. class UserManager
  23. {
  24. private function __construct () {
  25. }
  26. /**
  27. * Creates a new user for the platform
  28. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
  29. * Roan Embrechts <roan_embrechts@yahoo.com>
  30. *
  31. * @param string Firstname
  32. * @param string Lastname
  33. * @param int Status (1 for course tutor, 5 for student, 6 for anonymous)
  34. * @param string e-mail address
  35. * @param string Login
  36. * @param string Password
  37. * @param string Any official code (optional)
  38. * @param string User language (optional)
  39. * @param string Phone number (optional)
  40. * @param string Picture URI (optional)
  41. * @param string Authentication source (optional, defaults to 'platform', dependind on constant)
  42. * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00')
  43. * @param int Whether the account is enabled or disabled by default
  44. * @param int The user ID of the person who registered this user (optional, defaults to null)
  45. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  46. * @return mixed new user id - if the new user creation succeeds, false otherwise
  47. *
  48. * @desc The function tries to retrieve $_user['user_id'] from the global space.
  49. * if it exists, $_user['user_id'] is the creator id. If a problem arises,
  50. * it stores the error message in global $api_failureList
  51. */
  52. public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id = 0, $extra = null) {
  53. global $_user, $userPasswordCrypted;
  54. $firstName = Security::remove_XSS($firstName);
  55. $lastName = Security::remove_XSS($lastName);
  56. $loginName = Security::remove_XSS($loginName);
  57. $phone = Security::remove_XSS($phone);
  58. // database table definition
  59. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  60. // default langauge
  61. if ($language == '') {
  62. $language = api_get_setting('platformLanguage');
  63. }
  64. if ($_user['user_id']) {
  65. $creator_id = intval($_user['user_id']);
  66. } else {
  67. $creator_id = '';
  68. }
  69. // First check wether the login already exists
  70. if (!self::is_username_available($loginName)) {
  71. return api_set_failure('login-pass already taken');
  72. }
  73. //$password = "PLACEHOLDER";
  74. $password = api_get_encrypted_password($password);
  75. //$password = ($userPasswordCrypted ? md5($password) : $password);
  76. $current_date = date('Y-m-d H:i:s', time());
  77. $sql = "INSERT INTO $table_user
  78. SET lastname = '".Database::escape_string(trim($lastName))."',
  79. firstname = '".Database::escape_string(trim($firstName))."',
  80. username = '".Database::escape_string(trim($loginName))."',
  81. status = '".Database::escape_string($status)."',
  82. password = '".Database::escape_string($password)."',
  83. email = '".Database::escape_string($email)."',
  84. official_code = '".Database::escape_string($official_code)."',
  85. picture_uri = '".Database::escape_string($picture_uri)."',
  86. creator_id = '".Database::escape_string($creator_id)."',
  87. auth_source = '".Database::escape_string($auth_source)."',
  88. phone = '".Database::escape_string($phone)."',
  89. language = '".Database::escape_string($language)."',
  90. registration_date = '".$current_date."',
  91. expiration_date = '".Database::escape_string($expiration_date)."',
  92. hr_dept_id = '".Database::escape_string($hr_dept_id)."',
  93. active = '".Database::escape_string($active)."'";
  94. $result = Database::query($sql, __FILE__, __LINE__);
  95. if ($result) {
  96. //echo "id returned";
  97. $return = Database::insert_id();
  98. global $_configuration;
  99. require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
  100. if ($_configuration['multiple_access_urls'] == true) {
  101. if (api_get_current_access_url_id() != -1) {
  102. UrlManager::add_user_to_url($return, api_get_current_access_url_id());
  103. } else {
  104. UrlManager::add_user_to_url($return, 1);
  105. }
  106. } else {
  107. //we are adding by default the access_url_user table with access_url_id = 1
  108. UrlManager::add_user_to_url($return, 1);
  109. }
  110. // add event to system log
  111. $time = time();
  112. $user_id_manager = api_get_user_id();
  113. event_system(LOG_USER_CREATE, LOG_USER_ID, $return, $time, $user_id_manager);
  114. } else {
  115. //echo "false - failed" ;
  116. $return=false;
  117. }
  118. if (is_array($extra) && count($extra) > 0) {
  119. $res = true;
  120. foreach($extra as $fname => $fvalue) {
  121. $res = $res && self::update_extra_field($return, $fname, $fvalue);
  122. }
  123. }
  124. return $return;
  125. }
  126. /**
  127. * Can user be deleted?
  128. * This functions checks if there's a course in which the given user is the
  129. * only course administrator. If that is the case, the user can't be
  130. * deleted because the course would remain without a course admin.
  131. * @param int $user_id The user id
  132. * @return boolean true if user can be deleted
  133. */
  134. public static function can_delete_user($user_id) {
  135. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  136. if ($user_id != strval(intval($user_id))) return false;
  137. if ($user_id === false) return false;
  138. $sql = "SELECT * FROM $table_course_user WHERE status = '1' AND user_id = '".$user_id."'";
  139. $res = Database::query($sql, __FILE__, __LINE__);
  140. while ($course = Database::fetch_object($res)) {
  141. $sql = "SELECT user_id FROM $table_course_user WHERE status='1' AND course_code ='".Database::escape_string($course->course_code)."'";
  142. $res2 = Database::query($sql, __FILE__, __LINE__);
  143. if (Database::num_rows($res2) == 1) {
  144. return false;
  145. }
  146. }
  147. return true;
  148. }
  149. /**
  150. * Delete a user from the platform
  151. * @param int $user_id The user id
  152. * @return boolean true if user is succesfully deleted, false otherwise
  153. */
  154. public static function delete_user($user_id) {
  155. global $_configuration;
  156. if ($user_id != strval(intval($user_id))) return false;
  157. if ($user_id === false) return false;
  158. if (!self::can_delete_user($user_id)) {
  159. return false;
  160. }
  161. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  162. $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  163. $table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
  164. $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  165. $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
  166. $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  167. $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  168. // Unsubscribe the user from all groups in all his courses
  169. $sql = "SELECT * FROM $table_course c, $table_course_user cu WHERE cu.user_id = '".$user_id."' AND c.code = cu.course_code";
  170. $res = Database::query($sql, __FILE__, __LINE__);
  171. while ($course = Database::fetch_object($res)) {
  172. $table_group = Database :: get_course_table(TABLE_GROUP_USER, $course->db_name);
  173. $sql = "DELETE FROM $table_group WHERE user_id = '".$user_id."'";
  174. Database::query($sql, __FILE__, __LINE__);
  175. }
  176. // Unsubscribe user from all classes
  177. $sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
  178. Database::query($sql, __FILE__, __LINE__);
  179. // Unsubscribe user from all courses
  180. $sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
  181. Database::query($sql, __FILE__, __LINE__);
  182. // Unsubscribe user from all courses in sessions
  183. $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
  184. Database::query($sql, __FILE__, __LINE__);
  185. // Unsubscribe user from all sessions
  186. $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
  187. Database::query($sql, __FILE__, __LINE__);
  188. // Delete user picture
  189. // TODO: Logic about api_get_setting('split_users_upload_directory') === 'true' , a user has 4 differnt sized photos to be deleted.
  190. $user_info = api_get_user_info($user_id);
  191. if (strlen($user_info['picture_uri']) > 0) {
  192. $img_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/'.$user_info['picture_uri'];
  193. if (file_exists($img_path))
  194. unlink($img_path);
  195. }
  196. // Delete the personal course categories
  197. $course_cat_table = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  198. $sql = "DELETE FROM $course_cat_table WHERE user_id = '".$user_id."'";
  199. Database::query($sql, __FILE__, __LINE__);
  200. // Delete user from database
  201. $sql = "DELETE FROM $table_user WHERE user_id = '".$user_id."'";
  202. Database::query($sql, __FILE__, __LINE__);
  203. // Delete user from the admin table
  204. $sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
  205. Database::query($sql, __FILE__, __LINE__);
  206. // Delete the personal agenda-items from this user
  207. $agenda_table = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
  208. $sql = "DELETE FROM $agenda_table WHERE user = '".$user_id."'";
  209. Database::query($sql, __FILE__, __LINE__);
  210. $gradebook_results_table = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
  211. $sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
  212. Database::query($sql, __FILE__, __LINE__);
  213. $user = Database::fetch_array($res);
  214. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  215. $sqlv = "DELETE FROM $t_ufv WHERE user_id = $user_id";
  216. $resv = Database::query($sqlv, __FILE__, __LINE__);
  217. if ($_configuration['multiple_access_urls']) {
  218. require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
  219. $url_id = 1;
  220. if (api_get_current_access_url_id() != -1) {
  221. $url_id = api_get_current_access_url_id();
  222. }
  223. UrlManager::delete_url_rel_user($user_id, $url_id);
  224. }
  225. // add event to system log
  226. $time = time();
  227. $user_id_manager = api_get_user_id();
  228. event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, $time, $user_id_manager);
  229. return true;
  230. }
  231. /**
  232. * Update user information with new openid
  233. * @param int $user_id
  234. * @param string $openid
  235. * @return boolean true if the user information was updated
  236. */
  237. public static function update_openid($user_id, $openid) {
  238. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  239. if ($user_id != strval(intval($user_id))) return false;
  240. if ($user_id === false) return false;
  241. $sql = "UPDATE $table_user SET
  242. openid='".Database::escape_string($openid)."'";
  243. $sql .= " WHERE user_id='$user_id'";
  244. return Database::query($sql, __FILE__, __LINE__);
  245. }
  246. /**
  247. * Update user information
  248. * @param int $user_id
  249. * @param string $firstname
  250. * @param string $lastname
  251. * @param string $username
  252. * @param string $password
  253. * @param string $auth_source
  254. * @param string $email
  255. * @param int $status
  256. * @param string $official_code
  257. * @param string $phone
  258. * @param string $picture_uri
  259. * @param int The user ID of the person who registered this user (optional, defaults to null)
  260. * @param int The department of HR in which the user is registered (optional, defaults to 0)
  261. * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
  262. * @return boolean true if the user information was updated
  263. */
  264. public static function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, $creator_id = null, $hr_dept_id = 0, $extra = null, $language = 'english') {
  265. global $userPasswordCrypted;
  266. if ($user_id != strval(intval($user_id))) return false;
  267. if ($user_id === false) return false;
  268. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  269. $sql = "UPDATE $table_user SET
  270. lastname='".Database::escape_string($lastname)."',
  271. firstname='".Database::escape_string($firstname)."',
  272. username='".Database::escape_string($username)."',
  273. language='".Database::escape_string($language)."',";
  274. if (!is_null($password)) {
  275. //$password = $userPasswordCrypted ? md5($password) : $password;
  276. $password = api_get_encrypted_password($password);
  277. $sql .= " password='".Database::escape_string($password)."',";
  278. }
  279. if (!is_null($auth_source)) {
  280. $sql .= " auth_source='".Database::escape_string($auth_source)."',";
  281. }
  282. $sql .= "
  283. email='".Database::escape_string($email)."',
  284. status='".Database::escape_string($status)."',
  285. official_code='".Database::escape_string($official_code)."',
  286. phone='".Database::escape_string($phone)."',
  287. picture_uri='".Database::escape_string($picture_uri)."',
  288. expiration_date='".Database::escape_string($expiration_date)."',
  289. active='".Database::escape_string($active)."',
  290. hr_dept_id=".intval($hr_dept_id);
  291. if (!is_null($creator_id)) {
  292. $sql .= ", creator_id='".Database::escape_string($creator_id)."'";
  293. }
  294. $sql .= " WHERE user_id='$user_id'";
  295. $return = Database::query($sql, __FILE__, __LINE__);
  296. if (is_array($extra) && count($extra) > 0) {
  297. $res = true;
  298. foreach($extra as $fname => $fvalue) {
  299. $res = $res && self::update_extra_field($user_id,$fname,$fvalue);
  300. }
  301. }
  302. return $return;
  303. }
  304. /**
  305. * Check if a username is available
  306. * @param string the wanted username
  307. * @return boolean true if the wanted username is available
  308. */
  309. public static function is_username_available($username) {
  310. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  311. $sql = "SELECT username FROM $table_user WHERE username = '".Database::escape_string($username)."'";
  312. $res = Database::query($sql, __FILE__, __LINE__);
  313. return Database::num_rows($res) == 0;
  314. }
  315. /**
  316. * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
  317. * @param string $firstname The first name of the user.
  318. * @param string $lastname The last name of the user.
  319. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  320. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  321. * @return string Suggests a username that contains only ASCII-letters and digits, without check for uniqueness within the system.
  322. * @author Julio Montoya Armas
  323. * @author Ivan Tcholakov, 2009 - rework about internationalization.
  324. */
  325. public static function create_username($firstname, $lastname, $language = null, $encoding = null) {
  326. if (is_null($encoding)) {
  327. $encoding = api_get_system_encoding();
  328. }
  329. if (is_null($language)) {
  330. $language = api_get_interface_language();
  331. }
  332. $firstname = substr(preg_replace(USERNAME_PURIFIER, '', api_transliterate($firstname, '', $encoding)), 0, 1); // The first letter only.
  333. $lastname = preg_replace(USERNAME_PURIFIER, '', api_transliterate($lastname, '', $encoding));
  334. $username = api_is_western_name_order(null, $language) ? $firstname.$lastname : $lastname.$firstname;
  335. if (empty($username)) {
  336. $username = 'user';
  337. }
  338. return strtolower(substr($username, 0, USERNAME_MAX_LENGTH - 3));
  339. }
  340. /**
  341. * Creates a unique username, using:
  342. * 1. the first name and the last name of a user;
  343. * 2. an already created username but not checked for uniqueness yet.
  344. * @param string $firstname The first name of a given user. If the second parameter $lastname is NULL, then this
  345. * parameter is treated as username which is to be checked for uniqueness and to be modified when it is necessary.
  346. * @param string $lastname The last name of the user.
  347. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  348. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  349. * @return string Returns a username that contains only ASCII-letters and digits, and that is unique within the system.
  350. * Note: When the method is called several times with same parameters, its results look like the following sequence: ivan, ivan2, ivan3, ivan4, ...
  351. * @author Ivan Tcholakov, 2009
  352. */
  353. public static function create_unique_username($firstname, $lastname = null, $language = null, $encoding = null) {
  354. if (is_null($lastname)) {
  355. // In this case the actual input parameter $firstname should contain ASCII-letters and digits only.
  356. // For making this method tolerant of mistakes, let us transliterate and purify the suggested input username anyway.
  357. // So, instead of the sentence $username = $firstname; we place the following:
  358. $username = strtolower(preg_replace(USERNAME_PURIFIER, '', api_transliterate($firstname, '', $encoding)));
  359. } else {
  360. $username = self::create_username($firstname, $lastname, $language, $encoding);
  361. }
  362. if (!self::is_username_available($username)) {
  363. $i = 2;
  364. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string)$i)).$i;
  365. while (!self::is_username_available($temp_username)) {
  366. $i++;
  367. $temp_username = substr($username, 0, USERNAME_MAX_LENGTH - strlen((string)$i)).$i;
  368. }
  369. $username = $temp_username;
  370. }
  371. return $username;
  372. }
  373. /**
  374. * Modifies a given username accordingly to the specification for valid characters and length.
  375. * @param $username string The input username.
  376. * @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.
  377. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  378. * @return string The resulting purified username.
  379. */
  380. public function purify_username($username, $strict = false, $encoding = null) {
  381. if ($strict) {
  382. // 1. Conversion of unacceptable letters (latinian letters with accents for example) into ASCII letters in order they not to be totally removed.
  383. // 2. Applying the strict purifier.
  384. // 3. Length limitation.
  385. return substr(preg_replace(USERNAME_PURIFIER, '', api_transliterate($username, '', $encoding)), 0, USERNAME_MAX_LENGTH);
  386. }
  387. // 1. Applying the shallow purifier.
  388. // 2. Length limitation.
  389. return substr(preg_replace(USERNAME_PURIFIER_SHALLOW, '', $username), 0, USERNAME_MAX_LENGTH);
  390. }
  391. /**
  392. * Checks whether a given username matches to the specification strictly. The empty username is assumed here as invalid.
  393. * Mostly this function is to be used in the user interface built-in validation routines for providing feedback while usernames are enterd manually.
  394. * @param string $username The input username.
  395. * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
  396. * @return bool Returns TRUE if the username is valid, FALSE otherwise.
  397. */
  398. public function is_username_valid($username, $encoding = null) {
  399. return !empty($username) && $username == self::purify_username($username, true);
  400. }
  401. /**
  402. * Checks whether a username is empty. If the username contains whitespace characters, such as spaces, tabulators, newlines, etc.,
  403. * it is assumed as empty too. This function is safe for validation unpurified data (during importing).
  404. * @param string $username The given username.
  405. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  406. */
  407. public static function is_username_empty($username) {
  408. return (strlen(self::purify_username($username, false)) == 0);
  409. }
  410. /**
  411. * Checks whether a username is too long or not.
  412. * @param string $username The given username, it should contain only ASCII-letters and digits.
  413. * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
  414. */
  415. public static function is_username_too_long($username) {
  416. return (strlen($username) > USERNAME_MAX_LENGTH);
  417. }
  418. /**
  419. * Get a list of users of which the given conditions match with an = 'cond'
  420. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  421. * @param array $order_by a list of fields on which sort
  422. * @return array An array with all users of the platform.
  423. * @todo optional course code parameter, optional sorting parameters...
  424. */
  425. public static function get_user_list($conditions = array(), $order_by = array()) {
  426. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  427. $return_array = array();
  428. $sql_query = "SELECT * FROM $user_table";
  429. if (count($conditions) > 0) {
  430. $sql_query .= ' WHERE ';
  431. foreach ($conditions as $field => $value) {
  432. $field = Database::escape_string($field);
  433. $value = Database::escape_string($value);
  434. $sql_query .= $field.' = '.$value;
  435. }
  436. }
  437. if (count($order_by) > 0) {
  438. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by));
  439. }
  440. $sql_result = Database::query($sql_query, __FILE__, __LINE__);
  441. while ($result = Database::fetch_array($sql_result)) {
  442. $return_array[] = $result;
  443. }
  444. return $return_array;
  445. }
  446. /**
  447. * Get a list of users of which the given conditions match with a LIKE '%cond%'
  448. * @param array $conditions a list of condition (exemple : status=>STUDENT)
  449. * @param array $order_by a list of fields on which sort
  450. * @return array An array with all users of the platform.
  451. * @todo optional course code parameter, optional sorting parameters...
  452. */
  453. function get_user_list_like($conditions = array(), $order_by = array()) {
  454. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  455. $return_array = array();
  456. $sql_query = "SELECT * FROM $user_table";
  457. if (count($conditions) > 0) {
  458. $sql_query .= ' WHERE ';
  459. foreach ($conditions as $field => $value) {
  460. $field = Database::escape_string($field);
  461. $value = Database::escape_string($value);
  462. $sql_query .= $field.' LIKE \'%'.$value.'%\'';
  463. }
  464. }
  465. if (count($order_by) > 0) {
  466. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',', $order_by));
  467. }
  468. $sql_result = Database::query($sql_query, __FILE__, __LINE__);
  469. while ($result = Database::fetch_array($sql_result)) {
  470. $return_array[] = $result;
  471. }
  472. return $return_array;
  473. }
  474. /**
  475. * Get user information
  476. * @param string The username
  477. * @return array All user information as an associative array
  478. */
  479. public static function get_user_info($username) {
  480. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  481. $username = Database::escape_string($username);
  482. $sql = "SELECT * FROM $user_table WHERE username='".$username."'";
  483. $res = Database::query($sql, __FILE__, __LINE__);
  484. if (Database::num_rows($res) > 0) {
  485. return Database::fetch_array($res);
  486. }
  487. return false;
  488. }
  489. /**
  490. * Get user information
  491. * @param string The id
  492. * @param boolean Whether to return the user's extra fields (defaults to false)
  493. * @return array All user information as an associative array
  494. */
  495. public static function get_user_info_by_id($user_id, $user_fields = false) {
  496. $user_id = intval($user_id);
  497. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  498. $sql = "SELECT * FROM $user_table WHERE user_id=".$user_id;
  499. $res = Database::query($sql, __FILE__, __LINE__);
  500. if (Database::num_rows($res) > 0) {
  501. $user = Database::fetch_array($res);
  502. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  503. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  504. $sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
  505. $resf = Database::query($sqlf, __FILE__, __LINE__);
  506. if (Database::num_rows($resf) > 0) {
  507. while ($rowf = Database::fetch_array($resf)) {
  508. $sqlv = "SELECT * FROM $t_ufv WHERE field_id = ".$rowf['id']." AND user_id = ".$user['user_id']." ORDER BY id DESC";
  509. $resv = Database::query($sqlv, __FILE__, __LINE__);
  510. if (Database::num_rows($resv) > 0) {
  511. //There should be only one value for a field and a user
  512. $rowv = Database::fetch_array($resv);
  513. $user['extra'][$rowf['field_variable']] = $rowv['field_value'];
  514. } else {
  515. $user['extra'][$rowf['field_variable']] = '';
  516. }
  517. }
  518. }
  519. return $user;
  520. }
  521. return false;
  522. }
  523. /** Get the teacher list
  524. * @param int the course ID
  525. * @param array Content the list ID of user_id selected
  526. */
  527. //for survey
  528. // TODO: Ivan, 14-SEP-2009: It seems that this method is not used at all (it can be located in a test unit only. To be deprecated?
  529. public static function get_teacher_list($course_id, $sel_teacher = '') {
  530. $user_course_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  531. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  532. $course_id = Database::escape_string($course_id);
  533. $sql_query = "SELECT * FROM $user_table a, $user_course_table b where a.user_id=b.user_id AND b.status=1 AND b.course_code='$course_id'";
  534. $sql_result = Database::query($sql_query, __FILE__, __LINE__);
  535. echo "<select name=\"author\">";
  536. while ($result = Database::fetch_array($sql_result)) {
  537. if ($sel_teacher == $result['user_id']) $selected ="selected";
  538. echo "\n<option value=\"".$result['user_id']."\" $selected>".$result['firstname']."</option>";
  539. }
  540. echo "</select>";
  541. }
  542. /**
  543. * Get user picture URL or path from user ID (returns an array).
  544. * The return format is a complete path, enabling recovery of the directory
  545. * with dirname() or the file with basename(). This also works for the
  546. * functions dealing with the user's productions, as they are located in
  547. * the same directory.
  548. * @param integer User ID
  549. * @param string Type of path to return (can be 'none', 'system', 'rel', 'web')
  550. * @param bool Whether we want to have the directory name returned 'as if' there was a file or not (in the case we want to know which directory to create - otherwise no file means no split subdir)
  551. * @param bool If we want that the function returns the /main/img/unknown.jpg image set it at true
  552. * @return array Array of 2 elements: 'dir' and 'file' which contain the dir and file as the name implies if image does not exist it will return the unknow image if anonymous parameter is true if not it returns an empty er's
  553. */
  554. public static function get_user_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false) {
  555. switch ($type) {
  556. case 'system': // Base: absolute system path.
  557. $base = api_get_path(SYS_CODE_PATH);
  558. break;
  559. case 'rel': // Base: semi-absolute web path (no server base).
  560. $base = api_get_path(REL_CODE_PATH);
  561. break;
  562. case 'web': // Base: absolute web path.
  563. $base = api_get_path(WEB_CODE_PATH);
  564. break;
  565. case 'none':
  566. default: // Base: empty, the result path below will be relative.
  567. $base = '';
  568. }
  569. if (empty($id) || empty($type)) {
  570. return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
  571. }
  572. $user_id = intval($id);
  573. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  574. $sql = "SELECT picture_uri FROM $user_table WHERE user_id=".$user_id;
  575. $res = Database::query($sql, __FILE__, __LINE__);
  576. if (!Database::num_rows($res)) {
  577. return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
  578. }
  579. $user = Database::fetch_array($res);
  580. $picture_filename = trim($user['picture_uri']);
  581. if (api_get_setting('split_users_upload_directory') === 'true') {
  582. if (!empty($picture_filename)) {
  583. $dir = $base.'upload/users/'.substr($picture_filename, 0, 1).'/'.$user_id.'/';
  584. } elseif ($preview) {
  585. $dir = $base.'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
  586. } else {
  587. $dir = $base.'upload/users/'.$user_id.'/';
  588. }
  589. } else {
  590. $dir = $base.'upload/users/'.$user_id.'/';
  591. }
  592. if (empty($picture_filename) && $anonymous) {
  593. return array('dir' => $base.'img/', 'file' => 'unknown.jpg');
  594. }
  595. return array('dir' => $dir, 'file' => $picture_filename);
  596. }
  597. /**
  598. * Creates new user pfotos in various sizes of a user, or deletes user pfotos.
  599. * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php
  600. * @param int $user_id The user internal identitfication number.
  601. * @param string $file The common file name for the newly created pfotos. It will be checked and modified for compatibility with the file system.
  602. * If full name is provided, path component is ignored.
  603. * If an empty name is provided, then old user photos are deleted only, @see UserManager::delete_user_picture() as the prefered way for deletion.
  604. * @param string $source_file The full system name of the image from which user photos will be created.
  605. * @return string/bool Returns the resulting common file name of created images which usually should be stored in database.
  606. * When deletion is recuested returns empty string. In case of internal error or negative validation returns FALSE.
  607. */
  608. public static function update_user_picture($user_id, $file = null, $source_file = null) {
  609. // Validation 1.
  610. if (empty($user_id)) {
  611. return false;
  612. }
  613. $delete = empty($file);
  614. if (empty($source_file)) {
  615. $source_file = $file;
  616. }
  617. // Configuration options about user photos.
  618. require_once api_get_path(CONFIGURATION_PATH).'profile.conf.php';
  619. // User-reserved directory where photos have to be placed.
  620. $path_info = self::get_user_picture_path_by_id($user_id, 'system', true);
  621. $path = $path_info['dir'];
  622. // If this directory does not exist - we create it.
  623. if (!file_exists($path)) {
  624. $perm = api_get_setting('permissions_for_new_directories');
  625. $perm = octdec(!empty($perm) ? $perm : '0770');
  626. @mkdir($path, $perm, true);
  627. }
  628. // The old photos (if any).
  629. $old_file = $path_info['file'];
  630. // Let us delete them.
  631. if (!empty($old_file)) {
  632. if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
  633. $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
  634. @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
  635. @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
  636. @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
  637. @rename($path.$old_file, $path.$prefix.$old_file);
  638. } else {
  639. @unlink($path.'small_'.$old_file);
  640. @unlink($path.'medium_'.$old_file);
  641. @unlink($path.'big_'.$old_file);
  642. @unlink($path.$old_file);
  643. }
  644. }
  645. // Exit if only deletion has been requested. Return an empty picture name.
  646. if ($delete) {
  647. return '';
  648. }
  649. // Validation 2.
  650. $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
  651. $file = str_replace('\\', '/', $file);
  652. $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
  653. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  654. if (!in_array($extension, $allowed_types)) {
  655. return false;
  656. }
  657. // This is the common name for the new photos.
  658. if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
  659. $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
  660. $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
  661. $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
  662. } else {
  663. $filename = replace_dangerous_char($filename);
  664. if (PREFIX_IMAGE_FILENAME_WITH_UID) {
  665. $filename = uniqid('').'_'.$filename;
  666. }
  667. // We always prefix user photos with user ids, so on setting
  668. // api_get_setting('split_users_upload_directory') === 'true'
  669. // the correspondent directories to be found successfully.
  670. $filename = $user_id.'_'.$filename;
  671. }
  672. // Storing the new photos in 4 versions with various sizes.
  673. $picture_info = @getimagesize($source_file);
  674. $type = $picture_info[2];
  675. $small = self::resize_picture($source_file, 22);
  676. $medium = self::resize_picture($source_file, 85);
  677. $normal = self::resize_picture($source_file, 200);
  678. $big = new image($source_file); // This is the original picture.
  679. $ok = false;
  680. $detected = array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG');
  681. if (in_array($type, array_keys($detected))) {
  682. $ok = $small->send_image($detected[$type], $path.'small_'.$filename)
  683. && $medium->send_image($detected[$type], $path.'medium_'.$filename)
  684. && $normal->send_image($detected[$type], $path.$filename)
  685. && $big->send_image($detected[$type], $path.'big_'.$filename);
  686. }
  687. return $ok ? $filename : false;
  688. }
  689. /**
  690. * Deletes user pfotos.
  691. * Note: This method relies on configuration setting from dokeos/main/inc/conf/profile.conf.php
  692. * @param int $user_id The user internal identitfication number.
  693. * @return string/bool Returns empty string on success, FALSE on error.
  694. */
  695. public static function delete_user_picture($user_id) {
  696. return self::update_user_picture($user_id);
  697. }
  698. /*
  699. -----------------------------------------------------------
  700. PRODUCTIONS FUNCTIONS
  701. -----------------------------------------------------------
  702. */
  703. /**
  704. * Returns an XHTML formatted list of productions for a user, or FALSE if he
  705. * doesn't have any.
  706. *
  707. * If there has been a request to remove a production, the function will return
  708. * without building the list unless forced to do so by the optional second
  709. * parameter. This increases performance by avoiding to read through the
  710. * productions on the filesystem before the removal request has been carried
  711. * out because they'll have to be re-read afterwards anyway.
  712. *
  713. * @param $user_id User id
  714. * @param $force Optional parameter to force building after a removal request
  715. * @return A string containing the XHTML code to dipslay the production list, or FALSE
  716. */
  717. public static function build_production_list($user_id, $force = false, $showdelete = false) {
  718. if (!$force && !empty($_POST['remove_production'])) {
  719. return true; // postpone reading from the filesystem
  720. }
  721. $productions = self::get_user_productions($user_id);
  722. if (empty($productions)) {
  723. return false;
  724. }
  725. $production_path = self::get_user_picture_path_by_id($user_id, 'web', true);
  726. $production_dir = $production_path['dir'].$user_id.'/';
  727. $del_image = api_get_path(WEB_CODE_PATH).'img/delete.gif';
  728. $del_text = get_lang('Delete');
  729. $production_list = '';
  730. if (count($productions) > 0) {
  731. $production_list = '<ul id="productions">';
  732. foreach ($productions as $file) {
  733. $production_list .= '<li><a href="'.$production_dir.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  734. if ($showdelete) {
  735. $production_list .= '<input type="image" name="remove_production['.urlencode($file).']" src="'.$del_image.'" alt="'.$del_text.'" title="'.$del_text.' '.htmlentities($file).'" onclick="javascript: return confirmation(\''.htmlentities($file).'\');" /></li>';
  736. }
  737. }
  738. $production_list .= '</ul>';
  739. }
  740. return $production_list;
  741. }
  742. /**
  743. * Returns an array with the user's productions.
  744. *
  745. * @param $user_id User id
  746. * @return An array containing the user's productions
  747. */
  748. public static function get_user_productions($user_id) {
  749. $production_path = self::get_user_picture_path_by_id($user_id, 'system', true);
  750. $production_repository = $production_path['dir'].$user_id.'/';
  751. $productions = array();
  752. if (is_dir($production_repository)) {
  753. $handle = opendir($production_repository);
  754. while ($file = readdir($handle)) {
  755. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($production_repository.$file)) {
  756. continue; // skip current/parent directory and .htaccess
  757. }
  758. if (preg_match('/('.$user_id.'|[0-9a-f]{13}|saved)_.+\.(png|jpg|jpeg|gif)$/i', $file)) {
  759. // User's photos should not be listed as productions.
  760. continue;
  761. }
  762. $productions[] = $file;
  763. }
  764. }
  765. return $productions; // can be an empty array
  766. }
  767. /**
  768. * Remove a user production.
  769. *
  770. * @param $user_id User id
  771. * @param $production The production to remove
  772. */
  773. public static function remove_user_production($user_id, $production) {
  774. $production_path = self::get_user_picture_path_by_id($user_id, 'system', true);
  775. unlink($production_path['dir'].$user_id.'/'.$production);
  776. }
  777. /**
  778. * Update an extra field. This function is called when a user changes his/her profile
  779. * and by consequence fills or edits his/her extra fields.
  780. *
  781. * @param integer Field ID
  782. * @param array Database columns and their new value
  783. * @return boolean true if field updated, false otherwise
  784. */
  785. public static function update_extra_field($fid, $columns) {
  786. //TODO check that values added are values proposed for enumerated field types
  787. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  788. $fid = Database::escape_string($fid);
  789. $sqluf = "UPDATE $t_uf SET ";
  790. $known_fields = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter');
  791. $safecolumns = array();
  792. foreach ($columns as $index => $newval) {
  793. if (in_array($index, $known_fields)) {
  794. $safecolumns[$index] = Database::escape_string($newval);
  795. $sqluf .= $index." = '".$safecolumns[$index]."', ";
  796. }
  797. }
  798. $time = time();
  799. $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'";
  800. $resuf = Database::query($sqluf, __FILE__, __LINE__);
  801. return $resuf;
  802. }
  803. /**
  804. * Update an extra field value for a given user
  805. * @param integer User ID
  806. * @param string Field variable name
  807. * @param string Field value
  808. * @return boolean true if field updated, false otherwise
  809. */
  810. public static function update_extra_field_value($user_id, $fname, $fvalue = '') {
  811. //TODO check that values added are values proposed for enumerated field types
  812. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  813. $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  814. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  815. $fname = Database::escape_string($fname);
  816. if ($user_id != strval(intval($user_id))) return false;
  817. if ($user_id === false) return false;
  818. $fvalues = '';
  819. //echo '<pre>'; print_r($fvalue);
  820. if (is_array($fvalue)) {
  821. foreach($fvalue as $val) {
  822. $fvalues .= Database::escape_string($val).';';
  823. }
  824. if (!empty($fvalues)) {
  825. $fvalues = substr($fvalues, 0, -1);
  826. }
  827. } else {
  828. $fvalues = Database::escape_string($fvalue);
  829. }
  830. $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
  831. $resuf = Database::query($sqluf, __FILE__, __LINE__);
  832. if (Database::num_rows($resuf) == 1) {
  833. //ok, the field exists
  834. // Check if enumerated field, if the option is available
  835. $rowuf = Database::fetch_array($resuf);
  836. switch ($rowuf['field_type']) {
  837. case 10 :
  838. //Tags are process here
  839. UserManager::process_tags(explode(';', $fvalues), $user_id, $rowuf['id']);
  840. return true;
  841. break;
  842. case 3:
  843. case 4:
  844. case 5:
  845. $sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
  846. $resuo = Database::query($sqluo, __FILE__, __LINE__);
  847. $values = split(';',$fvalues);
  848. if (Database::num_rows($resuo) > 0) {
  849. $check = false;
  850. while ($rowuo = Database::fetch_array($resuo)) {
  851. if (in_array($rowuo['option_value'], $values)) {
  852. $check = true;
  853. break;
  854. }
  855. }
  856. if ($check == false) {
  857. return false; //option value not found
  858. }
  859. } else {
  860. return false; //enumerated type but no option found
  861. }
  862. break;
  863. case 1:
  864. case 2:
  865. default:
  866. break;
  867. }
  868. $tms = time();
  869. $sqlufv = "SELECT * FROM $t_ufv WHERE user_id = $user_id AND field_id = ".$rowuf['id']." ORDER BY id";
  870. $resufv = Database::query($sqlufv, __FILE__, __LINE__);
  871. $n = Database::num_rows($resufv);
  872. if ($n > 1) {
  873. //problem, we already have to values for this field and user combination - keep last one
  874. while ($rowufv = Database::fetch_array($resufv)) {
  875. if ($n > 1) {
  876. $sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
  877. $resd = Database::query($sqld, __FILE__, __LINE__);
  878. $n--;
  879. }
  880. $rowufv = Database::fetch_array($resufv);
  881. if ($rowufv['field_value'] != $fvalues) {
  882. $sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
  883. $resu = Database::query($sqlu, __FILE__, __LINE__);
  884. return($resu ? true : false);
  885. }
  886. return true;
  887. }
  888. }
  889. elseif ($n == 1) {
  890. //we need to update the current record
  891. $rowufv = Database::fetch_array($resufv);
  892. if ($rowufv['field_value'] != $fvalues) {
  893. $sqlu = "UPDATE $t_ufv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowufv['id'];
  894. //error_log('UM::update_extra_field_value: '.$sqlu);
  895. $resu = Database::query($sqlu, __FILE__, __LINE__);
  896. return($resu ? true : false);
  897. }
  898. return true;
  899. } else {
  900. $sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms) " .
  901. "VALUES ($user_id,".$rowuf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
  902. //error_log('UM::update_extra_field_value: '.$sqli);
  903. $resi = Database::query($sqli, __FILE__, __LINE__);
  904. return($resi ? true : false);
  905. }
  906. } else {
  907. return false; //field not found
  908. }
  909. }
  910. /**
  911. * Get an array of extra fieds with field details (type, default value and options)
  912. * @param integer Offset (from which row)
  913. * @param integer Number of items
  914. * @param integer Column on which sorting is made
  915. * @param string Sorting direction
  916. * @param boolean Optional. Whether we get all the fields or just the visible ones
  917. * @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
  918. */
  919. public static function get_extra_fields($from = 0, $number_of_items = 0, $column = 5, $direction = 'ASC', $all_visibility = true) {
  920. $fields = array();
  921. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  922. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  923. $columns = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_filter', 'tms');
  924. $column = intval($column);
  925. $sort_direction = '';
  926. if (in_array(strtoupper($direction), array('ASC', 'DESC'))) {
  927. $sort_direction = strtoupper($direction);
  928. }
  929. $sqlf = "SELECT * FROM $t_uf ";
  930. if ($all_visibility == false) {
  931. $sqlf .= " WHERE field_visible = 1 ";
  932. }
  933. $sqlf .= " ORDER BY ".$columns[$column]." $sort_direction " ;
  934. if ($number_of_items != 0) {
  935. $sqlf .= " LIMIT ".Database::escape_string($from).','.Database::escape_string($number_of_items);
  936. }
  937. $resf = Database::query($sqlf, __FILE__, __LINE__);
  938. if (Database::num_rows($resf) > 0) {
  939. while($rowf = Database::fetch_array($resf)) {
  940. $fields[$rowf['id']] = array(
  941. 0 => $rowf['id'],
  942. 1 => $rowf['field_variable'],
  943. 2 => $rowf['field_type'],
  944. //3 => (empty($rowf['field_display_text']) ? '' : get_lang($rowf['field_display_text'], '')),
  945. // Temporarily removed auto-translation. Need update to get_lang() to know if translation exists (todo)
  946. // Ivan, 15-SEP-2009: get_lang() has been modified accordingly in order this issue to be solved.
  947. 3 => (empty($rowf['field_display_text']) ? '' : $rowf['field_display_text']),
  948. 4 => $rowf['field_default_value'],
  949. 5 => $rowf['field_order'],
  950. 6 => $rowf['field_visible'],
  951. 7 => $rowf['field_changeable'],
  952. 8 => $rowf['field_filter'],
  953. 9 => array()
  954. );
  955. $sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id']." ORDER BY option_order ASC";
  956. $reso = Database::query($sqlo, __FILE__, __LINE__);
  957. if (Database::num_rows($reso) > 0) {
  958. while ($rowo = Database::fetch_array($reso)) {
  959. $fields[$rowf['id']][9][$rowo['id']] = array(
  960. 0 => $rowo['id'],
  961. 1 => $rowo['option_value'],
  962. //2 => (empty($rowo['option_display_text']) ? '' : get_lang($rowo['option_display_text'], '')),
  963. 2 => (empty($rowo['option_display_text']) ? '' : $rowo['option_display_text']),
  964. 3 => $rowo['option_order']
  965. );
  966. }
  967. }
  968. }
  969. }
  970. return $fields;
  971. }
  972. /**
  973. * Get the list of options attached to an extra field
  974. * @param string $fieldname the name of the field
  975. * @return array the list of options
  976. */
  977. public static function get_extra_field_options($field_name) {
  978. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  979. $t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  980. $sql = 'SELECT options.*
  981. FROM '.$t_ufo.' options
  982. INNER JOIN '.$t_uf.' fields
  983. ON fields.id = options.field_id
  984. AND fields.field_variable="'.Database::escape_string($field_name).'"';
  985. $rs = Database::query($sql, __FILE__, __LINE__);
  986. return Database::store_result($rs);
  987. }
  988. /**
  989. * Get the number of extra fields currently recorded
  990. * @param boolean Optional switch. true (default) returns all fields, false returns only visible fields
  991. * @return integer Number of fields
  992. */
  993. public static function get_number_of_extra_fields($all_visibility = true) {
  994. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  995. $sqlf = "SELECT * FROM $t_uf ";
  996. if ($all_visibility == false) {
  997. $sqlf .= " WHERE field_visible = 1 ";
  998. }
  999. $sqlf .= " ORDER BY field_order";
  1000. $resf = Database::query($sqlf, __FILE__, __LINE__);
  1001. return Database::num_rows($resf);
  1002. }
  1003. /**
  1004. * Creates a new extra field
  1005. * @param string Field's internal variable name
  1006. * @param int Field's type
  1007. * @param string Field's language var name
  1008. * @param string Field's default value
  1009. * @param string Optional comma-separated list of options to provide for select and radio
  1010. * @return int new user id - if the new user creation succeeds, false otherwise
  1011. */
  1012. public static function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
  1013. // database table definition
  1014. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1015. $table_field_options= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1016. // First check wether the login already exists
  1017. if (self::is_extra_field_available($fieldvarname)) {
  1018. return api_set_failure('login-pass already taken');
  1019. }
  1020. $sql = "SELECT MAX(field_order) FROM $table_field";
  1021. $res = Database::query($sql, __FILE__, __LINE__);
  1022. $order = 0;
  1023. if (Database::num_rows($res) > 0) {
  1024. $row = Database::fetch_array($res);
  1025. $order = $row[0]+1;
  1026. }
  1027. $time = time();
  1028. $sql = "INSERT INTO $table_field
  1029. SET field_type = '".Database::escape_string($fieldtype)."',
  1030. field_variable = '".Database::escape_string($fieldvarname)."',
  1031. field_display_text = '".Database::escape_string($fieldtitle)."',
  1032. field_default_value = '".Database::escape_string($fielddefault)."',
  1033. field_order = '$order',
  1034. tms = FROM_UNIXTIME($time)";
  1035. $result = Database::query($sql);
  1036. if ($result) {
  1037. //echo "id returned";
  1038. $return = Database::insert_id();
  1039. } else {
  1040. //echo "false - failed" ;
  1041. return false;
  1042. }
  1043. if (!empty($fieldoptions) && in_array($fieldtype, array(USER_FIELD_TYPE_RADIO, USER_FIELD_TYPE_SELECT, USER_FIELD_TYPE_SELECT_MULTIPLE, USER_FIELD_TYPE_DOUBLE_SELECT))) {
  1044. if ($fieldtype == USER_FIELD_TYPE_DOUBLE_SELECT) {
  1045. $twolist = explode('|', $fieldoptions);
  1046. $counter = 0;
  1047. foreach ($twolist as $individual_list) {
  1048. $splitted_individual_list = split(';', $individual_list);
  1049. foreach ($splitted_individual_list as $individual_list_option) {
  1050. //echo 'counter:'.$counter;
  1051. if ($counter == 0) {
  1052. $list[] = $individual_list_option;
  1053. } else {
  1054. $list[] = str_repeat('*', $counter).$individual_list_option;
  1055. }
  1056. }
  1057. $counter++;
  1058. }
  1059. } else {
  1060. $list = split(';', $fieldoptions);
  1061. }
  1062. foreach ($list as $option) {
  1063. $option = Database::escape_string($option);
  1064. $sql = "SELECT * FROM $table_field_options WHERE field_id = $return AND option_value = '".$option."'";
  1065. $res = Database::query($sql, __FILE__, __LINE__);
  1066. if (Database::num_rows($res) > 0) {
  1067. //the option already exists, do nothing
  1068. } else {
  1069. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = $return";
  1070. $res = Database::query($sql, __FILE__, __LINE__);
  1071. $max = 1;
  1072. if (Database::num_rows($res) > 0) {
  1073. $row = Database::fetch_array($res);
  1074. $max = $row[0] + 1;
  1075. }
  1076. $time = time();
  1077. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ($return,'$option','$option',$max,FROM_UNIXTIME($time))";
  1078. $res = Database::query($sql, __FILE__, __LINE__);
  1079. if ($res === false) {
  1080. $return = false;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. return $return;
  1086. }
  1087. /**
  1088. * Save the changes in the definition of the extra user profile field
  1089. * The function is called after you (as admin) decide to store the changes you have made to one of the fields you defined
  1090. *
  1091. * There is quite some logic in this field
  1092. * 1. store the changes to the field (tupe, name, label, default text)
  1093. * 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
  1094. * the options (and choices) that do no longer have to appear. We cannot remove all options and choices because if you remove them all
  1095. * and simply re-add them all then all the user who have already filled this form will loose their selected value.
  1096. * 3. we add the options that are newly added
  1097. *
  1098. * @example current options are a;b;c and the user changes this to a;b;x (removing c and adding x)
  1099. * we first remove c (and also the entry in the option_value table for the users who have chosen this)
  1100. * we then add x
  1101. * a and b are neither removed nor added
  1102. *
  1103. * @param integer $fieldid the id of the field we are editing
  1104. * @param string $fieldvarname the internal variable name of the field
  1105. * @param int $fieldtype the type of the field
  1106. * @param string $fieldtitle the title of the field
  1107. * @param string $fielddefault the default value of the field
  1108. * @param string $fieldoptions Optional comma-separated list of options to provide for select and radio
  1109. * @return boolean true
  1110. *
  1111. *
  1112. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1113. * @version July 2008
  1114. * @since Dokeos 1.8.6
  1115. */
  1116. public static function save_extra_field_changes($fieldid, $fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '') {
  1117. // database table definition
  1118. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1119. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1120. $table_field_options_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1121. // we first update the field definition with the new values
  1122. $time = time();
  1123. $sql = "UPDATE $table_field
  1124. SET field_type = '".Database::escape_string($fieldtype)."',
  1125. field_variable = '".Database::escape_string($fieldvarname)."',
  1126. field_display_text = '".Database::escape_string($fieldtitle)."',
  1127. field_default_value = '".Database::escape_string($fielddefault)."',
  1128. tms = FROM_UNIXTIME($time)
  1129. WHERE id = '".Database::escape_string($fieldid)."'";
  1130. $result = Database::query($sql, __FILE__, __LINE__);
  1131. // we create an array with all the options (will be used later in the script)
  1132. if ($fieldtype == USER_FIELD_TYPE_DOUBLE_SELECT) {
  1133. $twolist = explode('|', $fieldoptions);
  1134. $counter = 0;
  1135. foreach ($twolist as $individual_list) {
  1136. $splitted_individual_list = split(';', $individual_list);
  1137. foreach ($splitted_individual_list as $individual_list_option) {
  1138. //echo 'counter:'.$counter;
  1139. if ($counter == 0) {
  1140. $list[] = trim($individual_list_option);
  1141. } else {
  1142. $list[] = str_repeat('*', $counter).trim($individual_list_option);
  1143. }
  1144. }
  1145. $counter++;
  1146. }
  1147. } else {
  1148. $templist = split(';', $fieldoptions);
  1149. $list = array_map('trim', $templist);
  1150. }
  1151. // Remove all the field options (and also the choices of the user) that are NOT in the new list of options
  1152. $sql = "SELECT * FROM $table_field_options WHERE option_value NOT IN ('".implode("','", $list)."') AND field_id = '".Database::escape_string($fieldid)."'";
  1153. $result = Database::query($sql, __FILE__, __LINE__);
  1154. $return['deleted_options'] = 0;
  1155. while ($row = Database::fetch_array($result)) {
  1156. // deleting the option
  1157. $sql_delete_option = "DELETE FROM $table_field_options WHERE id='".Database::escape_string($row['id'])."'";
  1158. $result_delete_option = Database::query($sql_delete_option, __FILE__, __LINE__);
  1159. $return['deleted_options']++;
  1160. // deleting the answer of the user who has chosen this option
  1161. $sql_delete_option_value = "DELETE FROM $table_field_options_values WHERE field_id = '".Database::escape_string($fieldid)."' AND field_value = '".Database::escape_string($row['option_value'])."'";
  1162. $result_delete_option_value = Database::query($sql_delete_option_value, __FILE__, __LINE__);
  1163. $return['deleted_option_values'] = $return['deleted_option_values'] + Database::affected_rows();
  1164. }
  1165. // we now try to find the field options that are newly added
  1166. $sql = "SELECT * FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
  1167. $result = Database::query($sql, __FILE__, __LINE__);
  1168. while ($row = Database::fetch_array($result)) {
  1169. // we remove every option that is already in the database from the $list
  1170. if (in_array(trim($row['option_display_text']), $list)) {
  1171. $key = array_search(trim($row['option_display_text']), $list);
  1172. unset($list[$key]);
  1173. }
  1174. }
  1175. // we store the new field options in the database
  1176. foreach ($list as $key => $option) {
  1177. $sql = "SELECT MAX(option_order) FROM $table_field_options WHERE field_id = '".Database::escape_string($fieldid)."'";
  1178. $res = Database::query($sql, __FILE__, __LINE__);
  1179. $max = 1;
  1180. if (Database::num_rows($res) > 0) {
  1181. $row = Database::fetch_array($res);
  1182. $max = $row[0] + 1;
  1183. }
  1184. $time = time();
  1185. $sql = "INSERT INTO $table_field_options (field_id,option_value,option_display_text,option_order,tms) VALUES ('".Database::escape_string($fieldid)."','".Database::escape_string($option)."','".Database::escape_string($option)."',$max,FROM_UNIXTIME($time))";
  1186. $result = Database::query($sql, __FILE__, __LINE__);
  1187. }
  1188. return true;
  1189. }
  1190. /**
  1191. * Check if a field is available
  1192. * @param string the wanted fieldname
  1193. * @return boolean true if the wanted username is available
  1194. */
  1195. public static function is_extra_field_available($fieldname) {
  1196. $t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
  1197. $sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
  1198. $res = Database::query($sql, __FILE__, __LINE__);
  1199. return Database::num_rows($res) > 0;
  1200. }
  1201. /**
  1202. * Gets user extra fields data
  1203. * @param integer User ID
  1204. * @param boolean Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
  1205. * @param boolean Whether to return invisible fields as well
  1206. * @param boolean Whether to split multiple-selection fields or not
  1207. * @return array Array of fields => value for the given user
  1208. */
  1209. public static function get_extra_user_data($user_id, $prefix = false, $all_visibility = true, $splitmultiple = false) {
  1210. // A sanity check.
  1211. if (empty($user_id)) {
  1212. $user_id = 0;
  1213. } else {
  1214. if ($user_id != strval(intval($user_id))) return array();
  1215. }
  1216. $extra_data = array();
  1217. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1218. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1219. $user_id = Database::escape_string($user_id);
  1220. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1221. if ($all_visibility == false) {
  1222. $sql .= " WHERE f.field_visible = 1 ";
  1223. }
  1224. $sql .= " ORDER BY f.field_order";
  1225. $res = Database::query($sql, __FILE__, __LINE__);
  1226. if (Database::num_rows($res) > 0) {
  1227. while ($row = Database::fetch_array($res)) {
  1228. $sqlu = "SELECT field_value as fval " .
  1229. " FROM $t_ufv " .
  1230. " WHERE field_id=".$row['id']."" .
  1231. " AND user_id=".$user_id;
  1232. $resu = Database::query($sqlu, __FILE__, __LINE__);
  1233. $fval = '';
  1234. // get default value
  1235. $sql_df = "SELECT field_default_value as fval_df " .
  1236. " FROM $t_uf " .
  1237. " WHERE id=".$row['id'];
  1238. $res_df = Database::query($sql_df, __FILE__, __LINE__);
  1239. if (Database::num_rows($resu) > 0) {
  1240. $rowu = Database::fetch_array($resu);
  1241. $fval = $rowu['fval'];
  1242. if ($row['type'] == USER_FIELD_TYPE_SELECT_MULTIPLE) {
  1243. $fval = split(';',$rowu['fval']);
  1244. }
  1245. } else {
  1246. $row_df = Database::fetch_array($res_df);
  1247. $fval = $row_df['fval_df'];
  1248. }
  1249. if ($prefix) {
  1250. if ($row['type'] == USER_FIELD_TYPE_RADIO) {
  1251. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  1252. } else {
  1253. $extra_data['extra_'.$row['fvar']] = $fval;
  1254. }
  1255. } else {
  1256. if ($row['type'] == USER_FIELD_TYPE_RADIO) {
  1257. $extra_data['extra_'.$row['fvar']]['extra_'.$row['fvar']] = $fval;
  1258. } else {
  1259. $extra_data[$row['fvar']] = $fval;
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return $extra_data;
  1265. }
  1266. /** Get extra user data by field
  1267. * @param int user ID
  1268. * @param string the internal variable name of the field
  1269. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  1270. */
  1271. public static function get_extra_user_data_by_field($user_id, $field_variable, $prefix = false, $all_visibility = true, $splitmultiple = false) {
  1272. // A sanity check.
  1273. if (empty($user_id)) {
  1274. $user_id = 0;
  1275. } else {
  1276. if ($user_id != strval(intval($user_id))) return array();
  1277. }
  1278. $extra_data = array();
  1279. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1280. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1281. $user_id = Database::escape_string($user_id);
  1282. $sql = "SELECT f.id as id, f.field_variable as fvar, f.field_type as type FROM $t_uf f ";
  1283. $sql .= " WHERE f.field_variable = '$field_variable' ";
  1284. if ($all_visibility == false) {
  1285. $sql .= " AND f.field_visible = 1 ";
  1286. }
  1287. $sql .= " ORDER BY f.field_order";
  1288. $res = Database::query($sql, __FILE__, __LINE__);
  1289. if (Database::num_rows($res) > 0) {
  1290. while ($row = Database::fetch_array($res)) {
  1291. $sqlu = "SELECT field_value as fval " .
  1292. " FROM $t_ufv " .
  1293. " WHERE field_id=".$row['id']."" .
  1294. " AND user_id=".$user_id;
  1295. $resu = Database::query($sqlu, __FILE__, __LINE__);
  1296. $fval = '';
  1297. if (Database::num_rows($resu) > 0) {
  1298. $rowu = Database::fetch_array($resu);
  1299. $fval = $rowu['fval'];
  1300. if ($row['type'] == USER_FIELD_TYPE_SELECT_MULTIPLE) {
  1301. $fval = split(';',$rowu['fval']);
  1302. }
  1303. }
  1304. if ($prefix) {
  1305. $extra_data['extra_'.$row['fvar']] = $fval;
  1306. } else {
  1307. $extra_data[$row['fvar']] = $fval;
  1308. }
  1309. }
  1310. }
  1311. return $extra_data;
  1312. }
  1313. /**
  1314. * Get the extra field information for a certain field (the options as well)
  1315. * @param int The name of the field we want to know everything about
  1316. * @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)
  1317. * @author Julio Montoya
  1318. * @since Dokeos 1.8.6
  1319. */
  1320. public static function get_extra_field_information_by_name($field_variable, $fuzzy = false) {
  1321. // database table definition
  1322. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1323. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1324. // all the information of the field
  1325. $sql = "SELECT * FROM $table_field WHERE field_variable='".Database::escape_string($field_variable)."'";
  1326. $result = Database::query($sql, __FILE__, __LINE__);
  1327. $return = Database::fetch_array($result);
  1328. // all the options of the field
  1329. $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($return['id'])."' ORDER BY option_order ASC";
  1330. $result = Database::query($sql, __FILE__, __LINE__);
  1331. while ($row = Database::fetch_array($result)) {
  1332. $return['options'][$row['id']] = $row;
  1333. }
  1334. return $return;
  1335. }
  1336. public static function get_all_extra_field_by_type($field_type) {
  1337. // database table definition
  1338. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1339. // all the information of the field
  1340. $sql = "SELECT * FROM $table_field WHERE field_type='".Database::escape_string($field_type)."'";
  1341. $result = Database::query($sql, __FILE__, __LINE__);
  1342. while ($row = Database::fetch_array($result)) {
  1343. $return[] = $row['id'];
  1344. }
  1345. return $return;
  1346. }
  1347. /**
  1348. * Get all the extra field information of a certain field (also the options)
  1349. *
  1350. * @param int $field_name the name of the field we want to know everything of
  1351. * @return array $return containing all th information about the extra profile field
  1352. * @author Julio Montoya
  1353. * @since Dokeos 1.8.6
  1354. */
  1355. public static function get_extra_field_information($field_id) {
  1356. // database table definition
  1357. $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1358. $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1359. // all the information of the field
  1360. $sql = "SELECT * FROM $table_field WHERE id='".Database::escape_string($field_id)."'";
  1361. $result = Database::query($sql, __FILE__, __LINE__);
  1362. $return = Database::fetch_array($result);
  1363. // all the options of the field
  1364. $sql = "SELECT * FROM $table_field_options WHERE field_id='".Database::escape_string($field_id)."' ORDER BY option_order ASC";
  1365. $result = Database::query($sql, __FILE__, __LINE__);
  1366. while ($row = Database::fetch_array($result)) {
  1367. $return['options'][$row['id']] = $row;
  1368. }
  1369. return $return;
  1370. }
  1371. /** Get extra user data by value
  1372. * @param string the internal variable name of the field
  1373. * @param string the internal value of the field
  1374. * @return array with extra data info of a user i.e array('field_variable'=>'value');
  1375. */
  1376. public static function get_extra_user_data_by_value($field_variable, $field_value, $all_visibility = true) {
  1377. $extra_data = array();
  1378. $table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  1379. $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  1380. $table_user_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
  1381. $where = '';
  1382. /*
  1383. if (is_array($field_variable_array) && is_array($field_value_array)) {
  1384. if (count($field_variable_array) == count($field_value_array)) {
  1385. $field_var_count = count($field_variable_array);
  1386. for ($i = 0; $i < $field_var_count; $i++) {
  1387. if ($i != 0 && $i != $field_var_count) {
  1388. $where.= ' AND ';
  1389. }
  1390. $where.= "field_variable='".Database::escape_string($field_variable_array[$i])."' AND user_field_options.id='".Database::escape_string($field_value_array[$i])."'";
  1391. }
  1392. }
  1393. }*/
  1394. $where = "field_variable='".Database::escape_string($field_variable)."' AND field_value='".Database::escape_string($field_value)."'";
  1395. $sql = "SELECT user_id FROM $table_user_field user_field INNER JOIN $table_user_field_values user_field_values
  1396. ON (user_field.id = user_field_values.field_id)
  1397. WHERE $where";
  1398. if ($all_visibility == true) {
  1399. $sql .= " AND user_field.field_visible = 1 ";
  1400. } else {
  1401. $sql .= " AND user_field.field_visible = 0 ";
  1402. }
  1403. $res = Database::query($sql, __FILE__, __LINE__);
  1404. $result_data = array();
  1405. if (Database::num_rows($res) > 0) {
  1406. while ($row = Database::fetch_array($res)) {
  1407. $result_data[] = $row['user_id'];
  1408. }
  1409. }
  1410. return $result_data;
  1411. }
  1412. /**
  1413. * Gives a list of [session_category][session_id] for the current user.
  1414. * @param integer $user_id
  1415. * @param boolean whether to fill the first element or not (to give space for courses out of categories)
  1416. * @param boolean optional true if limit time from session is over, false otherwise
  1417. * @return array list of statuses [session_category][session_id]
  1418. * @todo ensure multiple access urls are managed correctly
  1419. */
  1420. public static function get_sessions_by_category ($user_id, $fill_first = false, $is_time_over = false) {
  1421. // Database Table Definitions
  1422. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  1423. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1424. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  1425. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1426. if ($user_id != strval(intval($user_id))) return array();
  1427. $categories = array();
  1428. if ($fill_first) {
  1429. $categories[0] = array();
  1430. }
  1431. /*
  1432. //we filter the courses from the URL
  1433. $join_access_url=$where_access_url='';
  1434. global $_configuration;
  1435. if ($_configuration['multiple_access_urls']==true) {
  1436. $access_url_id = api_get_current_access_url_id();
  1437. if($access_url_id!=-1) {
  1438. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1439. $join_access_url= "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  1440. $where_access_url=" AND access_url_id = $access_url_id ";
  1441. }
  1442. }
  1443. */
  1444. // get the list of sessions where the user is subscribed as student
  1445. $condition_date_end = "";
  1446. if ($is_time_over) {
  1447. $condition_date_end = " AND date_end < CURDATE() AND date_end != '0000-00-00' ";
  1448. } else {
  1449. $condition_date_end = " AND (date_end >= CURDATE() OR date_end = '0000-00-00') ";
  1450. }
  1451. $sessions_sql = "SELECT DISTINCT id, session_category_id
  1452. FROM $tbl_session_user, $tbl_session
  1453. WHERE id_session=id AND id_user=$user_id $condition_date_end
  1454. ORDER BY session_category_id, date_start, date_end";
  1455. $result = Database::query($sessions_sql,__FILE__,__LINE__);
  1456. if (Database::num_rows($result)>0) {
  1457. while ($row = Database::fetch_array($result)) {
  1458. $categories[$row['session_category_id']][] = $row['id'];
  1459. }
  1460. }
  1461. // get the list of sessions where the user is subscribed as coach in a course $tbl_session_course_user
  1462. /*$sessions_sql = "SELECT DISTINCT id, session_category_id
  1463. FROM $tbl_session as session
  1464. INNER JOIN $tbl_session_course as session_rel_course
  1465. ON session_rel_course.id_session = session.id
  1466. AND session_rel_course.id_coach = $user_id
  1467. ORDER BY session_category_id, date_start, date_end";*/
  1468. $sessions_sql = "SELECT DISTINCT id, session_category_id
  1469. FROM $tbl_session as session
  1470. INNER JOIN $tbl_session_course_user as session_rel_course_user
  1471. ON session_rel_course_user.id_session = session.id
  1472. AND session_rel_course_user.id_user = $user_id
  1473. AND session_rel_course_user.status = 2 $condition_date_end
  1474. ORDER BY session_category_id, date_start, date_end";
  1475. $result = Database::query($sessions_sql,__FILE__,__LINE__);
  1476. if (Database::num_rows($result)>0) {
  1477. while ($row = Database::fetch_array($result)) {
  1478. $categories[$row['session_category_id']][] = $row['id'];
  1479. }
  1480. }
  1481. // get the list of sessions where the user is subscribed as coach
  1482. $sessions_sql = "SELECT DISTINCT id, session_category_id
  1483. FROM $tbl_session as session
  1484. WHERE session.id_coach = $user_id $condition_date_end
  1485. ORDER BY session_category_id, date_start, date_end";
  1486. $result = Database::query($sessions_sql,__FILE__,__LINE__);
  1487. if (Database::num_rows($result)>0) {
  1488. while ($row = Database::fetch_array($result)) {
  1489. $categories[$row['session_category_id']][] = $row['id'];
  1490. }
  1491. }
  1492. return $categories;
  1493. }
  1494. /**
  1495. * Gives a list of [session_id-course_code] => [status] for the current user.
  1496. * @param integer $user_id
  1497. * @return array list of statuses (session_id-course_code => status)
  1498. */
  1499. public static function get_personal_session_course_list($user_id) {
  1500. // Database Table Definitions
  1501. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1502. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  1503. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1504. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1505. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  1506. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1507. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  1508. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1509. if ($user_id != strval(intval($user_id))) return array();
  1510. //we filter the courses from the URL
  1511. $join_access_url = $where_access_url = '';
  1512. global $_configuration;
  1513. if ($_configuration['multiple_access_urls'] == true) {
  1514. $access_url_id = api_get_current_access_url_id();
  1515. if ($access_url_id != -1) {
  1516. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1517. $join_access_url = "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  1518. $where_access_url = " AND access_url_id = $access_url_id ";
  1519. }
  1520. }
  1521. // variable initialisation
  1522. $personal_course_list_sql = '';
  1523. $personal_course_list = array();
  1524. //Courses in which we suscribed out of any session
  1525. /*$personal_course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i,
  1526. course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort,
  1527. course_rel_user.user_course_cat user_course_cat
  1528. FROM ".$tbl_course." course,".$main_course_user_table." course_rel_user
  1529. WHERE course.code = course_rel_user.course_code"."
  1530. AND course_rel_user.user_id = '".$user_id."'
  1531. ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC,i";*/
  1532. $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
  1533. $personal_course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
  1534. FROM ".$tbl_course_user." course_rel_user
  1535. LEFT JOIN ".$tbl_course." course
  1536. ON course.code = course_rel_user.course_code
  1537. LEFT JOIN ".$tbl_user_course_category." user_course_category
  1538. ON course_rel_user.user_course_cat = user_course_category.id
  1539. $join_access_url
  1540. WHERE course_rel_user.user_id = '".$user_id."' $where_access_url
  1541. ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
  1542. $course_list_sql_result = api_sql_query($personal_course_list_sql, __FILE__, __LINE__);
  1543. //var_dump($course_list_sql_result); exit;
  1544. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1545. $personal_course_list[] = $result_row;
  1546. }
  1547. // get the list of sessions where the user is subscribed as student
  1548. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
  1549. FROM $tbl_session_user, $tbl_session
  1550. WHERE id_session=id AND id_user=$user_id
  1551. AND (date_start <= CURDATE() AND date_end >= CURDATE() OR date_start='0000-00-00')
  1552. ORDER BY date_start, date_end, name";
  1553. $result = Database::query($sessions_sql,__FILE__,__LINE__);
  1554. $sessions=Database::store_result($result);
  1555. $sessions = array_merge($sessions , Database::store_result($result));
  1556. // get the list of sessions where the user is subscribed as student where visibility = SESSION_VISIBLE_READ_ONLY = 1 SESSION_VISIBLE = 2
  1557. $sessions_out_date_sql = "SELECT DISTINCT id, name, date_start, date_end
  1558. FROM $tbl_session_user, $tbl_session
  1559. WHERE id_session=id AND id_user=$user_id
  1560. AND (date_end <= CURDATE() AND date_end<>'0000-00-00') AND (visibility = ".SESSION_VISIBLE_READ_ONLY." || visibility = ".SESSION_VISIBLE.")
  1561. ORDER BY date_start, date_end, name";
  1562. $result_out_date = Database::query($sessions_out_date_sql,__FILE__,__LINE__);
  1563. $sessions_out_date=Database::store_result($result_out_date);
  1564. $sessions = array_merge($sessions , $sessions_out_date);
  1565. // get the list of sessions where the user is subscribed as coach in a course
  1566. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end, DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY), ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY)
  1567. FROM $tbl_session as session
  1568. INNER JOIN $tbl_session_course_user as session_rel_course_user
  1569. ON session_rel_course_user.id_session = session.id
  1570. AND session_rel_course_user.id_user = $user_id AND session_rel_course_user.status = 2
  1571. WHERE (CURDATE() >= DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY)
  1572. AND CURDATE() <= ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY)
  1573. OR date_start='0000-00-00')
  1574. ORDER BY date_start, date_end, name";
  1575. $result = Database::query($sessions_sql, __FILE__, __LINE__);
  1576. $session_is_coach = Database::store_result($result);
  1577. $sessions = array_merge($sessions, $session_is_coach);
  1578. // get the list of sessions where the user is subscribed as coach
  1579. $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
  1580. FROM $tbl_session as session
  1581. WHERE session.id_coach = $user_id
  1582. AND (CURDATE() >= DATE_SUB(date_start, INTERVAL nb_days_access_before_beginning DAY)
  1583. AND CURDATE() <= ADDDATE(date_end, INTERVAL nb_days_access_after_end DAY)
  1584. OR date_start='0000-00-00')
  1585. ORDER BY date_start, date_end, name";
  1586. $result = Database::query($sessions_sql, __FILE__, __LINE__);
  1587. $sessions = array_merge($sessions, Database::store_result($result));
  1588. if (api_is_allowed_to_create_course()) {
  1589. foreach($sessions as $enreg) {
  1590. $id_session = $enreg['id'];
  1591. $personal_course_list_sql = "SELECT DISTINCT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t, email, course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name
  1592. FROM $tbl_session_course_user as session_course_user
  1593. INNER JOIN $tbl_course AS course
  1594. ON course.code = session_course_user.course_code
  1595. INNER JOIN $tbl_session as session
  1596. ON session.id = session_course_user.id_session
  1597. LEFT JOIN $tbl_user as user
  1598. ON user.user_id = session_course_user.id_user
  1599. WHERE session_course_user.id_session = $id_session
  1600. AND ((session_course_user.id_user=$user_id AND session_course_user.status = 2) OR session.id_coach=$user_id)
  1601. ORDER BY i";
  1602. $course_list_sql_result = Database::query($personal_course_list_sql, __FILE__, __LINE__);
  1603. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1604. $result_row['s'] = 2;
  1605. $key = $result_row['id_session'].' - '.$result_row['k'];
  1606. $personal_course_list[$key] = $result_row;
  1607. }
  1608. }
  1609. }
  1610. foreach ($sessions as $enreg) {
  1611. $id_session = $enreg['id'];
  1612. /*$personal_course_list_sql = "SELECT DISTINCT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, CONCAT(user.lastname,' ',user.firstname) t, email, course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, IF(session_course.id_coach = ".$user_id.",'2', '5')
  1613. FROM $tbl_session_course as session_course
  1614. INNER JOIN $tbl_course AS course
  1615. ON course.code = session_course.course_code
  1616. LEFT JOIN $tbl_user as user
  1617. ON user.user_id = session_course.id_coach
  1618. INNER JOIN $tbl_session_course_user
  1619. ON $tbl_session_course_user.id_session = $id_session
  1620. AND $tbl_session_course_user.id_user = $user_id
  1621. INNER JOIN $tbl_session as session
  1622. ON session_course.id_session = session.id
  1623. WHERE session_course.id_session = $id_session
  1624. ORDER BY i";
  1625. */
  1626. // 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
  1627. $personal_course_list_sql = "SELECT distinct course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, CONCAT(user.lastname,' ',user.firstname) t, email, course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5')
  1628. FROM $tbl_session_course_user as session_course_user
  1629. INNER JOIN $tbl_course AS course
  1630. ON course.code = session_course_user.course_code AND session_course_user.id_session = $id_session
  1631. INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
  1632. LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
  1633. WHERE session_course_user.id_user = $user_id ORDER BY i";
  1634. $course_list_sql_result = Database::query($personal_course_list_sql, __FILE__, __LINE__);
  1635. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1636. $key = $result_row['id_session'].' - '.$result_row['k'];
  1637. $result_row['s'] = $result_row['14'];
  1638. if (!isset($personal_course_list[$key])) {
  1639. $personal_course_list[$key] = $result_row;
  1640. }
  1641. }
  1642. }
  1643. //print_r($personal_course_list);
  1644. return $personal_course_list;
  1645. }
  1646. /**
  1647. * Gives a list of courses for the given user in the given session
  1648. * @param integer $user_id
  1649. * @return array list of statuses (session_id-course_code => status)
  1650. */
  1651. public static function get_courses_list_by_session ($user_id, $session_id) {
  1652. // Database Table Definitions
  1653. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1654. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  1655. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1656. $user_id = intval($user_id);
  1657. $session_id = intval($session_id);
  1658. //we filter the courses from the URL
  1659. $join_access_url=$where_access_url='';
  1660. global $_configuration;
  1661. if ($_configuration['multiple_access_urls']==true) {
  1662. $access_url_id = api_get_current_access_url_id();
  1663. if($access_url_id!=-1) {
  1664. $tbl_url_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1665. $join_access_url= "LEFT JOIN $tbl_url_course url_rel_course ON url_rel_course.course_code= course.code";
  1666. $where_access_url=" AND access_url_id = $access_url_id ";
  1667. }
  1668. }
  1669. // variable initialisation
  1670. $personal_course_list_sql = '';
  1671. $personal_course_list = array();
  1672. $courses = array();
  1673. // 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
  1674. $personal_course_list_sql = "SELECT distinct scu.course_code as code
  1675. FROM $tbl_session_course_user as scu
  1676. $join_access_url
  1677. WHERE scu.id_user = $user_id
  1678. AND scu.id_session = $session_id
  1679. $where_access_url
  1680. ORDER BY code";
  1681. $course_list_sql_result = Database::query($personal_course_list_sql, __FILE__, __LINE__);
  1682. if (Database::num_rows($course_list_sql_result)>0) {
  1683. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1684. $result_row['status'] = 5;
  1685. if (!in_array($result_row['code'],$courses)) {
  1686. $personal_course_list[] = $result_row;
  1687. $courses[] = $result_row['code'];
  1688. }
  1689. }
  1690. }
  1691. if(api_is_allowed_to_create_course()) {
  1692. $personal_course_list_sql = "SELECT DISTINCT scu.course_code as code
  1693. FROM $tbl_session_course_user as scu, $tbl_session as s
  1694. $join_access_url
  1695. WHERE s.id = $session_id
  1696. AND scu.id_session = s.id
  1697. AND ((scu.id_user=$user_id AND scu.status=2) OR s.id_coach=$user_id)
  1698. $where_access_url
  1699. ORDER BY code";
  1700. $course_list_sql_result = Database::query($personal_course_list_sql, __FILE__, __LINE__);
  1701. if (Database::num_rows($course_list_sql_result)>0) {
  1702. while ($result_row = Database::fetch_array($course_list_sql_result)) {
  1703. $result_row['status'] = 2;
  1704. if (!in_array($result_row['code'],$courses)) {
  1705. $personal_course_list[] = $result_row;
  1706. $courses[] = $result_row['code'];
  1707. }
  1708. }
  1709. }
  1710. }
  1711. return $personal_course_list;
  1712. }
  1713. /**
  1714. * Get user id from a username
  1715. * @param string Username
  1716. * @return int User ID (or false if not found)
  1717. */
  1718. public static function get_user_id_from_username($username) {
  1719. $username = Database::escape_string($username);
  1720. $t_user = Database::get_main_table(TABLE_MAIN_USER);
  1721. $sql = "SELECT user_id FROM $t_user WHERE username = '$username'";
  1722. $res = Database::query($sql, __FILE__, __LINE__);
  1723. if ($res === false) { return false; }
  1724. if (Database::num_rows($res) !== 1) { return false; }
  1725. $row = Database::fetch_array($res);
  1726. return $row['user_id'];
  1727. }
  1728. /**
  1729. * Get the users files upload from his share_folder
  1730. * @param string User ID
  1731. * @param string course directory
  1732. * @param int deprecated
  1733. * @return int User ID (or false if not found)
  1734. */
  1735. public static function get_user_upload_files_by_course($user_id, $course, $column = 2) {
  1736. $return = '';
  1737. if (!empty($user_id) && !empty($course)) {
  1738. $user_id = intval($user_id);
  1739. $path = api_get_path(SYS_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  1740. $web_path = api_get_path(WEB_COURSE_PATH).$course.'/document/shared_folder/sf_user_'.$user_id.'/';
  1741. $file_list = array();
  1742. if (is_dir($path)) {
  1743. $handle = opendir($path);
  1744. while ($file = readdir($handle)) {
  1745. if ($file == '.' || $file == '..' || $file == '.htaccess' || is_dir($path.$file)) {
  1746. continue; // skip current/parent directory and .htaccess
  1747. }
  1748. $file_list[] = $file;
  1749. }
  1750. if (count($file_list) > 0) {
  1751. $return = $course;
  1752. $return .= '<ul>';
  1753. }
  1754. foreach ($file_list as $file) {
  1755. $return .= '<li><a href="'.$web_path.urlencode($file).'" target="_blank">'.htmlentities($file).'</a>';
  1756. }
  1757. $return .= '</ul>';
  1758. }
  1759. }
  1760. return $return;
  1761. }
  1762. /**
  1763. * Gets the API key (or keys) and return them into an array
  1764. * @param int Optional user id (defaults to the result of api_get_user_id())
  1765. * @result array Non-indexed array containing the list of API keys for this user, or FALSE on error
  1766. */
  1767. public static function get_api_keys($user_id = null, $api_service = 'dokeos') {
  1768. if ($user_id != strval(intval($user_id))) return false;
  1769. if (empty($user_id)) { $user_id = api_get_user_id(); }
  1770. if ($user_id === false) return false;
  1771. $service_name = Database::escape_string($api_service);
  1772. if (is_string($service_name) === false) { return false;}
  1773. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1774. $sql = "SELECT id, api_key FROM $t_api WHERE user_id = ".$user_id." AND api_service='".$api_service."';";
  1775. $res = Database::query($sql, __FILE__, __LINE__);
  1776. if ($res === false) return false; //error during query
  1777. $num = Database::num_rows($res);
  1778. if ($num == 0) return false;
  1779. $list = array();
  1780. while ($row = Database::fetch_array($res)) {
  1781. $list[$row['id']] = $row['api_key'];
  1782. }
  1783. return $list;
  1784. }
  1785. /**
  1786. * Adds a new API key to the users' account
  1787. * @param int Optional user ID (defaults to the results of api_get_user_id())
  1788. * @return boolean True on success, false on failure
  1789. */
  1790. public static function add_api_key($user_id = null, $api_service = 'dokeos') {
  1791. if ($user_id != strval(intval($user_id))) return false;
  1792. if (empty($user_id)) { $user_id = api_get_user_id(); }
  1793. if ($user_id === false) return false;
  1794. $service_name = Database::escape_string($api_service);
  1795. if (is_string($service_name) === false) { return false; }
  1796. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1797. $md5 = md5((time() + ($user_id * 5)) - rand(10000, 10000)); //generate some kind of random key
  1798. $sql = "INSERT INTO $t_api (user_id, api_key,api_service) VALUES ($user_id,'$md5','$service_name')";
  1799. $res = Database::query($sql, __FILE__, __LINE__);
  1800. if ($res === false) return false; //error during query
  1801. $num = Database::insert_id();
  1802. return ($num == 0) ? false : $num;
  1803. }
  1804. /**
  1805. * Deletes an API key from the user's account
  1806. * @param int API key's internal ID
  1807. * @return boolean True on success, false on failure
  1808. */
  1809. public static function delete_api_key($key_id) {
  1810. if ($key_id != strval(intval($key_id))) return false;
  1811. if ($key_id === false) return false;
  1812. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1813. $sql = "SELECT * FROM $t_api WHERE id = ".$key_id;
  1814. $res = Database::query($sql, __FILE__, __LINE__);
  1815. if ($res === false) return false; //error during query
  1816. $num = Database::num_rows($res);
  1817. if ($num !== 1) return false;
  1818. $sql = "DELETE FROM $t_api WHERE id = ".$key_id;
  1819. $res = Database::query($sql, __FILE__, __LINE__);
  1820. if ($res === false) return false; //error during query
  1821. return true;
  1822. }
  1823. /**
  1824. * Regenerate an API key from the user's account
  1825. * @param int user ID (defaults to the results of api_get_user_id())
  1826. * @param string API key's internal ID
  1827. * @return int num
  1828. */
  1829. public static function update_api_key($user_id, $api_service) {
  1830. if ($user_id != strval(intval($user_id))) return false;
  1831. if ($user_id === false) return false;
  1832. $service_name = Database::escape_string($api_service);
  1833. if (is_string($service_name) === false) { return false; }
  1834. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1835. $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  1836. $res = Database::query($sql, __FILE__, __LINE__);
  1837. $num = Database::num_rows($res);
  1838. if ($num == 1) {
  1839. $id_key = Database::fetch_array($res, 'ASSOC');
  1840. self::delete_api_key($id_key['id']);
  1841. $num = self::add_api_key($user_id, $api_service);
  1842. } elseif ($num == 0) {
  1843. $num = self::add_api_key($user_id);
  1844. }
  1845. return $num;
  1846. }
  1847. /**
  1848. * @param int user ID (defaults to the results of api_get_user_id())
  1849. * @param string API key's internal ID
  1850. * @return int row ID, not return a boolean
  1851. */
  1852. public static function get_api_key_id($user_id, $api_service) {
  1853. if ($user_id != strval(intval($user_id))) return false;
  1854. if ($user_id === false) return false;
  1855. $service_name = Database::escape_string($api_service);
  1856. if (is_string($service_name) === false) { return false; }
  1857. $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
  1858. $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
  1859. $res = Database::query($sql, __FILE__, __LINE__);
  1860. $row = Database::fetch_array($res, 'ASSOC');
  1861. return $row['id'];
  1862. }
  1863. /**
  1864. * Subscribes users to the given session and optionally (default) unsubscribes previous users
  1865. * @param int Session ID
  1866. * @param array List of user IDs
  1867. * @param bool Whether to unsubscribe existing users (true, default) or not (false)
  1868. * @return void Nothing, or false on error
  1869. */
  1870. public static function suscribe_users_to_session($id_session, $UserList, $empty_users = true) {
  1871. if ($id_session != strval(intval($id_session))) return false;
  1872. foreach ($UserList as $intUser) {
  1873. if ($intUser != strval(intval($intUser))) return false;
  1874. }
  1875. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1876. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1877. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1878. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1879. $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session'";
  1880. $result = Database::query($sql, __FILE__, __LINE__);
  1881. $existingUsers = array();
  1882. while($row = Database::fetch_array($result)) {
  1883. $existingUsers[] = $row['id_user'];
  1884. }
  1885. $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'";
  1886. $result = Database::query($sql, __FILE__, __LINE__);
  1887. $CourseList = array();
  1888. while($row = Database::fetch_array($result)) {
  1889. $CourseList[] = $row['course_code'];
  1890. }
  1891. foreach ($CourseList as $enreg_course) {
  1892. // for each course in the session
  1893. $nbr_users = 0;
  1894. $enreg_course = Database::escape_string($enreg_course);
  1895. // delete existing users
  1896. if ($empty_users !== false) {
  1897. foreach ($existingUsers as $existing_user) {
  1898. if(!in_array($existing_user, $UserList)) {
  1899. $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user'";
  1900. Database::query($sql, __FILE__, __LINE__);
  1901. if (Database::affected_rows()) {
  1902. $nbr_users--;
  1903. }
  1904. }
  1905. }
  1906. }
  1907. // insert new users into session_rel_course_rel_user and ignore if they already exist
  1908. foreach ($UserList as $enreg_user) {
  1909. if (!in_array($enreg_user, $existingUsers)) {
  1910. $enreg_user = Database::escape_string($enreg_user);
  1911. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')";
  1912. Database::query($insert_sql, __FILE__, __LINE__);
  1913. if (Database::affected_rows()) {
  1914. $nbr_users++;
  1915. }
  1916. }
  1917. }
  1918. // count users in this session-course relation
  1919. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'";
  1920. $rs = Database::query($sql, __FILE__, __LINE__);
  1921. list($nbr_users) = Database::fetch_array($rs);
  1922. // update the session-course relation to add the users total
  1923. $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'";
  1924. Database::query($update_sql, __FILE__, __LINE__);
  1925. }
  1926. // delete users from the session
  1927. if ($empty_users !== false) {
  1928. Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session = $id_session", __FILE__, __LINE__);
  1929. }
  1930. // insert missing users into session
  1931. $nbr_users = 0;
  1932. foreach ($UserList as $enreg_user) {
  1933. $enreg_user = Database::escape_string($enreg_user);
  1934. $nbr_users++;
  1935. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$enreg_user')";
  1936. Database::query($insert_sql, __FILE__, __LINE__);
  1937. }
  1938. // update number of users in the session
  1939. $nbr_users = count($UserList);
  1940. $update_sql = "UPDATE $tbl_session SET nbr_users= $nbr_users WHERE id='$id_session' ";
  1941. Database::query($update_sql, __FILE__, __LINE__);
  1942. }
  1943. /**
  1944. * Checks if a user_id is platform admin
  1945. * @param int user ID
  1946. * @return boolean True if is admin, false otherwise
  1947. * @see main_api.lib.php::api_is_platform_admin() for a context-based check
  1948. */
  1949. function is_admin($user_id) {
  1950. if (empty($user_id) or $user_id != strval(intval($user_id))) { return false; }
  1951. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  1952. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  1953. $res = Database::query($sql);
  1954. return Database::num_rows($res) === 1;
  1955. }
  1956. /**
  1957. * Get the total count of users
  1958. * @return mixed Number of users or false on error
  1959. */
  1960. public static function get_number_of_users() {
  1961. $t_u = Database::get_main_table(TABLE_MAIN_USER);
  1962. $sql = "SELECT count(*) FROM $t_u";
  1963. $res = Database::query($sql);
  1964. if (Database::num_rows($res) === 1) {
  1965. return (int) Database::result($res, 0, 0);
  1966. }
  1967. return false;
  1968. }
  1969. /**
  1970. * Resize a picture
  1971. *
  1972. * @param string file picture
  1973. * @param int size in pixels
  1974. * @return obj image object
  1975. */
  1976. public static function resize_picture($file, $max_size_for_picture) {
  1977. if (!class_exists('image')) {
  1978. require_once api_get_path(LIBRARY_PATH).'image.lib.php';
  1979. }
  1980. $temp = new image($file);
  1981. $picture_infos = api_getimagesize($file);
  1982. if ($picture_infos[0] > $max_size_for_picture) {
  1983. $thumbwidth = $max_size_for_picture;
  1984. if (empty($thumbwidth) or $thumbwidth == 0) {
  1985. $thumbwidth = $max_size_for_picture;
  1986. }
  1987. $new_height = round(($thumbwidth / $picture_infos[0]) * $picture_infos[1]);
  1988. if ($new_height > $max_size_for_picture)
  1989. $new_height = $thumbwidth;
  1990. $temp->resize($thumbwidth, $new_height, 0);
  1991. }
  1992. return $temp;
  1993. }
  1994. /**
  1995. * Gets the current user image
  1996. * @param string user id
  1997. * @param string picture user name
  1998. * @param string height
  1999. * @param string picture size it can be small_, medium_ or big_
  2000. * @param string style css
  2001. * @return array with the file and the style of an image i.e $array['file'] $array['style']
  2002. */
  2003. public static function get_picture_user($user_id, $picture_file, $height, $size_picture = 'medium_', $style = '') {
  2004. $patch_profile = 'upload/users/';
  2005. $picture = array();
  2006. $picture['style'] = $style;
  2007. if ($picture_file == 'unknown.jpg') {
  2008. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/'.$picture_file;
  2009. return $picture;
  2010. }
  2011. $image_array_sys = self::get_user_picture_path_by_id($user_id, 'system', false, true);
  2012. $image_array = self::get_user_picture_path_by_id($user_id, 'web', false, true);
  2013. $file = $image_array_sys['dir'].$size_picture.$picture_file;
  2014. if (file_exists($file)) {
  2015. $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
  2016. $picture['style'] = '';
  2017. if ($height > 0) {
  2018. $dimension = api_getimagesize($picture['file']);
  2019. $margin = (($height - $dimension[1]) / 2);
  2020. //@ todo the padding-top should not be here
  2021. $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension[0].'px; height:'.$dimension[1].';" ';
  2022. }
  2023. } else {
  2024. //$file = api_get_path(SYS_CODE_PATH).$patch_profile.$user_id.'/'.$picture_file;
  2025. $file = $image_array_sys['dir'].$picture_file;
  2026. if (file_exists($file)) {
  2027. $picture['file'] = $image_array['dir'].$picture_file;
  2028. } else {
  2029. $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
  2030. }
  2031. }
  2032. return $picture;
  2033. }
  2034. /**
  2035. * @author Isaac flores <isaac.flores@dokeos.com>
  2036. * @param string The email administrator
  2037. * @param integer The user id
  2038. * @param string The message title
  2039. * @param string The content message
  2040. */
  2041. public static function send_message_in_outbox($email_administrator, $user_id, $title, $content) {
  2042. $table_message = Database::get_main_table(TABLE_MESSAGE);
  2043. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2044. $title = api_utf8_decode($title);
  2045. $content = api_utf8_decode($content);
  2046. $email_administrator = Database::escape_string($email_administrator);
  2047. //message in inbox
  2048. $sql_message_outbox = 'SELECT user_id from '.$table_user.' WHERE email="'.$email_administrator.'" ';
  2049. //$num_row_query = Database::num_rows($sql_message_outbox);
  2050. $res_message_outbox = Database::query($sql_message_outbox, __FILE__, __LINE__);
  2051. $array_users_administrator = array();
  2052. while ($row_message_outbox = Database::fetch_array($res_message_outbox, 'ASSOC')) {
  2053. $array_users_administrator[] = $row_message_outbox['user_id'];
  2054. }
  2055. //allow to insert messages in outbox
  2056. for ($i = 0; $i < count($array_users_administrator); $i++) {
  2057. $sql_insert_outbox = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content ) ".
  2058. " VALUES (".
  2059. "'".(int)$user_id."', '".(int)($array_users_administrator[$i])."', '4', '".date('Y-m-d H:i:s')."','".Database::escape_string($title)."','".Database::escape_string($content)."'".
  2060. ")";
  2061. $rs = Database::query($sql_insert_outbox, __FILE__, __LINE__);
  2062. }
  2063. }
  2064. /*
  2065. *
  2066. * USER TAGS
  2067. *
  2068. * Intructions to create a new user tag by Julio Montoya <gugli100@gmail.com>
  2069. *
  2070. * 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.
  2071. * 2. Go to profile main/auth/profile.php There you will see a special input (facebook style) that will show suggestions of tags.
  2072. * 3. Step 2 will not work since this special input needs a file called "main/user/books.php" In this case. In order to have this file copy and paste from this file main/user/tag.php
  2073. * 4. All the tags are registered in the user_tag table and the relationship between user and tags is in the user_rel_tag table
  2074. * 5. Test and enjoy.
  2075. *
  2076. */
  2077. /**
  2078. * Gets the tags of a specific field_id
  2079. *
  2080. * @param int field_id
  2081. * @param string how we are going to result value in array or in a string (json)
  2082. * @return mixed
  2083. * @since Nov 2009
  2084. * @version 1.8.6.2
  2085. */
  2086. public static function get_tags($tag, $field_id, $return_format='json',$limit=10) {
  2087. // database table definition
  2088. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2089. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2090. $field_id = intval($field_id); //like '%$tag%'
  2091. $limit = intval($limit);
  2092. $tag = Database::escape_string($tag);
  2093. // all the information of the field
  2094. $sql = "SELECT id, tag from $table_user_tag
  2095. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag LIMIT $limit";
  2096. $result = Database::query($sql, __FILE__, __LINE__);
  2097. $return = array();
  2098. if (Database::num_rows($result)>0) {
  2099. while ($row = Database::fetch_array($result,'ASSOC')) {
  2100. $return[] = array('caption'=>$row['tag'], 'value'=>$row['tag']);
  2101. }
  2102. }
  2103. if ($return_format=='json') {
  2104. $return = json_encode($return);
  2105. }
  2106. return $return;
  2107. }
  2108. public static function get_top_tags($field_id, $limit=100) {
  2109. // database table definition
  2110. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2111. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2112. $field_id = intval($field_id);
  2113. $limit = intval($limit);
  2114. // all the information of the field
  2115. $sql = "SELECT count(*) count, tag FROM $table_user_tag_values uv INNER JOIN $table_user_tag ut ON(ut.id = uv.tag_id)
  2116. WHERE field_id = $field_id GROUP BY tag_id ORDER BY count DESC LIMIT $limit";
  2117. $result = Database::query($sql, __FILE__, __LINE__);
  2118. $return = array();
  2119. if (Database::num_rows($result)>0) {
  2120. while ($row = Database::fetch_array($result,'ASSOC')) {
  2121. $return[] = $row;
  2122. }
  2123. }
  2124. return $return;
  2125. }
  2126. /**
  2127. * Get user's tags
  2128. * @param int field_id
  2129. * @param int user_id
  2130. * @return array
  2131. */
  2132. public static function get_user_tags($user_id,$field_id) {
  2133. // database table definition
  2134. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2135. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2136. $field_id = intval($field_id);
  2137. $user_id = intval($user_id);
  2138. // all the information of the field
  2139. $sql = "SELECT ut.id, tag,count FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID)
  2140. WHERE field_id = $field_id AND user_id = $user_id ORDER BY tag";
  2141. $result = Database::query($sql, __FILE__, __LINE__);
  2142. $return = array();
  2143. if (Database::num_rows($result)> 0) {
  2144. while ($row = Database::fetch_array($result,'ASSOC')) {
  2145. $return[$row['id']] = array('tag'=>$row['tag'],'count'=>$row['count']);
  2146. }
  2147. }
  2148. return $return;
  2149. }
  2150. /**
  2151. * Searchs user with a specific tag
  2152. * @param string the tag
  2153. * @param int field id of the tag
  2154. * @return array
  2155. */
  2156. public static function get_all_user_tags($tag, $field_id, $from, $number_of_items) {
  2157. // database table definition
  2158. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2159. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2160. $field_id = intval($field_id);
  2161. $tag = Database::escape_string($tag);
  2162. $from = intval($from);
  2163. $number_of_items = intval($number_of_items);
  2164. // all the information of the field
  2165. $sql = "SELECT u.user_id,u.username,firstname, lastname, tag FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.ID)
  2166. INNER JOIN user u ON(uv.user_id =u.user_id)
  2167. WHERE field_id = $field_id AND tag LIKE '$tag%' ORDER BY tag";
  2168. $sql .= " LIMIT $from,$number_of_items";
  2169. $result = Database::query($sql, __FILE__, __LINE__);
  2170. $return = array();
  2171. if (Database::num_rows($result)> 0) {
  2172. while ($row = Database::fetch_array($result,'ASSOC')) {
  2173. $return[$row['user_id']] = $row;
  2174. }
  2175. }
  2176. return $return;
  2177. }
  2178. /**
  2179. * Get the tag id
  2180. * @param int $tag
  2181. * @param int $field_id
  2182. * @return int 0 if fails otherwise the tag id
  2183. */
  2184. public function get_tag_id($tag, $field_id) {
  2185. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2186. $tag = Database::escape_string($tag);
  2187. $field_id = intval($field_id);
  2188. //with COLLATE latin1_bin to select query in a case sensitive mode
  2189. $sql = "SELECT id FROM $table_user_tag WHERE tag COLLATE latin1_bin LIKE '$tag' AND field_id = $field_id";
  2190. $result = Database::query($sql, __FILE__, __LINE__);
  2191. if (Database::num_rows($result)>0) {
  2192. $row = Database::fetch_array($result,'ASSOC');
  2193. return $row['id'];
  2194. } else {
  2195. return 0;
  2196. }
  2197. }
  2198. /**
  2199. * Get the tag id
  2200. * @param int $tag
  2201. * @param int $field_id
  2202. * @return int 0 if fails otherwise the tag id
  2203. */
  2204. public function get_tag_id_from_id($tag_id, $field_id) {
  2205. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2206. $tag_id = intval($tag_id);
  2207. $field_id = intval($field_id);
  2208. $sql = "SELECT id FROM $table_user_tag WHERE id = '$tag_id' AND field_id = $field_id";
  2209. $result = Database::query($sql, __FILE__, __LINE__);
  2210. if (Database::num_rows($result)>0) {
  2211. $row = Database::fetch_array($result,'ASSOC');
  2212. return $row['id'];
  2213. } else {
  2214. return false;
  2215. }
  2216. }
  2217. /**
  2218. * Adds a user-tag value
  2219. * @param mixed $tag
  2220. * @param int $user_id
  2221. * @param int $field_id
  2222. * @return bool
  2223. */
  2224. public function add_tag($tag, $user_id, $field_id) {
  2225. // database table definition
  2226. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2227. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2228. $tag = Database::escape_string($tag);
  2229. $user_id = intval($user_id);
  2230. $field_id = intval($field_id);
  2231. //&& (substr($tag,strlen($tag)-1) == '@')
  2232. /*$sent_by_user = false;
  2233. if ( substr($tag,0,1) == '@') {
  2234. //is a value sent by the list
  2235. $sent_by_user = true;
  2236. $tag = substr($tag,1,strlen($tag)-2);
  2237. }
  2238. */
  2239. $tag_id = UserManager::get_tag_id($tag,$field_id);
  2240. //@todo we don't create tags with numbers
  2241. if (is_numeric($tag)) {
  2242. //the form is sending an id this means that the user select it from the list so it MUST exists
  2243. /*$new_tag_id = UserManager::get_tag_id_from_id($tag,$field_id);
  2244. if ($new_tag_id !== false) {
  2245. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $new_tag_id";
  2246. $result = Database::query($sql, __FILE__, __LINE__);
  2247. $last_insert_id = $new_tag_id;
  2248. } else {
  2249. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  2250. $result = Database::query($sql, __FILE__, __LINE__);
  2251. $last_insert_id = Database::get_last_insert_id();
  2252. }*/
  2253. } else {
  2254. //this is a new tag
  2255. if ($tag_id == 0) {
  2256. //the tag doesn't exist
  2257. $sql = "INSERT INTO $table_user_tag (tag, field_id,count) VALUES ('$tag','$field_id', count + 1)";
  2258. $result = Database::query($sql, __FILE__, __LINE__);
  2259. $last_insert_id = Database::get_last_insert_id();
  2260. } else {
  2261. //the tag exists we update it
  2262. $sql = "UPDATE $table_user_tag SET count = count + 1 WHERE id = $tag_id";
  2263. $result = Database::query($sql, __FILE__, __LINE__);
  2264. $last_insert_id = $tag_id;
  2265. }
  2266. }
  2267. if (!empty($last_insert_id) && ($last_insert_id!=0)) {
  2268. //we insert the relationship user-tag
  2269. $sql_select ="SELECT tag_id FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $last_insert_id ";
  2270. $result = Database::query($sql_select, __FILE__, __LINE__);
  2271. //if the relationship does not exist we create it
  2272. if (Database::num_rows($result)==0) {
  2273. $sql = "INSERT INTO $table_user_tag_values SET user_id = $user_id, tag_id = $last_insert_id";
  2274. $result = Database::query($sql, __FILE__, __LINE__);
  2275. }
  2276. }
  2277. }
  2278. /**
  2279. * Deletes an user tag
  2280. * @param int user id
  2281. * @param int field id
  2282. *
  2283. */
  2284. public function delete_user_tags($user_id, $field_id) {
  2285. // database table definition
  2286. $table_user_tag = Database::get_main_table(TABLE_MAIN_USER_TAG);
  2287. $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
  2288. $tags = UserManager::get_user_tags($user_id, $field_id);
  2289. //echo '<pre>';var_dump($tags);
  2290. if(is_array($tags) && count($tags)>0) {
  2291. foreach ($tags as $key=>$tag) {
  2292. if ($tag['count']>'0') {
  2293. $sql = "UPDATE $table_user_tag SET count = count - 1 WHERE id = $key ";
  2294. $result = Database::query($sql, __FILE__, __LINE__);
  2295. }
  2296. $sql = "DELETE FROM $table_user_tag_values WHERE user_id = $user_id AND tag_id = $key";
  2297. $result = Database::query($sql, __FILE__, __LINE__);
  2298. }
  2299. }
  2300. }
  2301. /**
  2302. * Process the tag list comes from the UserManager::update_extra_field_value() function
  2303. * @param array the tag list that will be added
  2304. * @param int user id
  2305. * @param int field id
  2306. * @return bool
  2307. */
  2308. public function process_tags($tags, $user_id, $field_id) {
  2309. //We loop the tags and add it to the DB
  2310. if (is_array($tags)) {
  2311. foreach($tags as $tag) {
  2312. UserManager::add_tag($tag, $user_id, $field_id);
  2313. }
  2314. } else {
  2315. UserManager::add_tag($tags,$user_id, $field_id);
  2316. }
  2317. return true;
  2318. }
  2319. }