social.lib.php 124 KB

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