social.lib.php 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CForumPost;
  4. use Chamilo\CourseBundle\Entity\CForumThread;
  5. use ChamiloSession as Session;
  6. use Zend\Feed\Reader\Entry\Rss;
  7. use Zend\Feed\Reader\Reader;
  8. /**
  9. * Class SocialManager.
  10. *
  11. * This class provides methods for the social network management.
  12. * Include/require it in your code to use its features.
  13. *
  14. * @package chamilo.social
  15. */
  16. class SocialManager extends UserManager
  17. {
  18. const DEFAULT_WALL_POSTS = 10;
  19. const DEFAULT_SCROLL_NEW_POST = 5;
  20. /**
  21. * Constructor.
  22. */
  23. public function __construct()
  24. {
  25. }
  26. /**
  27. * Allow to see contacts list.
  28. *
  29. * @author isaac flores paz
  30. *
  31. * @return array
  32. */
  33. public static function show_list_type_friends()
  34. {
  35. $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
  36. $sql = 'SELECT id, title FROM '.$table.'
  37. WHERE id<>6
  38. ORDER BY id ASC';
  39. $result = Database::query($sql);
  40. $friend_relation_list = [];
  41. while ($row = Database::fetch_array($result, 'ASSOC')) {
  42. $friend_relation_list[] = $row;
  43. }
  44. $count_list = count($friend_relation_list);
  45. if ($count_list == 0) {
  46. $friend_relation_list[] = get_lang('Unknown');
  47. } else {
  48. return $friend_relation_list;
  49. }
  50. }
  51. /**
  52. * Get relation type contact by name.
  53. *
  54. * @param string names of the kind of relation
  55. *
  56. * @return int
  57. *
  58. * @author isaac flores paz
  59. */
  60. public static function get_relation_type_by_name($relation_type_name)
  61. {
  62. $list_type_friend = self::show_list_type_friends();
  63. foreach ($list_type_friend as $value_type_friend) {
  64. if (strtolower($value_type_friend['title']) == $relation_type_name) {
  65. return $value_type_friend['id'];
  66. }
  67. }
  68. }
  69. /**
  70. * Get the kind of relation between contacts.
  71. *
  72. * @param int user id
  73. * @param int user friend id
  74. * @param string
  75. *
  76. * @return int
  77. *
  78. * @author isaac flores paz
  79. */
  80. public static function get_relation_between_contacts($user_id, $user_friend)
  81. {
  82. $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
  83. $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  84. $sql = 'SELECT rt.id as id
  85. FROM '.$table.' rt
  86. WHERE rt.id = (
  87. SELECT uf.relation_type
  88. FROM '.$userRelUserTable.' uf
  89. WHERE
  90. user_id='.((int) $user_id).' AND
  91. friend_user_id='.((int) $user_friend).' AND
  92. uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
  93. LIMIT 1
  94. )';
  95. $res = Database::query($sql);
  96. if (Database::num_rows($res) > 0) {
  97. $row = Database::fetch_array($res, 'ASSOC');
  98. return $row['id'];
  99. } else {
  100. return USER_UNKNOWN;
  101. }
  102. }
  103. /**
  104. * Get count of friends from user.
  105. *
  106. * @param int $userId
  107. *
  108. * @return int
  109. */
  110. public static function getCountFriends($userId)
  111. {
  112. $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  113. $userId = (int) $userId;
  114. if (empty($userId)) {
  115. return 0;
  116. }
  117. $sql = 'SELECT count(friend_user_id) count
  118. FROM '.$table.'
  119. WHERE
  120. relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
  121. friend_user_id<>'.$userId.' AND
  122. user_id='.$userId;
  123. $res = Database::query($sql);
  124. if (Database::num_rows($res)) {
  125. $row = Database::fetch_array($res, 'ASSOC');
  126. return (int) $row['count'];
  127. }
  128. return 0;
  129. }
  130. /**
  131. * Gets friends id list.
  132. *
  133. * @param int user id
  134. * @param int group id
  135. * @param string name to search
  136. * @param bool true will load firstname, lastname, and image name
  137. *
  138. * @return array
  139. *
  140. * @author Julio Montoya <gugli100@gmail.com> Cleaning code, function renamed, $load_extra_info option added
  141. * @author isaac flores paz
  142. */
  143. public static function get_friends(
  144. $user_id,
  145. $id_group = null,
  146. $search_name = null,
  147. $load_extra_info = true
  148. ) {
  149. $user_id = (int) $user_id;
  150. $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  151. $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
  152. $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
  153. WHERE
  154. relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
  155. friend_user_id<>'.$user_id.' AND
  156. user_id='.$user_id;
  157. if (isset($id_group) && $id_group > 0) {
  158. $sql .= ' AND relation_type='.$id_group;
  159. }
  160. if (isset($search_name)) {
  161. $search_name = trim($search_name);
  162. $search_name = str_replace(' ', '', $search_name);
  163. $sql .= ' AND friend_user_id IN (
  164. SELECT user_id FROM '.$tbl_my_user.'
  165. WHERE
  166. firstName LIKE "%'.Database::escape_string($search_name).'%" OR
  167. lastName LIKE "%'.Database::escape_string($search_name).'%" OR
  168. '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
  169. ) ';
  170. }
  171. $res = Database::query($sql);
  172. $list = [];
  173. while ($row = Database::fetch_array($res, 'ASSOC')) {
  174. if ($load_extra_info) {
  175. $userInfo = api_get_user_info($row['friend_user_id']);
  176. $list[] = [
  177. 'friend_user_id' => $row['friend_user_id'],
  178. 'firstName' => $userInfo['firstName'],
  179. 'lastName' => $userInfo['lastName'],
  180. 'username' => $userInfo['username'],
  181. 'image' => $userInfo['avatar'],
  182. 'user_info' => $userInfo,
  183. ];
  184. } else {
  185. $list[] = $row;
  186. }
  187. }
  188. return $list;
  189. }
  190. /**
  191. * get web path of user invitate.
  192. *
  193. * @author isaac flores paz
  194. * @author Julio Montoya setting variable array
  195. *
  196. * @param int user id
  197. *
  198. * @return array
  199. */
  200. public static function get_list_web_path_user_invitation_by_user_id($user_id)
  201. {
  202. $list_ids = self::get_list_invitation_of_friends_by_user_id($user_id);
  203. $list = [];
  204. foreach ($list_ids as $values_ids) {
  205. $list[] = UserManager::get_user_picture_path_by_id(
  206. $values_ids['user_sender_id'],
  207. 'web'
  208. );
  209. }
  210. return $list;
  211. }
  212. /**
  213. * Sends an invitation to contacts.
  214. *
  215. * @param int user id
  216. * @param int user friend id
  217. * @param string title of the message
  218. * @param string content of the message
  219. *
  220. * @return bool
  221. *
  222. * @author isaac flores paz
  223. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  224. */
  225. public static function send_invitation_friend(
  226. $user_id,
  227. $friend_id,
  228. $message_title,
  229. $message_content
  230. ) {
  231. $tbl_message = Database::get_main_table(TABLE_MESSAGE);
  232. $user_id = (int) $user_id;
  233. $friend_id = (int) $friend_id;
  234. //Just in case we replace the and \n and \n\r while saving in the DB
  235. $message_content = str_replace(["\n", "\n\r"], '<br />', $message_content);
  236. $clean_message_content = Database::escape_string($message_content);
  237. $now = api_get_utc_datetime();
  238. $sql = 'SELECT COUNT(*) AS count FROM '.$tbl_message.'
  239. WHERE
  240. user_sender_id='.$user_id.' AND
  241. user_receiver_id='.$friend_id.' AND
  242. msg_status IN('.MESSAGE_STATUS_INVITATION_PENDING.', '.MESSAGE_STATUS_INVITATION_ACCEPTED.', '.MESSAGE_STATUS_INVITATION_DENIED.');
  243. ';
  244. $res_exist = Database::query($sql);
  245. $row_exist = Database::fetch_array($res_exist, 'ASSOC');
  246. if ($row_exist['count'] == 0) {
  247. $params = [
  248. 'user_sender_id' => $user_id,
  249. 'user_receiver_id' => $friend_id,
  250. 'msg_status' => MESSAGE_STATUS_INVITATION_PENDING,
  251. 'send_date' => $now,
  252. 'title' => $message_title,
  253. 'content' => $message_content,
  254. 'group_id' => 0,
  255. 'parent_id' => 0,
  256. 'update_date' => $now,
  257. ];
  258. $messageId = Database::insert($tbl_message, $params);
  259. $senderInfo = api_get_user_info($user_id);
  260. $notification = new Notification();
  261. $notification->saveNotification(
  262. $messageId,
  263. Notification::NOTIFICATION_TYPE_INVITATION,
  264. [$friend_id],
  265. $message_title,
  266. $message_content,
  267. $senderInfo
  268. );
  269. return true;
  270. } else {
  271. // invitation already exist
  272. $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
  273. WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
  274. $res_if_exist = Database::query($sql);
  275. $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
  276. if ($row_if_exist['count'] == 1) {
  277. $sql = 'UPDATE '.$tbl_message.' SET
  278. msg_status=5, content = "'.$clean_message_content.'"
  279. WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7 ';
  280. Database::query($sql);
  281. return true;
  282. } else {
  283. return false;
  284. }
  285. }
  286. }
  287. /**
  288. * Get number messages of the inbox.
  289. *
  290. * @author isaac flores paz
  291. *
  292. * @param int $userId user receiver id
  293. *
  294. * @return int
  295. */
  296. public static function get_message_number_invitation_by_user_id($userId)
  297. {
  298. $table = Database::get_main_table(TABLE_MESSAGE);
  299. $userId = (int) $userId;
  300. $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$table.'
  301. WHERE
  302. user_receiver_id='.$userId.' AND
  303. msg_status='.MESSAGE_STATUS_INVITATION_PENDING;
  304. $res = Database::query($sql);
  305. $row = Database::fetch_array($res, 'ASSOC');
  306. if ($row) {
  307. return (int) $row['count_message_in_box'];
  308. }
  309. return 0;
  310. }
  311. /**
  312. * Get number of messages sent to other users.
  313. *
  314. * @param int $userId
  315. *
  316. * @return int
  317. */
  318. public static function getCountMessagesSent($userId)
  319. {
  320. $userId = (int) $userId;
  321. $table = Database::get_main_table(TABLE_MESSAGE);
  322. $sql = 'SELECT COUNT(*) FROM '.$table.'
  323. WHERE
  324. user_sender_id='.$userId.' AND
  325. msg_status < 5';
  326. $res = Database::query($sql);
  327. $row = Database::fetch_row($res);
  328. return $row[0];
  329. }
  330. /**
  331. * Get number of messages received from other users.
  332. *
  333. * @param int $receiver_id
  334. *
  335. * @return int
  336. */
  337. public static function getCountMessagesReceived($receiver_id)
  338. {
  339. $table = Database::get_main_table(TABLE_MESSAGE);
  340. $sql = 'SELECT COUNT(*) FROM '.$table.'
  341. WHERE
  342. user_receiver_id='.intval($receiver_id).' AND
  343. msg_status < 4';
  344. $res = Database::query($sql);
  345. $row = Database::fetch_row($res);
  346. return $row[0];
  347. }
  348. /**
  349. * Get number of messages posted on own wall.
  350. *
  351. * @param int $userId
  352. *
  353. * @return int
  354. */
  355. public static function getCountWallPostedMessages($userId)
  356. {
  357. $userId = (int) $userId;
  358. if (empty($userId)) {
  359. return 0;
  360. }
  361. $table = Database::get_main_table(TABLE_MESSAGE);
  362. $sql = 'SELECT COUNT(*)
  363. FROM '.$table.'
  364. WHERE
  365. user_sender_id='.$userId.' AND
  366. (msg_status = '.MESSAGE_STATUS_WALL.' OR
  367. msg_status = '.MESSAGE_STATUS_WALL_POST.') AND
  368. parent_id = 0';
  369. $res = Database::query($sql);
  370. $row = Database::fetch_row($res);
  371. return $row[0];
  372. }
  373. /**
  374. * Get invitation list received by user.
  375. *
  376. * @author isaac flores paz
  377. *
  378. * @param int $userId
  379. * @param int $limit
  380. *
  381. * @return array
  382. */
  383. public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
  384. {
  385. $userId = (int) $userId;
  386. $limit = (int) $limit;
  387. if (empty($userId)) {
  388. return [];
  389. }
  390. $table = Database::get_main_table(TABLE_MESSAGE);
  391. $sql = 'SELECT user_sender_id, send_date, title, content
  392. FROM '.$table.'
  393. WHERE
  394. user_receiver_id = '.$userId.' AND
  395. msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
  396. if ($limit != null && $limit > 0) {
  397. $sql .= ' LIMIT '.$limit;
  398. }
  399. $res = Database::query($sql);
  400. $list = [];
  401. while ($row = Database::fetch_array($res, 'ASSOC')) {
  402. $list[] = $row;
  403. }
  404. return $list;
  405. }
  406. /**
  407. * Get invitation list sent by user.
  408. *
  409. * @author Julio Montoya <gugli100@gmail.com>
  410. *
  411. * @param int $userId
  412. *
  413. * @return array
  414. */
  415. public static function get_list_invitation_sent_by_user_id($userId)
  416. {
  417. $userId = (int) $userId;
  418. if (empty($userId)) {
  419. return [];
  420. }
  421. $table = Database::get_main_table(TABLE_MESSAGE);
  422. $sql = 'SELECT user_receiver_id, send_date,title,content
  423. FROM '.$table.'
  424. WHERE
  425. user_sender_id = '.$userId.' AND
  426. msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
  427. $res = Database::query($sql);
  428. $list = [];
  429. while ($row = Database::fetch_array($res, 'ASSOC')) {
  430. $list[$row['user_receiver_id']] = $row;
  431. }
  432. return $list;
  433. }
  434. /**
  435. * Get count invitation sent by user.
  436. *
  437. * @author Julio Montoya <gugli100@gmail.com>
  438. *
  439. * @param int $userId
  440. *
  441. * @return int
  442. */
  443. public static function getCountInvitationSent($userId)
  444. {
  445. $userId = (int) $userId;
  446. if (empty($userId)) {
  447. return 0;
  448. }
  449. $table = Database::get_main_table(TABLE_MESSAGE);
  450. $sql = 'SELECT count(user_receiver_id) count
  451. FROM '.$table.'
  452. WHERE
  453. user_sender_id = '.$userId.' AND
  454. msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
  455. $res = Database::query($sql);
  456. if (Database::num_rows($res)) {
  457. $row = Database::fetch_array($res, 'ASSOC');
  458. return (int) $row['count'];
  459. }
  460. return 0;
  461. }
  462. /**
  463. * Accepts invitation.
  464. *
  465. * @param int $user_send_id
  466. * @param int $user_receiver_id
  467. *
  468. * @return bool
  469. *
  470. * @author isaac flores paz
  471. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  472. */
  473. public static function invitation_accepted($user_send_id, $user_receiver_id)
  474. {
  475. if (empty($user_send_id) || empty($user_receiver_id)) {
  476. return false;
  477. }
  478. $table = Database::get_main_table(TABLE_MESSAGE);
  479. $sql = "UPDATE $table
  480. SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
  481. WHERE
  482. user_sender_id = ".((int) $user_send_id)." AND
  483. user_receiver_id=".((int) $user_receiver_id)." AND
  484. msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
  485. Database::query($sql);
  486. return true;
  487. }
  488. /**
  489. * Denies invitation.
  490. *
  491. * @param int user sender id
  492. * @param int user receiver id
  493. *
  494. * @return bool
  495. *
  496. * @author isaac flores paz
  497. * @author Julio Montoya <gugli100@gmail.com> Cleaning code
  498. */
  499. public static function invitation_denied($user_send_id, $user_receiver_id)
  500. {
  501. if (empty($user_send_id) || empty($user_receiver_id)) {
  502. return false;
  503. }
  504. $table = Database::get_main_table(TABLE_MESSAGE);
  505. $sql = 'DELETE FROM '.$table.'
  506. WHERE
  507. user_sender_id = '.((int) $user_send_id).' AND
  508. user_receiver_id='.((int) $user_receiver_id).' AND
  509. msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
  510. Database::query($sql);
  511. return true;
  512. }
  513. /**
  514. * Get user's feeds.
  515. *
  516. * @param int $user User ID
  517. * @param int $limit Limit of posts per feed
  518. *
  519. * @return string HTML section with all feeds included
  520. *
  521. * @author Yannick Warnier
  522. *
  523. * @since Dokeos 1.8.6.1
  524. */
  525. public static function getUserRssFeed($user, $limit = 5)
  526. {
  527. $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
  528. if (empty($feed)) {
  529. return '';
  530. }
  531. $feeds = explode(';', $feed['rssfeeds']);
  532. if (count($feeds) == 0) {
  533. return '';
  534. }
  535. $res = '';
  536. foreach ($feeds as $url) {
  537. if (empty($url)) {
  538. continue;
  539. }
  540. try {
  541. $channel = Reader::import($url);
  542. $i = 1;
  543. if (!empty($channel)) {
  544. $iconRss = '';
  545. if (!empty($feed)) {
  546. $iconRss = Display::url(
  547. Display::return_icon('social_rss.png', '', [], 22),
  548. Security::remove_XSS($feed['rssfeeds']),
  549. ['target' => '_blank']
  550. );
  551. }
  552. $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
  553. $res .= '<div class="rss-items">';
  554. /** @var Rss $item */
  555. foreach ($channel as $item) {
  556. if ($limit >= 0 and $i > $limit) {
  557. break;
  558. }
  559. $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
  560. $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
  561. $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
  562. $i++;
  563. }
  564. $res .= '</div>';
  565. }
  566. } catch (Exception $e) {
  567. error_log($e->getMessage());
  568. }
  569. }
  570. return $res;
  571. }
  572. /**
  573. * Sends invitations to friends.
  574. *
  575. * @param int $userId
  576. * @param string $subject
  577. * @param string $content
  578. *
  579. * @return bool
  580. */
  581. public static function sendInvitationToUser($userId, $subject = '', $content = '')
  582. {
  583. $user_info = api_get_user_info($userId);
  584. $success = get_lang('MessageSentTo');
  585. $success .= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
  586. if (isset($subject) && isset($content) && isset($userId)) {
  587. $result = MessageManager::send_message($userId, $subject, $content);
  588. if ($result) {
  589. Display::addFlash(
  590. Display::return_message($success, 'normal', false)
  591. );
  592. } else {
  593. Display::addFlash(
  594. Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
  595. );
  596. }
  597. return false;
  598. } elseif (isset($userId) && !isset($subject)) {
  599. if (isset($userId) && $userId > 0) {
  600. $count = self::send_invitation_friend(
  601. api_get_user_id(),
  602. $userId,
  603. get_lang('Invitation'),
  604. $content
  605. );
  606. if ($count) {
  607. Display::addFlash(
  608. Display::return_message(
  609. api_htmlentities(get_lang('InvitationHasBeenSent')),
  610. 'normal',
  611. false
  612. )
  613. );
  614. } else {
  615. Display::addFlash(
  616. Display::return_message(
  617. api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
  618. 'warning',
  619. false
  620. )
  621. );
  622. }
  623. }
  624. }
  625. }
  626. /**
  627. * Helper functions definition.
  628. */
  629. public static function get_logged_user_course_html($my_course, $count)
  630. {
  631. $result = '';
  632. $count = (int) $count;
  633. // Table definitions
  634. $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
  635. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  636. $course_directory = $my_course['course_info']['directory'];
  637. $course_title = $my_course['course_info']['title'];
  638. $course_visibility = $my_course['course_info']['visibility'];
  639. $user_in_course_status = CourseManager::getUserInCourseStatus(
  640. api_get_user_id(),
  641. $my_course['course_info']['real_id']
  642. );
  643. $course_path = api_get_path(SYS_COURSE_PATH).$course_directory; // course path
  644. if (api_get_setting('course_images_in_courses_list') === 'true') {
  645. if (file_exists($course_path.'/course-pic85x85.png')) {
  646. $image = $my_course['course_info']['course_image'];
  647. $imageCourse = Display::img($image, $course_title, ['class' => 'img-course']);
  648. } else {
  649. $imageCourse = Display::return_icon(
  650. 'session_default_small.png',
  651. $course_title,
  652. ['class' => 'img-course']
  653. );
  654. }
  655. } else {
  656. $imageCourse = Display::return_icon(
  657. 'course.png',
  658. get_lang('Course'),
  659. ['class' => 'img-default']
  660. );
  661. }
  662. //display course entry
  663. if (api_get_setting('course_images_in_courses_list') === 'true') {
  664. $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
  665. } else {
  666. $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
  667. }
  668. $result .= $imageCourse;
  669. //show a hyperlink to the course, unless the course is closed and user is not course admin
  670. if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
  671. ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
  672. ) {
  673. $result .= '<span class="title">'.$course_title.'<span>';
  674. } else {
  675. $result .= $course_title.' '.get_lang('CourseClosed');
  676. }
  677. $result .= '</li>';
  678. $session = '';
  679. if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
  680. // Request for the name of the general coach
  681. $sql = 'SELECT lastname, firstname
  682. FROM '.$tbl_session.' ts
  683. LEFT JOIN '.$main_user_table.' tu
  684. ON ts.id_coach = tu.user_id
  685. WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
  686. $rs = Database::query($sql);
  687. $sessioncoach = Database::store_result($rs);
  688. $sessioncoach = $sessioncoach[0];
  689. $session = [];
  690. $session['title'] = $my_course['session_name'];
  691. if ($my_course['access_start_date'] == '0000-00-00') {
  692. $session['dates'] = get_lang('WithoutTimeLimits');
  693. if (api_get_setting('show_session_coach') === 'true') {
  694. $session['coach'] = get_lang('GeneralCoach').': '.
  695. api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
  696. }
  697. } else {
  698. $session['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
  699. if (api_get_setting('show_session_coach') === 'true') {
  700. $session['coach'] = get_lang('GeneralCoach').': '.
  701. api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
  702. }
  703. }
  704. }
  705. $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
  706. $output = [
  707. $my_course['user_course_cat'],
  708. $result,
  709. $my_course['id_session'],
  710. $session,
  711. ];
  712. return $output;
  713. }
  714. /**
  715. * Shows the avatar block in social pages.
  716. *
  717. * @param string $show highlight link possible values:
  718. * group_add,
  719. * home,
  720. * messages,
  721. * messages_inbox,
  722. * messages_compose,
  723. * messages_outbox,
  724. * invitations,
  725. * shared_profile,
  726. * friends,
  727. * groups search
  728. * @param int $group_id
  729. * @param int $user_id
  730. */
  731. public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
  732. {
  733. $user_id = (int) $user_id;
  734. $group_id = (int) $group_id;
  735. if (empty($user_id)) {
  736. $user_id = api_get_user_id();
  737. }
  738. $show_groups = [
  739. 'groups',
  740. 'group_messages',
  741. 'messages_list',
  742. 'group_add',
  743. 'mygroups',
  744. 'group_edit',
  745. 'member_list',
  746. 'invite_friends',
  747. 'waiting_list',
  748. 'browse_groups',
  749. ];
  750. $template = new Template(null, false, false, false, false, false);
  751. if (in_array($show, $show_groups) && !empty($group_id)) {
  752. // Group image
  753. $userGroup = new UserGroup();
  754. $group_info = $userGroup->get($group_id);
  755. $userGroupImage = $userGroup->get_picture_group(
  756. $group_id,
  757. $group_info['picture'],
  758. 128,
  759. GROUP_IMAGE_SIZE_BIG
  760. );
  761. $template->assign('show_group', true);
  762. $template->assign('group_id', $group_id);
  763. $template->assign('user_group_image', $userGroupImage);
  764. $template->assign(
  765. 'user_is_group_admin',
  766. $userGroup->is_group_admin(
  767. $group_id,
  768. api_get_user_id()
  769. )
  770. );
  771. } else {
  772. $template->assign('show_group', false);
  773. $template->assign('show_user', true);
  774. $template->assign(
  775. 'user_image',
  776. [
  777. 'big' => UserManager::getUserPicture(
  778. $user_id,
  779. USER_IMAGE_SIZE_BIG
  780. ),
  781. 'normal' => UserManager::getUserPicture(
  782. $user_id,
  783. USER_IMAGE_SIZE_MEDIUM
  784. ),
  785. ]
  786. );
  787. }
  788. $skillBlock = $template->get_template('social/avatar_block.tpl');
  789. return $template->fetch($skillBlock);
  790. }
  791. /**
  792. * Shows the right menu of the Social Network tool.
  793. *
  794. * @param string $show highlight link possible values:
  795. * group_add,
  796. * home,
  797. * messages,
  798. * messages_inbox,
  799. * messages_compose ,
  800. * messages_outbox,
  801. * invitations,
  802. * shared_profile,
  803. * friends,
  804. * groups search
  805. * @param int $group_id group id
  806. * @param int $user_id user id
  807. * @param bool $show_full_profile show profile or not (show or hide the user image/information)
  808. * @param bool $show_delete_account_button
  809. */
  810. public static function show_social_menu(
  811. $show = '',
  812. $group_id = 0,
  813. $user_id = 0,
  814. $show_full_profile = false,
  815. $show_delete_account_button = false
  816. ) {
  817. $user_id = (int) $user_id;
  818. $group_id = (int) $group_id;
  819. if (empty($user_id)) {
  820. $user_id = api_get_user_id();
  821. }
  822. $usergroup = new UserGroup();
  823. $show_groups = [
  824. 'groups',
  825. 'group_messages',
  826. 'messages_list',
  827. 'group_add',
  828. 'mygroups',
  829. 'group_edit',
  830. 'member_list',
  831. 'invite_friends',
  832. 'waiting_list',
  833. 'browse_groups',
  834. ];
  835. // get count unread message and total invitations
  836. $count_unread_message = MessageManager::getCountNewMessagesFromDB(api_get_user_id());
  837. $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
  838. $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
  839. $group_pending_invitations = $usergroup->get_groups_by_user(
  840. api_get_user_id(),
  841. GROUP_USER_PERMISSION_PENDING_INVITATION,
  842. false
  843. );
  844. $group_pending_invitations = count($group_pending_invitations);
  845. $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
  846. $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
  847. $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
  848. $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
  849. $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
  850. $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
  851. $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
  852. $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
  853. $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
  854. $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
  855. $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
  856. $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
  857. $messageSocialIcon = Display::return_icon('promoted_message.png', get_lang('PromotedMessages'));
  858. $forumCourseId = api_get_configuration_value('global_forums_course_id');
  859. $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
  860. if (!empty($forumCourseId)) {
  861. $courseInfo = api_get_course_info_by_id($forumCourseId);
  862. if (!empty($courseInfo)) {
  863. $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
  864. }
  865. }
  866. $html = '';
  867. $active = null;
  868. if (!in_array(
  869. $show,
  870. ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
  871. )) {
  872. $links = '<ul class="nav nav-pills nav-stacked">';
  873. $active = $show === 'home' ? 'active' : null;
  874. $links .= '
  875. <li class="home-icon '.$active.'">
  876. <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
  877. '.$homeIcon.' '.get_lang('Home').'
  878. </a>
  879. </li>';
  880. $active = $show === 'messages' ? 'active' : null;
  881. $links .= '
  882. <li class="messages-icon '.$active.'">
  883. <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
  884. '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
  885. </a>
  886. </li>';
  887. // Invitations
  888. $active = $show === 'invitations' ? 'active' : null;
  889. $links .= '
  890. <li class="invitations-icon '.$active.'">
  891. <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
  892. '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
  893. </a>
  894. </li>';
  895. // Shared profile and groups
  896. $active = $show === 'shared_profile' ? 'active' : null;
  897. $links .= '
  898. <li class="shared-profile-icon'.$active.'">
  899. <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
  900. '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
  901. </a>
  902. </li>';
  903. $active = $show === 'friends' ? 'active' : null;
  904. $links .= '
  905. <li class="friends-icon '.$active.'">
  906. <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
  907. '.$friendsIcon.' '.get_lang('Friends').'
  908. </a>
  909. </li>';
  910. $active = $show === 'browse_groups' ? 'active' : null;
  911. $links .= '
  912. <li class="browse-groups-icon '.$active.'">
  913. <a href="'.$groupUrl.'">
  914. '.$groupsIcon.' '.get_lang('SocialGroups').'
  915. </a>
  916. </li>';
  917. // Search users
  918. $active = $show === 'search' ? 'active' : null;
  919. $links .= '
  920. <li class="search-icon '.$active.'">
  921. <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
  922. '.$searchIcon.' '.get_lang('Search').'
  923. </a>
  924. </li>';
  925. // My files
  926. $active = $show === 'myfiles' ? 'active' : null;
  927. $myFiles = '
  928. <li class="myfiles-icon '.$active.'">
  929. <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
  930. '.$filesIcon.' '.get_lang('MyFiles').'
  931. </a>
  932. </li>';
  933. if (api_get_setting('allow_my_files') === 'false') {
  934. $myFiles = '';
  935. }
  936. $links .= $myFiles;
  937. if (api_get_configuration_value('allow_portfolio_tool')) {
  938. $links .= '
  939. <li class="portoflio-icon '.($show === 'portfolio' ? 'active' : '').'">
  940. <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
  941. '.$portfolioIcon.' '.get_lang('Portfolio').'
  942. </a>
  943. </li>
  944. ';
  945. }
  946. if (!api_get_configuration_value('disable_gdpr')) {
  947. $active = $show === 'personal-data' ? 'active' : null;
  948. $personalData = '
  949. <li class="personal-data-icon '.$active.'">
  950. <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
  951. '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
  952. </a>
  953. </li>';
  954. $links .= $personalData;
  955. }
  956. if (api_is_platform_admin()) {
  957. $active = $show === 'promoted_messages' ? 'active' : null;
  958. $personalData = '
  959. <li class="personal-data-icon '.$active.'">
  960. <a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
  961. '.$messageSocialIcon.' '.get_lang('PromotedMessages').'
  962. </a>
  963. </li>';
  964. $links .= $personalData;
  965. }
  966. $links .= '</ul>';
  967. $html .= Display::panelCollapse(
  968. get_lang('SocialNetwork'),
  969. $links,
  970. 'social-network-menu',
  971. null,
  972. 'sn-sidebar',
  973. 'sn-sidebar-collapse'
  974. );
  975. }
  976. if (!empty($group_id) && in_array($show, $show_groups)) {
  977. $html .= $usergroup->show_group_column_information(
  978. $group_id,
  979. api_get_user_id(),
  980. $show
  981. );
  982. }
  983. if ($show === 'shared_profile') {
  984. $links = '<ul class="nav nav-pills nav-stacked">';
  985. // My own profile
  986. if ($show_full_profile && $user_id == api_get_user_id()) {
  987. $links .= '
  988. <li class="home-icon '.$active.'">
  989. <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
  990. '.$homeIcon.' '.get_lang('Home').'
  991. </a>
  992. </li>
  993. <li class="messages-icon '.$active.'">
  994. <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
  995. '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
  996. </a>
  997. </li>';
  998. $active = $show === 'invitations' ? 'active' : null;
  999. $links .= '
  1000. <li class="invitations-icon'.$active.'">
  1001. <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
  1002. '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
  1003. </a>
  1004. </li>';
  1005. $links .= '
  1006. <li class="shared-profile-icon active">
  1007. <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
  1008. '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
  1009. </a>
  1010. </li>
  1011. <li class="friends-icon">
  1012. <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
  1013. '.$friendsIcon.' '.get_lang('Friends').'
  1014. </a>
  1015. </li>';
  1016. $links .= '<li class="browse-groups-icon">
  1017. <a href="'.$groupUrl.'">
  1018. '.$groupsIcon.' '.get_lang('SocialGroups').'
  1019. </a>
  1020. </li>';
  1021. $active = $show == 'search' ? 'active' : null;
  1022. $links .= '
  1023. <li class="search-icon '.$active.'">
  1024. <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
  1025. '.$searchIcon.' '.get_lang('Search').'
  1026. </a>
  1027. </li>';
  1028. $active = $show == 'myfiles' ? 'active' : null;
  1029. $myFiles = '
  1030. <li class="myfiles-icon '.$active.'">
  1031. <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
  1032. '.$filesIcon.' '.get_lang('MyFiles').'
  1033. </a>
  1034. </li>';
  1035. if (api_get_setting('allow_my_files') === 'false') {
  1036. $myFiles = '';
  1037. }
  1038. $links .= $myFiles;
  1039. if (api_get_configuration_value('allow_portfolio_tool')) {
  1040. $links .= '
  1041. <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
  1042. <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
  1043. '.$portfolioIcon.' '.get_lang('Portfolio').'
  1044. </a>
  1045. </li>
  1046. ';
  1047. }
  1048. if (!api_get_configuration_value('disable_gdpr')) {
  1049. $active = $show == 'personal-data' ? 'active' : null;
  1050. $personalData = '
  1051. <li class="personal-data-icon '.$active.'">
  1052. <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
  1053. '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
  1054. </a>
  1055. </li>';
  1056. $links .= $personalData;
  1057. $links .= '</ul>';
  1058. }
  1059. }
  1060. // My friend profile.
  1061. if ($user_id != api_get_user_id()) {
  1062. $sendMessageText = get_lang('SendMessage');
  1063. $sendMessageIcon = Display::return_icon(
  1064. 'new-message.png',
  1065. $sendMessageText
  1066. );
  1067. $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
  1068. 'a' => 'get_user_popup',
  1069. 'user_id' => $user_id,
  1070. ]);
  1071. $links .= '<li>';
  1072. $links .= Display::url(
  1073. "$sendMessageIcon $sendMessageText",
  1074. $sendMessageUrl,
  1075. [
  1076. 'class' => 'ajax',
  1077. 'title' => $sendMessageText,
  1078. 'data-title' => $sendMessageText,
  1079. ]
  1080. );
  1081. $links .= '</li>';
  1082. if (api_get_configuration_value('allow_portfolio_tool')) {
  1083. $links .= '
  1084. <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
  1085. <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
  1086. '.$portfolioIcon.' '.get_lang('Portfolio').'
  1087. </a>
  1088. </li>
  1089. ';
  1090. }
  1091. }
  1092. // Check if I already sent an invitation message
  1093. $invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
  1094. if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
  1095. count($invitationSentList[$user_id]) > 0
  1096. ) {
  1097. $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
  1098. Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
  1099. .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
  1100. } else {
  1101. if (!$show_full_profile) {
  1102. $links .= '<li>
  1103. <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
  1104. Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
  1105. '</a></li>';
  1106. }
  1107. }
  1108. $links .= '</ul>';
  1109. $html .= Display::panelCollapse(
  1110. get_lang('SocialNetwork'),
  1111. $links,
  1112. 'social-network-menu',
  1113. null,
  1114. 'sn-sidebar',
  1115. 'sn-sidebar-collapse'
  1116. );
  1117. if ($show_full_profile && $user_id == api_get_user_id()) {
  1118. $personal_course_list = UserManager::get_personal_session_course_list($user_id);
  1119. $course_list_code = [];
  1120. $i = 1;
  1121. if (is_array($personal_course_list)) {
  1122. foreach ($personal_course_list as $my_course) {
  1123. if ($i <= 10) {
  1124. $course_list_code[] = ['code' => $my_course['code']];
  1125. } else {
  1126. break;
  1127. }
  1128. $i++;
  1129. }
  1130. // To avoid repeated courses
  1131. $course_list_code = array_unique_dimensional($course_list_code);
  1132. }
  1133. // Announcements
  1134. $announcements = [];
  1135. foreach ($course_list_code as $course) {
  1136. $course_info = api_get_course_info($course['code']);
  1137. if (!empty($course_info)) {
  1138. $content = AnnouncementManager::get_all_annoucement_by_user_course(
  1139. $course_info['code'],
  1140. $user_id
  1141. );
  1142. if (!empty($content)) {
  1143. $url = Display::url(
  1144. Display::return_icon(
  1145. 'announcement.png',
  1146. get_lang('Announcements')
  1147. ).$course_info['name'].' ('.$content['count'].')',
  1148. api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
  1149. );
  1150. $announcements[] = Display::tag('li', $url);
  1151. }
  1152. }
  1153. }
  1154. if (!empty($announcements)) {
  1155. $html .= '<div class="social_menu_items">';
  1156. $html .= '<ul>';
  1157. foreach ($announcements as $announcement) {
  1158. $html .= $announcement;
  1159. }
  1160. $html .= '</ul>';
  1161. $html .= '</div>';
  1162. }
  1163. }
  1164. }
  1165. if ($show_delete_account_button) {
  1166. $html .= '<div class="panel panel-default"><div class="panel-body">';
  1167. $html .= '<ul class="nav nav-pills nav-stacked"><li>';
  1168. $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
  1169. $html .= Display::url(
  1170. Display::return_icon(
  1171. 'delete.png',
  1172. get_lang('Unsubscribe'),
  1173. [],
  1174. ICON_SIZE_TINY
  1175. ).get_lang('Unsubscribe'),
  1176. $url
  1177. );
  1178. $html .= '</li></ul>';
  1179. $html .= '</div></div>';
  1180. }
  1181. $html .= '';
  1182. return $html;
  1183. }
  1184. /**
  1185. * Displays a sortable table with the list of online users.
  1186. *
  1187. * @param array $user_list The list of users to be shown
  1188. * @param bool $wrap Whether we want the function to wrap the spans list in a div or not
  1189. *
  1190. * @return string HTML block or null if and ID was defined
  1191. * @assert (null) === false
  1192. */
  1193. public static function display_user_list($user_list, $wrap = true)
  1194. {
  1195. $html = '';
  1196. if (isset($_GET['id']) || count($user_list) < 1) {
  1197. return false;
  1198. }
  1199. $course_url = '';
  1200. if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
  1201. $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
  1202. }
  1203. $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
  1204. foreach ($user_list as $uid) {
  1205. $user_info = api_get_user_info($uid, true);
  1206. $lastname = $user_info['lastname'];
  1207. $firstname = $user_info['firstname'];
  1208. $completeName = $firstname.', '.$lastname;
  1209. $user_rol = $user_info['status'] == 1 ? Display::return_icon('teacher.png', get_lang('Teacher'), null, ICON_SIZE_TINY) : Display::return_icon('user.png', get_lang('Student'), null, ICON_SIZE_TINY);
  1210. $status_icon_chat = null;
  1211. if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
  1212. $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
  1213. } else {
  1214. $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
  1215. }
  1216. $userPicture = $user_info['avatar'];
  1217. $officialCode = '';
  1218. if (api_get_setting('show_official_code_whoisonline') == 'true') {
  1219. $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
  1220. }
  1221. if ($hide === true) {
  1222. $completeName = '';
  1223. $firstname = '';
  1224. $lastname = '';
  1225. }
  1226. $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
  1227. $url = null;
  1228. // Anonymous users can't have access to the profile
  1229. if (!api_is_anonymous()) {
  1230. if (api_get_setting('allow_social_tool') === 'true') {
  1231. $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
  1232. } else {
  1233. $url = '?id='.$uid.$course_url;
  1234. }
  1235. } else {
  1236. $url = null;
  1237. }
  1238. $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
  1239. $html .= '<div class="col-xs-6 col-md-2">
  1240. <div class="items-user">
  1241. <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
  1242. <div class="items-user-name">
  1243. '.$name.'
  1244. </div>
  1245. '.$officialCode.'
  1246. <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
  1247. </div>
  1248. </div>';
  1249. }
  1250. return $html;
  1251. }
  1252. /**
  1253. * Displays the information of an individual user.
  1254. *
  1255. * @param int $user_id
  1256. *
  1257. * @return string
  1258. */
  1259. public static function display_individual_user($user_id)
  1260. {
  1261. global $interbreadcrumb;
  1262. $safe_user_id = (int) $user_id;
  1263. $currentUserId = api_get_user_id();
  1264. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1265. $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
  1266. $result = Database::query($sql);
  1267. $html = null;
  1268. if (Database::num_rows($result) == 1) {
  1269. $user_object = Database::fetch_object($result);
  1270. $userInfo = api_get_user_info($user_id);
  1271. $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
  1272. $status = get_status_from_code($user_object->status);
  1273. $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
  1274. $html .= '<div class ="thumbnail">';
  1275. $fullurl = $userInfo['avatar'];
  1276. $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
  1277. if (!empty($status)) {
  1278. $html .= '<div class="caption">'.$status.'</div>';
  1279. }
  1280. $html .= '</div>';
  1281. if (api_get_setting('show_email_addresses') == 'true') {
  1282. $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
  1283. }
  1284. if ($user_object->competences) {
  1285. $html .= Display::page_subheader(get_lang('MyCompetences'));
  1286. $html .= '<p>'.$user_object->competences.'</p>';
  1287. }
  1288. if ($user_object->diplomas) {
  1289. $html .= Display::page_subheader(get_lang('MyDiplomas'));
  1290. $html .= '<p>'.$user_object->diplomas.'</p>';
  1291. }
  1292. if ($user_object->teach) {
  1293. $html .= Display::page_subheader(get_lang('MyTeach'));
  1294. $html .= '<p>'.$user_object->teach.'</p>';
  1295. }
  1296. self::display_productions($user_object->user_id);
  1297. if ($user_object->openarea) {
  1298. $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
  1299. $html .= '<p>'.$user_object->openarea.'</p>';
  1300. }
  1301. } else {
  1302. $html .= '<div class="actions-title">';
  1303. $html .= get_lang('UsersOnLineList');
  1304. $html .= '</div>';
  1305. }
  1306. return $html;
  1307. }
  1308. /**
  1309. * Display productions in who is online.
  1310. *
  1311. * @param int $user_id User id
  1312. */
  1313. public static function display_productions($user_id)
  1314. {
  1315. $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
  1316. $sysdir = UserManager::getUserPathById($user_id, 'system');
  1317. $webdir = UserManager::getUserPathById($user_id, 'web');
  1318. if (!is_dir($sysdir)) {
  1319. mkdir($sysdir, api_get_permissions_for_new_directories(), true);
  1320. }
  1321. $productions = UserManager::get_user_productions($user_id);
  1322. if (count($productions) > 0) {
  1323. echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
  1324. echo '<dd><ul>';
  1325. foreach ($productions as $file) {
  1326. // Only display direct file links to avoid browsing an empty directory
  1327. if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
  1328. echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
  1329. }
  1330. // Real productions are under a subdirectory by the User's id
  1331. if (is_dir($sysdir.$file)) {
  1332. $subs = scandir($sysdir.$file);
  1333. foreach ($subs as $my => $sub) {
  1334. if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
  1335. echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
  1336. }
  1337. }
  1338. }
  1339. }
  1340. echo '</ul></dd>';
  1341. }
  1342. }
  1343. /**
  1344. * @param string $content
  1345. * @param string $span_count
  1346. *
  1347. * @return string
  1348. */
  1349. public static function social_wrapper_div($content, $span_count)
  1350. {
  1351. $span_count = (int) $span_count;
  1352. $html = '<div class="span'.$span_count.'">';
  1353. $html .= '<div class="well_border">';
  1354. $html .= $content;
  1355. $html .= '</div></div>';
  1356. return $html;
  1357. }
  1358. /**
  1359. * Dummy function.
  1360. */
  1361. public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
  1362. {
  1363. $content = '';
  1364. switch ($place) {
  1365. case SOCIAL_CENTER_PLUGIN:
  1366. $social_plugins = [1, 2];
  1367. if (is_array($social_plugins) && count($social_plugins) > 0) {
  1368. $content .= '<div id="social-plugins">';
  1369. foreach ($social_plugins as $plugin) {
  1370. $content .= '<div class="social-plugin-item">';
  1371. $content .= $plugin;
  1372. $content .= '</div>';
  1373. }
  1374. $content .= '</div>';
  1375. }
  1376. break;
  1377. case SOCIAL_LEFT_PLUGIN:
  1378. break;
  1379. case SOCIAL_RIGHT_PLUGIN:
  1380. break;
  1381. }
  1382. return $content;
  1383. }
  1384. /**
  1385. * Sends a message to someone's wall.
  1386. *
  1387. * @param int $userId id of author
  1388. * @param int $friendId id where we send the message
  1389. * @param string $messageContent of the message
  1390. * @param int $messageId id parent
  1391. * @param string $messageStatus status type of message
  1392. *
  1393. * @return int
  1394. *
  1395. * @author Yannick Warnier
  1396. */
  1397. public static function sendWallMessage(
  1398. $userId,
  1399. $friendId,
  1400. $messageContent,
  1401. $messageId = 0,
  1402. $messageStatus = ''
  1403. ) {
  1404. $tblMessage = Database::get_main_table(TABLE_MESSAGE);
  1405. $userId = (int) $userId;
  1406. $friendId = (int) $friendId;
  1407. $messageId = (int) $messageId;
  1408. if (empty($userId) || empty($friendId)) {
  1409. return 0;
  1410. }
  1411. // Just in case we replace the and \n and \n\r while saving in the DB
  1412. $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
  1413. $now = api_get_utc_datetime();
  1414. $attributes = [
  1415. 'user_sender_id' => $userId,
  1416. 'user_receiver_id' => $friendId,
  1417. 'msg_status' => $messageStatus,
  1418. 'send_date' => $now,
  1419. 'title' => '',
  1420. 'content' => $messageContent,
  1421. 'parent_id' => $messageId,
  1422. 'group_id' => 0,
  1423. 'update_date' => $now,
  1424. ];
  1425. return Database::insert($tblMessage, $attributes);
  1426. }
  1427. /**
  1428. * Send File attachment (jpg,png).
  1429. *
  1430. * @author Anibal Copitan
  1431. *
  1432. * @param int $userId id user
  1433. * @param array $fileAttach
  1434. * @param int $messageId id message (relation with main message)
  1435. * @param string $fileComment description attachment file
  1436. *
  1437. * @return bool|int
  1438. */
  1439. public static function sendWallMessageAttachmentFile(
  1440. $userId,
  1441. $fileAttach,
  1442. $messageId,
  1443. $fileComment = ''
  1444. ) {
  1445. $safeFileName = Database::escape_string($fileAttach['name']);
  1446. $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
  1447. $allowedTypes = api_get_supported_image_extensions();
  1448. $allowedTypes[] = 'mp4';
  1449. $allowedTypes[] = 'webm';
  1450. $allowedTypes[] = 'ogg';
  1451. if (in_array($extension, $allowedTypes)) {
  1452. return MessageManager::saveMessageAttachmentFile($fileAttach, $fileComment, $messageId, $userId);
  1453. }
  1454. return false;
  1455. }
  1456. /**
  1457. * Gets all messages from someone's wall (within specific limits).
  1458. *
  1459. * @param int $userId id of wall shown
  1460. * @param int|string $parentId id message (Post main)
  1461. * @param int|array $groupId
  1462. * @param int|array $friendId
  1463. * @param string $startDate Date from which we want to show the messages, in UTC time
  1464. * @param int $start Limit for the number of parent messages we want to show
  1465. * @param int $length Wall message query offset
  1466. * @param bool $getCount
  1467. * @param array $threadList
  1468. *
  1469. * @return array|int
  1470. *
  1471. * @author Yannick Warnier
  1472. */
  1473. public static function getWallMessages(
  1474. $userId,
  1475. $parentId = 0,
  1476. $groupId = 0,
  1477. $friendId = 0,
  1478. $startDate = '',
  1479. $start = 0,
  1480. $length = 10,
  1481. $getCount = false,
  1482. $threadList = []
  1483. ) {
  1484. $tblMessage = Database::get_main_table(TABLE_MESSAGE);
  1485. $parentId = (int) $parentId;
  1486. $userId = (int) $userId;
  1487. $start = (int) $start;
  1488. $length = (int) $length;
  1489. $select = " SELECT
  1490. id,
  1491. user_sender_id,
  1492. user_receiver_id,
  1493. send_date,
  1494. content,
  1495. parent_id,
  1496. msg_status,
  1497. group_id,
  1498. '' as forum_id,
  1499. '' as thread_id,
  1500. '' as c_id
  1501. ";
  1502. if ($getCount) {
  1503. $select = ' SELECT count(id) count ';
  1504. }
  1505. $sql = "$select
  1506. FROM $tblMessage m
  1507. WHERE
  1508. msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
  1509. // Get my own posts
  1510. $userReceiverCondition = ' (
  1511. user_receiver_id = '.$userId.' AND
  1512. msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
  1513. parent_id = '.$parentId.'
  1514. )';
  1515. $sql .= $userReceiverCondition;
  1516. $sql .= ' OR (
  1517. msg_status IN ('.MESSAGE_STATUS_PROMOTED.')
  1518. ) ';
  1519. // Get my group posts
  1520. $groupCondition = '';
  1521. if (!empty($groupId)) {
  1522. if (is_array($groupId)) {
  1523. $groupId = array_map('intval', $groupId);
  1524. $groupId = implode("','", $groupId);
  1525. $groupCondition = " OR ( group_id IN ('$groupId') ";
  1526. } else {
  1527. $groupId = (int) $groupId;
  1528. $groupCondition = " OR ( group_id = '$groupId' ";
  1529. }
  1530. $groupCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_NEW.', '.MESSAGE_STATUS_UNREAD.')) ';
  1531. }
  1532. // Get my friend posts
  1533. $friendCondition = '';
  1534. if (!empty($friendId)) {
  1535. if (is_array($friendId)) {
  1536. $friendId = array_map('intval', $friendId);
  1537. $friendId = implode("','", $friendId);
  1538. $friendCondition = " OR ( user_receiver_id IN ('$friendId') ";
  1539. } else {
  1540. $friendId = (int) $friendId;
  1541. $friendCondition = " OR ( user_receiver_id = '$friendId' ";
  1542. }
  1543. $friendCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_WALL_POST.') AND parent_id = 0) ';
  1544. }
  1545. if (!empty($groupCondition) || !empty($friendCondition)) {
  1546. $sql .= " $groupCondition $friendCondition ";
  1547. }
  1548. if (!empty($threadList)) {
  1549. if ($getCount) {
  1550. $select = ' SELECT count(iid) count ';
  1551. } else {
  1552. $select = " SELECT
  1553. iid,
  1554. poster_id,
  1555. '' as user_receiver_id,
  1556. post_date,
  1557. post_text,
  1558. '' as parent_id,
  1559. ".MESSAGE_STATUS_FORUM.",
  1560. '' as group_id,
  1561. forum_id,
  1562. thread_id,
  1563. c_id
  1564. ";
  1565. }
  1566. $threadList = array_map('intval', $threadList);
  1567. $threadList = implode("','", $threadList);
  1568. $condition = " thread_id IN ('$threadList') ";
  1569. $sql .= "
  1570. UNION (
  1571. $select
  1572. FROM c_forum_post
  1573. WHERE $condition
  1574. )
  1575. ";
  1576. }
  1577. if ($getCount) {
  1578. $res = Database::query($sql);
  1579. $row = Database::fetch_array($res);
  1580. return (int) $row['count'];
  1581. }
  1582. $sql .= ' ORDER BY send_date DESC ';
  1583. $sql .= " LIMIT $start, $length ";
  1584. $messages = [];
  1585. $res = Database::query($sql);
  1586. $em = Database::getManager();
  1587. if (Database::num_rows($res) > 0) {
  1588. $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
  1589. $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
  1590. $groups = [];
  1591. $userGroup = new UserGroup();
  1592. $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
  1593. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1594. $row['group_info'] = [];
  1595. if (!empty($row['group_id'])) {
  1596. if (!in_array($row['group_id'], $groups)) {
  1597. $group = $userGroup->get($row['group_id']);
  1598. $group['url'] = $urlGroup.$group['id'];
  1599. $groups[$row['group_id']] = $group;
  1600. $row['group_info'] = $group;
  1601. } else {
  1602. $row['group_info'] = $groups[$row['group_id']];
  1603. }
  1604. }
  1605. // Forums
  1606. $row['post_title'] = '';
  1607. $row['forum_title'] = '';
  1608. $row['thread_url'] = '';
  1609. if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
  1610. /** @var CForumPost $post */
  1611. $post = $repo->find($row['id']);
  1612. /** @var CForumThread $thread */
  1613. $thread = $repoThread->find($row['thread_id']);
  1614. if ($post && $thread) {
  1615. $courseInfo = api_get_course_info_by_id($post->getCId());
  1616. $row['post_title'] = $post->getForumId();
  1617. $row['forum_title'] = $thread->getThreadTitle();
  1618. $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
  1619. 'cidReq' => $courseInfo['code'],
  1620. 'forum' => $post->getForumId(),
  1621. 'thread' => $post->getThreadId(),
  1622. 'post_id' => $post->getIid(),
  1623. ]).'#post_id_'.$post->getIid();
  1624. }
  1625. }
  1626. $messages[] = $row;
  1627. }
  1628. }
  1629. return $messages;
  1630. }
  1631. /**
  1632. * Gets all messages from someone's wall (within specific limits), formatted.
  1633. *
  1634. * @param int $userId USER ID of the person's wall
  1635. * @param array $messageInfo
  1636. * @param string $start Start date (from when we want the messages until today)
  1637. * @param int $limit Limit to the number of messages we want
  1638. * @param int $offset Wall messages offset
  1639. *
  1640. * @return string HTML formatted string to show messages
  1641. */
  1642. public static function getWallPostComments(
  1643. $userId,
  1644. $messageInfo,
  1645. $start = null,
  1646. $limit = 10,
  1647. $offset = 0
  1648. ) {
  1649. $messageId = $messageInfo['id'];
  1650. $messages = MessageManager::getMessagesByParent($messageInfo['id'], 0, $offset, $limit);
  1651. $formattedList = '<div class="sub-mediapost row">';
  1652. $users = [];
  1653. // The messages are ordered by date descendant, for comments we need ascendant
  1654. krsort($messages);
  1655. foreach ($messages as $message) {
  1656. $userIdLoop = $message['user_sender_id'];
  1657. if (!isset($users[$userIdLoop])) {
  1658. $users[$userIdLoop] = api_get_user_info($userIdLoop);
  1659. }
  1660. $media = self::processPostComment($message, $users);
  1661. $formattedList .= $media;
  1662. }
  1663. $formattedList .= '</div>';
  1664. $formattedList .= '<div class="mediapost-form row">';
  1665. $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
  1666. <div class="col-sm-9">
  1667. <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
  1668. <input type="hidden" name = "messageId" value="'.$messageId.'" />
  1669. <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
  1670. </div>
  1671. <div class="col-sm-3 pull-right">
  1672. <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
  1673. <em class="fa fa-pencil"></em> '.get_lang('Post').'
  1674. </a>
  1675. </div>
  1676. </form>';
  1677. $formattedList .= '</div>';
  1678. return $formattedList;
  1679. }
  1680. /**
  1681. * @param array $message
  1682. * @param array $users
  1683. *
  1684. * @return string
  1685. */
  1686. public static function processPostComment($message, $users = [])
  1687. {
  1688. if (empty($message)) {
  1689. return false;
  1690. }
  1691. $date = Display::dateToStringAgoAndLongDate($message['send_date']);
  1692. $currentUserId = api_get_user_id();
  1693. $userIdLoop = $message['user_sender_id'];
  1694. $receiverId = $message['user_receiver_id'];
  1695. if (!isset($users[$userIdLoop])) {
  1696. $users[$userIdLoop] = api_get_user_info($userIdLoop);
  1697. }
  1698. $iconStatus = $users[$userIdLoop]['icon_status'];
  1699. $nameComplete = $users[$userIdLoop]['complete_name'];
  1700. $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
  1701. $comment = '<div class="rep-post col-md-12">';
  1702. $comment .= '<div class="col-md-2 col-xs-2 social-post-answers">';
  1703. $comment .= '<div class="user-image pull-right">';
  1704. $comment .= '<a href="'.$url.'">
  1705. <img src="'.$users[$userIdLoop]['avatar'].'"
  1706. alt="'.$users[$userIdLoop]['complete_name'].'"
  1707. class="avatar-thumb">
  1708. </a>';
  1709. $comment .= '</div>';
  1710. $comment .= '</div>';
  1711. $comment .= '<div class="col-md-7 col-xs-7 social-post-answers">';
  1712. $comment .= '<div class="user-data">';
  1713. $comment .= $iconStatus;
  1714. $comment .= '<div class="username"><a href="'.$url.'">'.$nameComplete.'</a>
  1715. <span>'.Security::remove_XSS($message['content']).'</span>
  1716. </div>';
  1717. $comment .= '<div>'.$date.'</div>';
  1718. $comment .= '<br />';
  1719. $comment .= '</div>';
  1720. $comment .= '</div>';
  1721. $comment .= '<div class="col-md-3 col-xs-3 social-post-answers">';
  1722. $comment .= '<div class="pull-right btn-group btn-group-sm">';
  1723. $comment .= MessageManager::getLikesButton(
  1724. $message['id'],
  1725. $currentUserId
  1726. );
  1727. $isOwnWall = $currentUserId == $userIdLoop || $currentUserId == $receiverId;
  1728. if ($isOwnWall) {
  1729. $comment .= Display::url(
  1730. Display::returnFontAwesomeIcon('trash', '', true),
  1731. 'javascript:void(0)',
  1732. [
  1733. 'id' => 'message_'.$message['id'],
  1734. 'title' => get_lang('SocialMessageDelete'),
  1735. 'onclick' => 'deleteComment('.$message['id'].')',
  1736. 'class' => 'btn btn-default',
  1737. ]
  1738. );
  1739. }
  1740. $comment .= '</div>';
  1741. $comment .= '</div>';
  1742. $comment .= '</div>';
  1743. return $comment;
  1744. }
  1745. /**
  1746. * @param array $message
  1747. *
  1748. * @return array
  1749. */
  1750. public static function getAttachmentPreviewList($message)
  1751. {
  1752. $messageId = $message['id'];
  1753. $list = [];
  1754. if (empty($message['group_id'])) {
  1755. $files = MessageManager::getAttachmentList($messageId);
  1756. if ($files) {
  1757. $downloadUrl = api_get_path(WEB_CODE_PATH).'social/download.php?message_id='.$messageId;
  1758. foreach ($files as $row_file) {
  1759. $url = $downloadUrl.'&attachment_id='.$row_file['id'];
  1760. $display = Display::fileHtmlGuesser($row_file['filename'], $url);
  1761. $list[] = $display;
  1762. }
  1763. }
  1764. } else {
  1765. $list = MessageManager::getAttachmentLinkList($messageId, 0);
  1766. }
  1767. return $list;
  1768. }
  1769. /**
  1770. * @param array $message
  1771. *
  1772. * @return string
  1773. */
  1774. public static function getPostAttachment($message)
  1775. {
  1776. $previews = self::getAttachmentPreviewList($message);
  1777. if (empty($previews)) {
  1778. return '';
  1779. }
  1780. return implode('', $previews);
  1781. }
  1782. /**
  1783. * @param array $messages
  1784. *
  1785. * @return array
  1786. */
  1787. public static function formatWallMessages($messages)
  1788. {
  1789. $data = [];
  1790. $users = [];
  1791. foreach ($messages as $key => $message) {
  1792. $userIdLoop = $message['user_sender_id'];
  1793. $userFriendIdLoop = $message['user_receiver_id'];
  1794. if (!isset($users[$userIdLoop])) {
  1795. $users[$userIdLoop] = api_get_user_info($userIdLoop);
  1796. }
  1797. if (!isset($users[$userFriendIdLoop])) {
  1798. $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
  1799. }
  1800. $html = self::headerMessagePost(
  1801. $users[$userIdLoop],
  1802. $users[$userFriendIdLoop],
  1803. $message
  1804. );
  1805. $data[$key] = $message;
  1806. $data[$key]['html'] = $html;
  1807. }
  1808. return $data;
  1809. }
  1810. /**
  1811. * get html data with OpenGrap passing the URL.
  1812. *
  1813. * @param $link url
  1814. *
  1815. * @return string data html
  1816. */
  1817. public static function readContentWithOpenGraph($link)
  1818. {
  1819. if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
  1820. $link = "http://".$link;
  1821. }
  1822. $graph = OpenGraph::fetch($link);
  1823. $link = parse_url($link);
  1824. $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
  1825. if (!$graph) {
  1826. return false;
  1827. }
  1828. $url = $graph->url;
  1829. $image = $graph->image;
  1830. $description = $graph->description;
  1831. $title = $graph->title;
  1832. $html = '<div class="thumbnail social-thumbnail">';
  1833. $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
  1834. <img class="img-responsive social-image" src="'.$image.'" /></a>';
  1835. $html .= '<div class="social-description">';
  1836. $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
  1837. $html .= empty($description) ? '' : '<span>'.$description.'</span>';
  1838. $html .= empty($host) ? '' : '<p>'.$host.'</p>';
  1839. $html .= '</div>';
  1840. $html .= '</div>';
  1841. return $html;
  1842. }
  1843. /**
  1844. * verify if Url Exist - Using Curl.
  1845. *
  1846. * @param $uri url
  1847. *
  1848. * @return bool
  1849. */
  1850. public static function verifyUrl($uri)
  1851. {
  1852. $curl = curl_init($uri);
  1853. curl_setopt($curl, CURLOPT_FAILONERROR, true);
  1854. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  1855. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1856. curl_setopt($curl, CURLOPT_TIMEOUT, 15);
  1857. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  1858. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  1859. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  1860. $response = curl_exec($curl);
  1861. curl_close($curl);
  1862. if (!empty($response)) {
  1863. return true;
  1864. }
  1865. return false;
  1866. }
  1867. /**
  1868. * Soft delete a message and his chidren.
  1869. *
  1870. * @param int $id id message to delete
  1871. *
  1872. * @return bool status query
  1873. */
  1874. public static function deleteMessage($id)
  1875. {
  1876. $id = (int) $id;
  1877. $messageInfo = MessageManager::get_message_by_id($id);
  1878. if (!empty($messageInfo)) {
  1879. // Delete comments too
  1880. $messages = MessageManager::getMessagesByParent($id);
  1881. if (!empty($messages)) {
  1882. foreach ($messages as $message) {
  1883. self::deleteMessage($message['id']);
  1884. }
  1885. }
  1886. // Soft delete message
  1887. $tblMessage = Database::get_main_table(TABLE_MESSAGE);
  1888. $statusMessage = MESSAGE_STATUS_WALL_DELETE;
  1889. $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
  1890. Database::query($sql);
  1891. MessageManager::delete_message_attachment_file($id, $messageInfo['user_sender_id']);
  1892. MessageManager::delete_message_attachment_file($id, $messageInfo['user_receiver_id']);
  1893. return true;
  1894. }
  1895. return false;
  1896. }
  1897. /**
  1898. * Generate the social block for a user.
  1899. *
  1900. * @param Template $template
  1901. * @param int $userId The user id
  1902. * @param string $groupBlock Optional. Highlight link possible values:
  1903. * group_add, home, messages, messages_inbox, messages_compose,
  1904. * messages_outbox, invitations, shared_profile, friends, groups, search
  1905. * @param int $groupId Optional. Group ID
  1906. * @param bool $show_full_profile
  1907. *
  1908. * @return string The HTML code with the social block
  1909. */
  1910. public static function setSocialUserBlock(
  1911. Template $template,
  1912. $userId,
  1913. $groupBlock = '',
  1914. $groupId = 0,
  1915. $show_full_profile = true
  1916. ) {
  1917. if (api_get_setting('allow_social_tool') != 'true') {
  1918. return '';
  1919. }
  1920. $currentUserId = api_get_user_id();
  1921. $userId = (int) $userId;
  1922. $userRelationType = 0;
  1923. $socialAvatarBlock = self::show_social_avatar_block(
  1924. $groupBlock,
  1925. $groupId,
  1926. $userId
  1927. );
  1928. $profileEditionLink = null;
  1929. if ($currentUserId === $userId) {
  1930. $profileEditionLink = Display::getProfileEditionLink($userId);
  1931. } else {
  1932. $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
  1933. }
  1934. $options = api_get_configuration_value('profile_fields_visibility');
  1935. if (isset($options['options'])) {
  1936. $options = $options['options'];
  1937. }
  1938. $vCardUserLink = Display::getVCardUserLink($userId);
  1939. if (isset($options['vcard']) && $options['vcard'] === false) {
  1940. $vCardUserLink = '';
  1941. }
  1942. $userInfo = api_get_user_info($userId, true, false, true, true);
  1943. if (isset($options['firstname']) && $options['firstname'] === false) {
  1944. $userInfo['firstname'] = '';
  1945. }
  1946. if (isset($options['lastname']) && $options['lastname'] === false) {
  1947. $userInfo['lastname'] = '';
  1948. }
  1949. if (isset($options['email']) && $options['email'] === false) {
  1950. $userInfo['email'] = '';
  1951. }
  1952. // Ofaj
  1953. $hasCertificates = Certificate::getCertificateByUser($userId);
  1954. $userInfo['has_certificates'] = 0;
  1955. if (!empty($hasCertificates)) {
  1956. $userInfo['has_certificates'] = 1;
  1957. }
  1958. $userInfo['is_admin'] = UserManager::is_admin($userId);
  1959. $languageId = api_get_language_id($userInfo['language']);
  1960. $languageInfo = api_get_language_info($languageId);
  1961. if ($languageInfo) {
  1962. $userInfo['language'] = [
  1963. 'label' => $languageInfo['original_name'],
  1964. 'value' => $languageInfo['english_name'],
  1965. 'code' => $languageInfo['isocode'],
  1966. ];
  1967. }
  1968. if (isset($options['language']) && $options['language'] === false) {
  1969. $userInfo['language'] = '';
  1970. }
  1971. if (isset($options['photo']) && $options['photo'] === false) {
  1972. $socialAvatarBlock = '';
  1973. }
  1974. $extraFieldBlock = self::getExtraFieldBlock($userId, true);
  1975. $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
  1976. $template->assign('user', $userInfo);
  1977. $template->assign('show_language_flag', $showLanguageFlag);
  1978. $template->assign('extra_info', $extraFieldBlock);
  1979. $template->assign('social_avatar_block', $socialAvatarBlock);
  1980. $template->assign('profile_edition_link', $profileEditionLink);
  1981. //Added the link to export the vCard to the Template
  1982. //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
  1983. if ($show_full_profile) {
  1984. $template->assign('vcard_user_link', $vCardUserLink);
  1985. }
  1986. if (api_get_setting('gamification_mode') === '1') {
  1987. $gamificationPoints = GamificationUtils::getTotalUserPoints(
  1988. $userId,
  1989. $userInfo['status']
  1990. );
  1991. $template->assign('gamification_points', $gamificationPoints);
  1992. }
  1993. $chatEnabled = api_is_global_chat_enabled();
  1994. if (isset($options['chat']) && $options['chat'] === false) {
  1995. $chatEnabled = '';
  1996. }
  1997. $template->assign('chat_enabled', $chatEnabled);
  1998. $template->assign('user_relation', $userRelationType);
  1999. $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
  2000. $template->assign('show_full_profile', $show_full_profile);
  2001. $templateName = $template->get_template('social/user_block.tpl');
  2002. if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
  2003. $templateName = $template->get_template('social/group_block.tpl');
  2004. }
  2005. $template->assign('social_avatar_block', $template->fetch($templateName));
  2006. }
  2007. /**
  2008. * @param int $user_id
  2009. * @param $link_shared
  2010. * @param $show_full_profile
  2011. *
  2012. * @return string
  2013. */
  2014. public static function listMyFriends($user_id, $link_shared, $show_full_profile)
  2015. {
  2016. // SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
  2017. $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
  2018. $number_of_images = 30;
  2019. $number_friends = count($friends);
  2020. $friendHtml = '';
  2021. if ($number_friends != 0) {
  2022. if ($number_friends > $number_of_images) {
  2023. if (api_get_user_id() == $user_id) {
  2024. $friendHtml .= ' <span><a href="friends.php">'.get_lang('SeeAll').'</a></span>';
  2025. } else {
  2026. $friendHtml .= ' <span>'
  2027. .'<a href="'.api_get_path(WEB_CODE_PATH).'social/profile_friends_and_groups.inc.php'
  2028. .'?view=friends&height=390&width=610&user_id='.$user_id.'"'
  2029. .'class="ajax" data-title="'.get_lang('SeeAll').'" title="'.get_lang('SeeAll').'" >'.get_lang('SeeAll').'</a></span>';
  2030. }
  2031. }
  2032. $friendHtml .= '<ul class="nav nav-list">';
  2033. $j = 1;
  2034. for ($k = 0; $k < $number_friends; $k++) {
  2035. if ($j > $number_of_images) {
  2036. break;
  2037. }
  2038. if (isset($friends[$k])) {
  2039. $friend = $friends[$k];
  2040. $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
  2041. $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
  2042. if ($user_info_friend['user_is_online']) {
  2043. $statusIcon = Display::span('', ['class' => 'online_user_in_text']);
  2044. } else {
  2045. $statusIcon = Display::span('', ['class' => 'offline_user_in_text']);
  2046. }
  2047. $friendHtml .= '<li>';
  2048. $friendHtml .= '<div>';
  2049. // the height = 92 must be the same in the image_friend_network span style in default.css
  2050. $friends_profile = UserManager::getUserPicture(
  2051. $friend['friend_user_id'],
  2052. USER_IMAGE_SIZE_SMALL
  2053. );
  2054. $friendHtml .= '<img src="'.$friends_profile.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'"/>';
  2055. $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
  2056. $friendHtml .= $statusIcon.'<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'">'.$name_user.'</a>';
  2057. $friendHtml .= '</div>';
  2058. $friendHtml .= '</li>';
  2059. }
  2060. $j++;
  2061. }
  2062. $friendHtml .= '</ul>';
  2063. } else {
  2064. $friendHtml .= '<div class="">'.get_lang('NoFriendsInYourContactList').'<br />
  2065. <a class="btn btn-primary" href="'.api_get_path(WEB_PATH).'whoisonline.php">
  2066. <em class="fa fa-search"></em> '.get_lang('TryAndFindSomeFriends').'</a></div>';
  2067. }
  2068. $friendHtml = Display::panel($friendHtml, get_lang('SocialFriend').' ('.$number_friends.')');
  2069. return $friendHtml;
  2070. }
  2071. /**
  2072. * @param int $user_id
  2073. * @param $link_shared
  2074. * @param bool $showLinkToChat
  2075. *
  2076. * @return string
  2077. */
  2078. public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
  2079. {
  2080. //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
  2081. $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
  2082. $numberFriends = count($friends);
  2083. $friendHtml = '';
  2084. if (!empty($numberFriends)) {
  2085. $friendHtml .= '<div class="list-group contact-list">';
  2086. $j = 1;
  2087. usort(
  2088. $friends,
  2089. function ($a, $b) {
  2090. return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
  2091. }
  2092. );
  2093. foreach ($friends as $friend) {
  2094. if ($j > $numberFriends) {
  2095. break;
  2096. }
  2097. $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
  2098. $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
  2099. $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
  2100. $status = 0;
  2101. if (!empty($user_info_friend['user_is_online_in_chat'])) {
  2102. $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
  2103. $status = 1;
  2104. }
  2105. $friendAvatarMedium = UserManager::getUserPicture(
  2106. $friend['friend_user_id'],
  2107. USER_IMAGE_SIZE_MEDIUM
  2108. );
  2109. $friendAvatarSmall = UserManager::getUserPicture(
  2110. $friend['friend_user_id'],
  2111. USER_IMAGE_SIZE_SMALL
  2112. );
  2113. $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
  2114. $relation = self::get_relation_between_contacts(
  2115. $friend['friend_user_id'],
  2116. api_get_user_id()
  2117. );
  2118. if ($showLinkToChat) {
  2119. $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
  2120. $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
  2121. $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
  2122. } else {
  2123. $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
  2124. $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
  2125. $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
  2126. $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
  2127. }
  2128. $friendHtml .= '</a>';
  2129. $j++;
  2130. }
  2131. $friendHtml .= '</div>';
  2132. } else {
  2133. $friendHtml = Display::return_message(get_lang('NoFriendsInYourContactList'), 'warning');
  2134. }
  2135. return $friendHtml;
  2136. }
  2137. /**
  2138. * @return string Get the JS code necessary for social wall to load open graph from URLs.
  2139. */
  2140. public static function getScriptToGetOpenGraph()
  2141. {
  2142. return '<script>
  2143. $(function() {
  2144. $("[name=\'social_wall_new_msg_main\']").on("paste", function(e) {
  2145. $.ajax({
  2146. contentType: "application/x-www-form-urlencoded",
  2147. beforeSend: function() {
  2148. $("[name=\'wall_post_button\']").prop( "disabled", true );
  2149. $(".panel-preview").hide();
  2150. $(".spinner").html("'
  2151. .'<div class=\'text-center\'>'
  2152. .'<em class=\'fa fa-spinner fa-pulse fa-1x\'></em>'
  2153. .'<p>'.get_lang('Loading').' '.get_lang('Preview').'</p>'
  2154. .'</div>'
  2155. .'");
  2156. },
  2157. type: "POST",
  2158. url: "'.api_get_path(WEB_AJAX_PATH).'social.ajax.php?a=read_url_with_open_graph",
  2159. data: "social_wall_new_msg_main=" + e.originalEvent.clipboardData.getData("text"),
  2160. success: function(response) {
  2161. $("[name=\'wall_post_button\']").prop("disabled", false);
  2162. if (!response == false) {
  2163. $(".spinner").html("");
  2164. $(".panel-preview").show();
  2165. $(".url_preview").html(response);
  2166. $("[name=\'url_content\']").val(response);
  2167. $(".url_preview img").addClass("img-responsive");
  2168. } else {
  2169. $(".spinner").html("");
  2170. }
  2171. }
  2172. });
  2173. });
  2174. });
  2175. </script>';
  2176. }
  2177. /**
  2178. * @param string $urlForm
  2179. *
  2180. * @return string
  2181. */
  2182. public static function getWallForm($urlForm)
  2183. {
  2184. $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
  2185. $form = new FormValidator(
  2186. 'social_wall_main',
  2187. 'post',
  2188. $urlForm.$userId,
  2189. null,
  2190. ['enctype' => 'multipart/form-data'],
  2191. FormValidator::LAYOUT_HORIZONTAL
  2192. );
  2193. $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
  2194. 'SocialWallWhatAreYouThinkingAbout'
  2195. );
  2196. $form->addTextarea(
  2197. 'social_wall_new_msg_main',
  2198. null,
  2199. [
  2200. 'placeholder' => $socialWallPlaceholder,
  2201. 'cols-size' => [1, 12, 1],
  2202. 'aria-label' => $socialWallPlaceholder,
  2203. ]
  2204. );
  2205. $form->addHtml('<div class="form-group">');
  2206. $form->addHtml('<div class="col-sm-6">');
  2207. $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
  2208. $form->addHtml('</div>');
  2209. $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
  2210. $form->addButtonSend(
  2211. get_lang('Post'),
  2212. 'wall_post_button',
  2213. false,
  2214. [
  2215. 'cols-size' => [1, 10, 1],
  2216. 'custom' => true,
  2217. ]
  2218. );
  2219. $form->addHtml('</div></div>');
  2220. $form->addHtml('</div>');
  2221. $form->addHidden('url_content', '');
  2222. $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
  2223. return $html;
  2224. }
  2225. /**
  2226. * @param int $userId
  2227. * @param int $start
  2228. * @param int $length
  2229. * @param array $threadList
  2230. *
  2231. * @return array
  2232. */
  2233. public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
  2234. {
  2235. $userGroup = new UserGroup();
  2236. $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
  2237. $groupList = [];
  2238. if (!empty($groups)) {
  2239. $groupList = array_column($groups, 'id');
  2240. }
  2241. $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
  2242. $friendList = [];
  2243. if (!empty($friends)) {
  2244. $friendList = array_column($friends, 'friend_user_id');
  2245. }
  2246. $messages = self::getWallMessages(
  2247. $userId,
  2248. 0,
  2249. $groupList,
  2250. $friendList,
  2251. '',
  2252. $start,
  2253. $length,
  2254. false,
  2255. $threadList
  2256. );
  2257. $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
  2258. $messages = self::formatWallMessages($messages);
  2259. $html = '';
  2260. foreach ($messages as $message) {
  2261. $post = $message['html'];
  2262. $comments = '';
  2263. if (in_array($message['msg_status'], [MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
  2264. $comments = self::getWallPostComments($userId, $message);
  2265. }
  2266. $html .= self::wrapPost($message, $post.$comments);
  2267. }
  2268. return [
  2269. 'posts' => $html,
  2270. 'count' => $countPost,
  2271. ];
  2272. }
  2273. /**
  2274. * @param string $message
  2275. * @param string $content
  2276. *
  2277. * @return string
  2278. */
  2279. public static function wrapPost($message, $content)
  2280. {
  2281. $class = '';
  2282. if ($message['msg_status'] === MESSAGE_STATUS_PROMOTED) {
  2283. $class = 'promoted_post';
  2284. }
  2285. return Display::panel($content, '',
  2286. '',
  2287. 'default',
  2288. '',
  2289. 'post_'.$message['id'],
  2290. null,
  2291. $class
  2292. );
  2293. }
  2294. /**
  2295. * @param int $userId
  2296. * @param array $groupList
  2297. * @param array $friendList
  2298. * @param array $threadList
  2299. *
  2300. * @return int
  2301. */
  2302. public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
  2303. {
  2304. $count = self::getWallMessages(
  2305. $userId,
  2306. 0,
  2307. $groupList,
  2308. $friendList,
  2309. '',
  2310. 0,
  2311. 0,
  2312. true,
  2313. $threadList
  2314. );
  2315. return $count;
  2316. }
  2317. /**
  2318. * @param int $userId
  2319. *
  2320. * @return string
  2321. */
  2322. public static function getWallMessagesByUser($userId)
  2323. {
  2324. $messages = self::getWallMessages($userId);
  2325. $messages = self::formatWallMessages($messages);
  2326. $html = '';
  2327. foreach ($messages as $message) {
  2328. $post = $message['html'];
  2329. $comments = self::getWallPostComments($userId, $message);
  2330. $html .= self::wrapPost($message, $post.$comments);
  2331. }
  2332. return $html;
  2333. }
  2334. /**
  2335. * Get HTML code block for user skills.
  2336. *
  2337. * @param int $userId The user ID
  2338. * @param string $orientation
  2339. *
  2340. * @return string
  2341. */
  2342. public static function getSkillBlock($userId, $orientation = 'horizontal')
  2343. {
  2344. if (Skill::isAllowed($userId, false) === false) {
  2345. return '';
  2346. }
  2347. $skill = new Skill();
  2348. $ranking = $skill->getUserSkillRanking($userId);
  2349. $template = new Template(null, false, false, false, false, false);
  2350. $template->assign('ranking', $ranking);
  2351. $template->assign('orientation', $orientation);
  2352. $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
  2353. $template->assign('user_id', $userId);
  2354. $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
  2355. $skillBlock = $template->get_template('social/skills_block.tpl');
  2356. return $template->fetch($skillBlock);
  2357. }
  2358. /**
  2359. * @param int $user_id
  2360. * @param bool $isArray
  2361. *
  2362. * @return string|array
  2363. */
  2364. public static function getExtraFieldBlock($user_id, $isArray = false)
  2365. {
  2366. $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
  2367. $fieldVisibilityKeys = [];
  2368. if (isset($fieldVisibility['options'])) {
  2369. $fieldVisibility = $fieldVisibility['options'];
  2370. $fieldVisibilityKeys = array_keys($fieldVisibility);
  2371. }
  2372. $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  2373. $extra_user_data = UserManager::get_extra_user_data($user_id);
  2374. $extra_information = '';
  2375. if (is_array($extra_user_data) && count($extra_user_data) > 0) {
  2376. $extra_information_value = '';
  2377. $extraField = new ExtraField('user');
  2378. $listType = [];
  2379. $extraFieldItem = [];
  2380. foreach ($extra_user_data as $key => $data) {
  2381. if (empty($data)) {
  2382. continue;
  2383. }
  2384. if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
  2385. continue;
  2386. }
  2387. // Avoiding parameters
  2388. if (in_array(
  2389. $key,
  2390. [
  2391. 'mail_notify_invitation',
  2392. 'mail_notify_message',
  2393. 'mail_notify_group_message',
  2394. ]
  2395. )) {
  2396. continue;
  2397. }
  2398. // get display text, visibility and type from user_field table
  2399. $field_variable = str_replace('extra_', '', $key);
  2400. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
  2401. $field_variable
  2402. );
  2403. if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
  2404. continue;
  2405. }
  2406. // if is not visible skip
  2407. if ($extraFieldInfo['visible_to_self'] != 1) {
  2408. continue;
  2409. }
  2410. // if is not visible to others skip also
  2411. if ($extraFieldInfo['visible_to_others'] != 1) {
  2412. continue;
  2413. }
  2414. if (is_array($data)) {
  2415. switch ($extraFieldInfo['field_type']) {
  2416. case ExtraField::FIELD_TYPE_RADIO:
  2417. $objEfOption = new ExtraFieldOption('user');
  2418. $value = $data['extra_'.$extraFieldInfo['variable']];
  2419. $optionInfo = $objEfOption->get_field_option_by_field_and_option(
  2420. $extraFieldInfo['id'],
  2421. $value
  2422. );
  2423. if ($optionInfo && isset($optionInfo[0])) {
  2424. $optionInfo = $optionInfo[0];
  2425. $extraFieldItem = [
  2426. 'variable' => $extraFieldInfo['variable'],
  2427. 'label' => ucfirst($extraFieldInfo['display_text']),
  2428. 'value' => $optionInfo['display_text'],
  2429. ];
  2430. } else {
  2431. $extraFieldItem = [
  2432. 'variable' => $extraFieldInfo['variable'],
  2433. 'label' => ucfirst($extraFieldInfo['display_text']),
  2434. 'value' => implode(',', $data),
  2435. ];
  2436. }
  2437. break;
  2438. default:
  2439. $extra_information_value .=
  2440. '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
  2441. .' '.implode(',', $data).'</li>';
  2442. $extraFieldItem = [
  2443. 'variable' => $extraFieldInfo['variable'],
  2444. 'label' => ucfirst($extraFieldInfo['display_text']),
  2445. 'value' => implode(',', $data),
  2446. ];
  2447. break;
  2448. }
  2449. } else {
  2450. switch ($extraFieldInfo['field_type']) {
  2451. case ExtraField::FIELD_TYPE_RADIO:
  2452. $objEfOption = new ExtraFieldOption('user');
  2453. $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
  2454. break;
  2455. case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
  2456. case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
  2457. $data = explode('::', $data);
  2458. $data = $data[0];
  2459. $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
  2460. $extraFieldItem = [
  2461. 'variable' => $extraFieldInfo['variable'],
  2462. 'label' => ucfirst($extraFieldInfo['display_text']),
  2463. 'value' => $data,
  2464. ];
  2465. break;
  2466. case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
  2467. $id_options = explode('::', $data);
  2468. $value_options = [];
  2469. // get option display text from user_field_options table
  2470. foreach ($id_options as $id_option) {
  2471. $sql = "SELECT display_text
  2472. FROM $t_ufo
  2473. WHERE id = '$id_option'";
  2474. $res_options = Database::query($sql);
  2475. $row_options = Database::fetch_row($res_options);
  2476. $value_options[] = $row_options[0];
  2477. }
  2478. $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
  2479. .' '.implode(' ', $value_options).'</li>';
  2480. $extraFieldItem = [
  2481. 'variable' => $extraFieldInfo['variable'],
  2482. 'label' => ucfirst($extraFieldInfo['display_text']),
  2483. 'value' => $value_options,
  2484. ];
  2485. break;
  2486. case ExtraField::FIELD_TYPE_TAG:
  2487. $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
  2488. $tag_tmp = '';
  2489. foreach ($user_tags as $tags) {
  2490. $tag_tmp .= '<a class="label label_tag"'
  2491. .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
  2492. .$tags['tag']
  2493. .'</a>';
  2494. }
  2495. if (is_array($user_tags) && count($user_tags) > 0) {
  2496. $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
  2497. .' '.$tag_tmp.'</li>';
  2498. }
  2499. $extraFieldItem = [
  2500. 'variable' => $extraFieldInfo['variable'],
  2501. 'label' => ucfirst($extraFieldInfo['display_text']),
  2502. 'value' => $tag_tmp,
  2503. ];
  2504. break;
  2505. case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
  2506. $icon_path = UserManager::get_favicon_from_url($data);
  2507. if (self::verifyUrl($icon_path) == false) {
  2508. break;
  2509. }
  2510. $bottom = '0.2';
  2511. //quick hack for hi5
  2512. $domain = parse_url($icon_path, PHP_URL_HOST);
  2513. if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
  2514. $bottom = '-0.8';
  2515. }
  2516. $data = '<a href="'.$data.'">'
  2517. .'<img src="'.$icon_path.'" alt="icon"'
  2518. .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
  2519. .$extraFieldInfo['display_text']
  2520. .'</a>';
  2521. $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
  2522. $extraFieldItem = [
  2523. 'variable' => $extraFieldInfo['variable'],
  2524. 'label' => ucfirst($extraFieldInfo['display_text']),
  2525. 'value' => $data,
  2526. ];
  2527. break;
  2528. case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  2529. $parsedData = explode('::', $data);
  2530. if (!$parsedData) {
  2531. break;
  2532. }
  2533. $objEfOption = new ExtraFieldOption('user');
  2534. $optionInfo = $objEfOption->get($parsedData[0]);
  2535. $extra_information_value .= '<li class="list-group-item">'
  2536. .$optionInfo['display_text'].': '
  2537. .$parsedData[1].'</li>';
  2538. $extraFieldItem = [
  2539. 'variable' => $extraFieldInfo['variable'],
  2540. 'label' => ucfirst($extraFieldInfo['display_text']),
  2541. 'value' => $parsedData[1],
  2542. ];
  2543. break;
  2544. case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
  2545. $optionIds = explode(';', $data);
  2546. $optionValues = [];
  2547. foreach ($optionIds as $optionId) {
  2548. $objEfOption = new ExtraFieldOption('user');
  2549. $optionInfo = $objEfOption->get($optionId);
  2550. $optionValues[] = $optionInfo['display_text'];
  2551. }
  2552. $extra_information_value .= '<li class="list-group-item">'
  2553. .ucfirst($extraFieldInfo['display_text']).': '
  2554. .implode(' ', $optionValues).'</li>';
  2555. $extraFieldItem = [
  2556. 'variable' => $extraFieldInfo['variable'],
  2557. 'label' => ucfirst($extraFieldInfo['display_text']),
  2558. 'value' => implode(' ', $optionValues),
  2559. ];
  2560. break;
  2561. default:
  2562. // Ofaj
  2563. // Converts "Date of birth" into "age"
  2564. if ($key === 'terms_datedenaissance') {
  2565. $dataArray = date_to_str_ago($data, 'UTC', true);
  2566. $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
  2567. if (!empty($dataToString)) {
  2568. $data = $dataToString;
  2569. $extraFieldInfo['display_text'] = get_lang('Age');
  2570. }
  2571. }
  2572. $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
  2573. $extraFieldItem = [
  2574. 'variable' => $extraFieldInfo['variable'],
  2575. 'label' => ucfirst($extraFieldInfo['display_text']),
  2576. 'value' => $data,
  2577. ];
  2578. break;
  2579. }
  2580. }
  2581. $listType[] = $extraFieldItem;
  2582. }
  2583. if ($isArray) {
  2584. return $listType;
  2585. } else {
  2586. // if there are information to show
  2587. if (!empty($extra_information_value)) {
  2588. $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
  2589. $extra_information .= Display::panelCollapse(
  2590. get_lang('ExtraInformation'),
  2591. $extra_information_value,
  2592. 'sn-extra-information',
  2593. null,
  2594. 'sn-extra-accordion',
  2595. 'sn-extra-collapse'
  2596. );
  2597. }
  2598. }
  2599. }
  2600. return $extra_information;
  2601. }
  2602. /**
  2603. * @param string $url
  2604. */
  2605. public static function handlePosts($url)
  2606. {
  2607. $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
  2608. $url = Security::remove_XSS($url);
  2609. // Main post
  2610. if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
  2611. $messageContent = $_POST['social_wall_new_msg_main'];
  2612. if (!empty($_POST['url_content'])) {
  2613. $messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
  2614. }
  2615. $messageId = self::sendWallMessage(
  2616. api_get_user_id(),
  2617. $friendId,
  2618. $messageContent,
  2619. 0,
  2620. MESSAGE_STATUS_WALL_POST
  2621. );
  2622. if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
  2623. self::sendWallMessageAttachmentFile(
  2624. api_get_user_id(),
  2625. $_FILES['picture'],
  2626. $messageId
  2627. );
  2628. }
  2629. Display::addFlash(Display::return_message(get_lang('MessageSent')));
  2630. header('Location: '.$url);
  2631. exit;
  2632. }
  2633. }
  2634. /**
  2635. * @param int $countPost
  2636. * @param array $htmlHeadXtra
  2637. */
  2638. public static function getScrollJs($countPost, &$htmlHeadXtra)
  2639. {
  2640. // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
  2641. $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
  2642. $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
  2643. $locale = api_get_language_isocode();
  2644. // Add Jquery scroll pagination plugin
  2645. $htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
  2646. // Add Jquery Time ago plugin
  2647. $htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
  2648. $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
  2649. if (file_exists($timeAgoLocaleDir)) {
  2650. $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
  2651. }
  2652. if ($countPost > self::DEFAULT_WALL_POSTS) {
  2653. $htmlHeadXtra[] = '<script>
  2654. $(function() {
  2655. var container = $("#wallMessages");
  2656. container.jscroll({
  2657. loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
  2658. nextSelector: "a.nextPage:last",
  2659. contentSelector: "",
  2660. callback: timeAgo
  2661. });
  2662. });
  2663. </script>';
  2664. }
  2665. $htmlHeadXtra[] = '<script>
  2666. function deleteMessage(id)
  2667. {
  2668. $.ajax({
  2669. url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
  2670. success: function (result) {
  2671. if (result) {
  2672. $("#message_" + id).parent().parent().parent().parent().html(result);
  2673. }
  2674. }
  2675. });
  2676. }
  2677. function deleteComment(id)
  2678. {
  2679. $.ajax({
  2680. url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
  2681. success: function (result) {
  2682. if (result) {
  2683. $("#message_" + id).parent().parent().parent().html(result);
  2684. }
  2685. }
  2686. });
  2687. }
  2688. function submitComment(messageId)
  2689. {
  2690. var data = $("#form_comment_"+messageId).serializeArray();
  2691. $.ajax({
  2692. type : "POST",
  2693. url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
  2694. data: data,
  2695. success: function (result) {
  2696. if (result) {
  2697. $("#post_" + messageId + " textarea").val("");
  2698. $("#post_" + messageId + " .sub-mediapost").prepend(result);
  2699. $("#post_" + messageId + " .sub-mediapost").append(
  2700. $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
  2701. );
  2702. $("#result_" + messageId + "").fadeIn("fast", function() {
  2703. $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
  2704. $(this).remove();
  2705. });
  2706. });
  2707. }
  2708. }
  2709. });
  2710. }
  2711. $(function() {
  2712. timeAgo();
  2713. /*$(".delete_message").on("click", function() {
  2714. var id = $(this).attr("id");
  2715. id = id.split("_")[1];
  2716. $.ajax({
  2717. url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
  2718. success: function (result) {
  2719. if (result) {
  2720. $("#message_" + id).parent().parent().parent().parent().html(result);
  2721. }
  2722. }
  2723. });
  2724. });
  2725. $(".delete_comment").on("click", function() {
  2726. var id = $(this).attr("id");
  2727. id = id.split("_")[1];
  2728. $.ajax({
  2729. url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
  2730. success: function (result) {
  2731. if (result) {
  2732. $("#message_" + id).parent().parent().parent().html(result);
  2733. }
  2734. }
  2735. });
  2736. });
  2737. */
  2738. });
  2739. function timeAgo() {
  2740. $(".timeago").timeago();
  2741. }
  2742. </script>';
  2743. }
  2744. /**
  2745. * @param int $userId
  2746. * @param int $countPost
  2747. *
  2748. * @return string
  2749. */
  2750. public static function getAutoExtendLink($userId, $countPost)
  2751. {
  2752. $userId = (int) $userId;
  2753. $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
  2754. $socialAutoExtendLink = '';
  2755. if ($countPost > self::DEFAULT_WALL_POSTS) {
  2756. $socialAutoExtendLink = Display::url(
  2757. get_lang('SeeMore'),
  2758. $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
  2759. self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
  2760. [
  2761. 'class' => 'nextPage next',
  2762. ]
  2763. );
  2764. }
  2765. return $socialAutoExtendLink;
  2766. }
  2767. /**
  2768. * @param int $userId
  2769. *
  2770. * @return array
  2771. */
  2772. public static function getThreadList($userId)
  2773. {
  2774. $forumCourseId = api_get_configuration_value('global_forums_course_id');
  2775. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  2776. $threads = [];
  2777. if (!empty($forumCourseId)) {
  2778. $courseInfo = api_get_course_info_by_id($forumCourseId);
  2779. getNotificationsPerUser($userId, true, $forumCourseId);
  2780. $notification = Session::read('forum_notification');
  2781. Session::erase('forum_notification');
  2782. $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
  2783. 'cidReq' => $courseInfo['code'],
  2784. ]).'&';
  2785. if (isset($notification['thread']) && !empty($notification['thread'])) {
  2786. $threadList = array_filter(array_unique($notification['thread']));
  2787. $em = Database::getManager();
  2788. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  2789. foreach ($threadList as $threadId) {
  2790. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  2791. $thread = $repo->find($threadId);
  2792. if ($thread) {
  2793. $threadUrl = $threadUrlBase.http_build_query([
  2794. 'forum' => $thread->getForumId(),
  2795. 'thread' => $thread->getIid(),
  2796. ]);
  2797. $threads[] = [
  2798. 'id' => $threadId,
  2799. 'url' => Display::url(
  2800. $thread->getThreadTitle(),
  2801. $threadUrl
  2802. ),
  2803. 'name' => Display::url(
  2804. $thread->getThreadTitle(),
  2805. $threadUrl
  2806. ),
  2807. 'description' => '',
  2808. ];
  2809. }
  2810. }
  2811. }
  2812. }
  2813. return $threads;
  2814. }
  2815. /**
  2816. * @param int $userId
  2817. *
  2818. * @return string
  2819. */
  2820. public static function getGroupBlock($userId)
  2821. {
  2822. $threadList = self::getThreadList($userId);
  2823. $userGroup = new UserGroup();
  2824. $forumCourseId = api_get_configuration_value('global_forums_course_id');
  2825. $courseInfo = null;
  2826. if (!empty($forumCourseId)) {
  2827. $courseInfo = api_get_course_info_by_id($forumCourseId);
  2828. }
  2829. $social_group_block = '';
  2830. if (!empty($courseInfo)) {
  2831. if (!empty($threadList)) {
  2832. $social_group_block .= '<div class="list-group">';
  2833. foreach ($threadList as $group) {
  2834. $social_group_block .= ' <li class="list-group-item">';
  2835. $social_group_block .= $group['name'];
  2836. $social_group_block .= '</li>';
  2837. }
  2838. $social_group_block .= '</div>';
  2839. }
  2840. $social_group_block .= Display::url(
  2841. get_lang('SeeAllCommunities'),
  2842. api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
  2843. );
  2844. if (!empty($social_group_block)) {
  2845. $social_group_block = Display::panelCollapse(
  2846. get_lang('MyCommunities'),
  2847. $social_group_block,
  2848. 'sm-groups',
  2849. null,
  2850. 'grups-acordion',
  2851. 'groups-collapse'
  2852. );
  2853. }
  2854. } else {
  2855. // Load my groups
  2856. $results = $userGroup->get_groups_by_user(
  2857. $userId,
  2858. [
  2859. GROUP_USER_PERMISSION_ADMIN,
  2860. GROUP_USER_PERMISSION_READER,
  2861. GROUP_USER_PERMISSION_MODERATOR,
  2862. GROUP_USER_PERMISSION_HRM,
  2863. ]
  2864. );
  2865. $myGroups = [];
  2866. if (!empty($results)) {
  2867. foreach ($results as $result) {
  2868. $id = $result['id'];
  2869. $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
  2870. $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
  2871. $group_url = "group_view.php?id=$id";
  2872. $link = Display::url(
  2873. api_ucwords(cut($result['name'], 40, true)),
  2874. $group_url
  2875. );
  2876. $result['name'] = $link;
  2877. $picture = $userGroup->get_picture_group(
  2878. $id,
  2879. $result['picture'],
  2880. null,
  2881. GROUP_IMAGE_SIZE_BIG
  2882. );
  2883. $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
  2884. $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
  2885. get_lang('SeeMore').'</a></div>';
  2886. $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
  2887. $myGroups[] = [
  2888. 'url' => Display::url(
  2889. $result['picture'],
  2890. $group_url
  2891. ),
  2892. 'name' => $result['name'],
  2893. 'description' => $group_info.$group_actions,
  2894. ];
  2895. }
  2896. $social_group_block .= '<div class="list-group">';
  2897. foreach ($myGroups as $group) {
  2898. $social_group_block .= ' <li class="list-group-item">';
  2899. $social_group_block .= $group['name'];
  2900. $social_group_block .= '</li>';
  2901. }
  2902. $social_group_block .= '</div>';
  2903. $form = new FormValidator(
  2904. 'find_groups_form',
  2905. 'get',
  2906. api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
  2907. null,
  2908. null,
  2909. FormValidator::LAYOUT_BOX_NO_LABEL
  2910. );
  2911. $form->addHidden('search_type', 2);
  2912. $form->addText(
  2913. 'q',
  2914. get_lang('Search'),
  2915. false,
  2916. [
  2917. 'aria-label' => get_lang('Search'),
  2918. 'custom' => true,
  2919. 'placeholder' => get_lang('Search'),
  2920. ]
  2921. );
  2922. $social_group_block .= $form->returnForm();
  2923. if (!empty($social_group_block)) {
  2924. $social_group_block = Display::panelCollapse(
  2925. get_lang('MyGroups'),
  2926. $social_group_block,
  2927. 'sm-groups',
  2928. null,
  2929. 'grups-acordion',
  2930. 'groups-collapse'
  2931. );
  2932. }
  2933. }
  2934. }
  2935. return $social_group_block;
  2936. }
  2937. /**
  2938. * Returns the formatted header message post.
  2939. *
  2940. * @param int $authorInfo
  2941. * @param int $receiverInfo
  2942. * @param array $message Message data
  2943. *
  2944. * @return string $html The formatted header message post
  2945. */
  2946. private static function headerMessagePost($authorInfo, $receiverInfo, $message)
  2947. {
  2948. $currentUserId = api_get_user_id();
  2949. $authorId = (int) $authorInfo['user_id'];
  2950. $receiverId = (int) $receiverInfo['user_id'];
  2951. $iconStatus = $authorInfo['icon_status'];
  2952. $date = Display::dateToStringAgoAndLongDate($message['send_date']);
  2953. $avatarAuthor = $authorInfo['avatar'];
  2954. $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
  2955. $nameCompleteAuthor = $authorInfo['complete_name'];
  2956. $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
  2957. $nameCompleteReceiver = $receiverInfo['complete_name'];
  2958. $htmlReceiver = '';
  2959. if ($authorId !== $receiverId) {
  2960. $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
  2961. }
  2962. if (!empty($message['group_info'])) {
  2963. $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
  2964. }
  2965. $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
  2966. if (!empty($message['thread_id'])) {
  2967. $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
  2968. $canEdit = false;
  2969. }
  2970. $postAttachment = self::getPostAttachment($message);
  2971. $html = '<div class="top-mediapost" >';
  2972. $html .= '<div class="pull-right btn-group btn-group-sm">';
  2973. $html .= MessageManager::getLikesButton(
  2974. $message['id'],
  2975. $currentUserId,
  2976. !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
  2977. );
  2978. if ($canEdit) {
  2979. $htmlDelete = Display::url(
  2980. Display::returnFontAwesomeIcon('trash', '', true),
  2981. 'javascript:void(0)',
  2982. [
  2983. 'id' => 'message_'.$message['id'],
  2984. 'title' => get_lang('SocialMessageDelete'),
  2985. 'onclick' => 'deleteMessage('.$message['id'].')',
  2986. 'class' => 'btn btn-default',
  2987. ]
  2988. );
  2989. $html .= $htmlDelete;
  2990. }
  2991. $html .= '</div>';
  2992. $html .= '<div class="user-image" >';
  2993. $html .= '<a href="'.$urlAuthor.'">
  2994. <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
  2995. $html .= '</div>';
  2996. $html .= '<div class="user-data">';
  2997. $html .= $iconStatus;
  2998. $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
  2999. $html .= '<div class="post-date">'.$date.'</div>';
  3000. $html .= '</div>';
  3001. $html .= '<div class="msg-content">';
  3002. if (!empty($postAttachment)) {
  3003. $html .= '<div class="post-attachment thumbnail">';
  3004. $html .= $postAttachment;
  3005. $html .= '</div>';
  3006. }
  3007. $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
  3008. $html .= '</div>';
  3009. $html .= '</div>'; // end mediaPost
  3010. // Popularity post functionality
  3011. $html .= '<div class="popularity-mediapost"></div>';
  3012. return $html;
  3013. }
  3014. }