social.lib.php 121 KB

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