social.lib.php 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269
  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('The message has been sent to');
  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('There was an error while trying to send the message.'), '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('The invitation has been sent')),
  598. 'normal',
  599. false
  600. )
  601. );
  602. } else {
  603. Display::addFlash(
  604. Display::return_message(
  605. api_htmlentities(get_lang('You already sent an invitation')),
  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('(the course is currently closed)');
  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('Without time limits');
  681. if (api_get_setting('show_session_coach') === 'true') {
  682. $session['coach'] = get_lang('General coach').': '.
  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('General coach').': '.
  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('My files'), 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('Social groups'), 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('My shared profile'));
  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('Personal data'));
  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('My shared profile').'
  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('Social groups').'
  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('My files').'
  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('Personal data').'
  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('Social network'),
  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('My shared profile').'
  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('Social groups').'
  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('My files').'
  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('Personal data').'
  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('Send message');
  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('You already sent an invitation'))
  1087. .'&nbsp;&nbsp;'.get_lang('You already sent an invitation').'</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('Send invitation').'">'.
  1092. Display::return_icon('invitation.png', get_lang('Invite to join my group of friends')).'&nbsp;'.get_lang('Send invitation').
  1093. '</a></li>';
  1094. }
  1095. }
  1096. $links .= '</ul>';
  1097. $html .= Display::panelCollapse(
  1098. get_lang('Social network'),
  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('Trainer'), null, ICON_SIZE_TINY) : Display::return_icon('user.png', get_lang('Learner'), 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('Code').'">'.$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('Online users list')];
  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('My competences'));
  1253. $html .= '<p>'.$user_object->competences.'</p>';
  1254. }
  1255. if ($user_object->diplomas) {
  1256. $html .= Display::page_subheader(get_lang('My diplomas'));
  1257. $html .= '<p>'.$user_object->diplomas.'</p>';
  1258. }
  1259. if ($user_object->teach) {
  1260. $html .= Display::page_subheader(get_lang('What I am able to teach'));
  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('My personal open area'));
  1266. $html .= '<p>'.$user_object->openarea.'</p>';
  1267. }
  1268. } else {
  1269. $html .= '<div class="actions-title">';
  1270. $html .= get_lang('Online users list');
  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('Write new comment').'</label>
  1650. <input type="hidden" name = "messageId" value="'.$messageId.'" />
  1651. <textarea rows="3" class="form-control" placeholder="'.get_lang('Write new comment').'" 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('Delete comment'),
  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('No friends in your contact list'), '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('Write something on your friend\'s wall') : get_lang(
  2112. 'Social wallWhatAreYouThinkingAbout'
  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('File upload'), ['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('Social wall'));
  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('Extra information'),
  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('Message Sent')));
  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('See more'),
  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('See all communities'),
  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('My communities'),
  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('See more').'</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('My groups'),
  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('Delete comment'),
  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. }