display.lib.php 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField;
  4. use Chamilo\CoreBundle\Framework\Container;
  5. use ChamiloSession as Session;
  6. use Symfony\Component\HttpFoundation\Response;
  7. /**
  8. * Class Display
  9. * Contains several public functions dealing with the display of
  10. * table data, messages, help topics, ...
  11. *
  12. * Include/require it in your code to use its public functionality.
  13. * There are also several display public functions in the main api library.
  14. *
  15. * All public functions static public functions inside a class called Display,
  16. * so you use them like this: e.g.
  17. * Display::return_message($message)
  18. *
  19. * @package chamilo.library
  20. */
  21. class Display
  22. {
  23. /** @var Template */
  24. public static $global_template;
  25. public static $preview_style = null;
  26. /**
  27. * Constructor.
  28. */
  29. public function __construct()
  30. {
  31. }
  32. /**
  33. * @return array
  34. */
  35. public static function toolList()
  36. {
  37. return [
  38. 'group',
  39. 'work',
  40. 'glossary',
  41. 'forum',
  42. 'course_description',
  43. 'gradebook',
  44. 'attendance',
  45. 'course_progress',
  46. 'notebook',
  47. ];
  48. }
  49. /**
  50. * Displays the page header.
  51. *
  52. * @param string The name of the page (will be showed in the page title)
  53. * @param string Optional help file name
  54. * @param string $page_header
  55. */
  56. public static function display_header(
  57. $tool_name = '',
  58. $help = null,
  59. $page_header = null
  60. ) {
  61. ob_start();
  62. return true;
  63. $origin = api_get_origin();
  64. $showHeader = true;
  65. if (isset($origin) && $origin == 'learnpath') {
  66. $showHeader = false;
  67. }
  68. self::$global_template = new Template($tool_name, $showHeader, $showHeader);
  69. // Fixing tools with any help it takes xxx part of main/xxx/index.php
  70. if (empty($help)) {
  71. $currentURL = api_get_self();
  72. preg_match('/main\/([^*\/]+)/', $currentURL, $matches);
  73. $toolList = self::toolList();
  74. if (!empty($matches)) {
  75. foreach ($matches as $match) {
  76. if (in_array($match, $toolList)) {
  77. $help = explode('_', $match);
  78. $help = array_map('ucfirst', $help);
  79. $help = implode('', $help);
  80. break;
  81. }
  82. }
  83. }
  84. }
  85. self::$global_template->setHelp($help);
  86. if (!empty(self::$preview_style)) {
  87. self::$global_template->preview_theme = self::$preview_style;
  88. self::$global_template->set_system_parameters();
  89. self::$global_template->setCssFiles();
  90. self::$global_template->set_js_files();
  91. self::$global_template->setCssCustomFiles();
  92. }
  93. if (!empty($page_header)) {
  94. self::$global_template->assign('header', $page_header);
  95. }
  96. echo self::$global_template->show_header_template();
  97. }
  98. /**
  99. * Displays the reduced page header (without banner).
  100. */
  101. public static function display_reduced_header()
  102. {
  103. global $show_learnpath, $tool_name;
  104. self::$global_template = new Template(
  105. $tool_name,
  106. false,
  107. false,
  108. $show_learnpath
  109. );
  110. echo self::$global_template->show_header_template();
  111. }
  112. /**
  113. * Display no header.
  114. */
  115. public static function display_no_header()
  116. {
  117. global $tool_name, $show_learnpath;
  118. $disable_js_and_css_files = true;
  119. self::$global_template = new Template(
  120. $tool_name,
  121. false,
  122. false,
  123. $show_learnpath
  124. );
  125. }
  126. /**
  127. * Display the page footer.
  128. */
  129. public static function display_footer()
  130. {
  131. $contents = ob_get_contents();
  132. ob_end_clean();
  133. $tpl = '@ChamiloTheme/Layout/layout_one_col.html.twig';
  134. $response = new Response();
  135. $params['content'] = $contents;
  136. global $interbreadcrumb, $htmlHeadXtra;
  137. $params['legacy_javascript'] = $htmlHeadXtra;
  138. $params['legacy_breadcrumb'] = $interbreadcrumb;
  139. $flash = Display::getFlashToString();
  140. Display::cleanFlashMessages();
  141. $params['flash_messages'] = $flash;
  142. $content = Container::getTemplating()->render($tpl, $params);
  143. $response->setContent($content);
  144. $response->send();
  145. exit;
  146. }
  147. /**
  148. * Display the page footer.
  149. */
  150. public static function display_reduced_footer()
  151. {
  152. echo self::$global_template->show_footer_js_template();
  153. echo '</body></html>';
  154. }
  155. /**
  156. * Displays the tool introduction of a tool.
  157. *
  158. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  159. *
  160. * @param string $tool these are the constants that are used for indicating the tools
  161. * @param array $editor_config Optional configuration settings for the online editor.
  162. * return: $tool return a string array list with the "define" in main_api.lib
  163. *
  164. * @return string html code for adding an introduction
  165. */
  166. public static function display_introduction_section(
  167. $tool,
  168. $editor_config = null
  169. ) {
  170. echo self::return_introduction_section($tool, $editor_config);
  171. }
  172. /**
  173. * @param string $tool
  174. * @param array $editor_config
  175. */
  176. public static function return_introduction_section(
  177. $tool,
  178. $editor_config = null
  179. ) {
  180. $moduleId = $tool;
  181. if (api_get_setting('enable_tool_introduction') == 'true' || $tool == TOOL_COURSE_HOMEPAGE) {
  182. $introduction_section = null;
  183. require api_get_path(SYS_INC_PATH).'introductionSection.inc.php';
  184. return $introduction_section;
  185. }
  186. }
  187. /**
  188. * Displays a table.
  189. *
  190. * @param array $header Titles for the table header
  191. * each item in this array can contain 3 values
  192. * - 1st element: the column title
  193. * - 2nd element: true or false (column sortable?)
  194. * - 3th element: additional attributes for
  195. * th-tag (eg for column-width)
  196. * - 4the element: additional attributes for the td-tags
  197. * @param array $content 2D-array with the tables content
  198. * @param array $sorting_options Keys are:
  199. * 'column' = The column to use as sort-key
  200. * 'direction' = SORT_ASC or SORT_DESC
  201. * @param array $paging_options Keys are:
  202. * 'per_page_default' = items per page when switching from
  203. * full- list to per-page-view
  204. * 'per_page' = number of items to show per page
  205. * 'page_nr' = The page to display
  206. * @param array $query_vars Additional variables to add in the query-string
  207. * @param string The style that the table will show. You can set 'table' or 'grid'
  208. *
  209. * @author bart.mollet@hogent.be
  210. */
  211. public static function display_sortable_table(
  212. $header,
  213. $content,
  214. $sorting_options = [],
  215. $paging_options = [],
  216. $query_vars = null,
  217. $form_actions = [],
  218. $style = 'table'
  219. ) {
  220. $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
  221. $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
  222. $table = new SortableTableFromArray($content, $column, $default_items_per_page);
  223. if (is_array($query_vars)) {
  224. $table->set_additional_parameters($query_vars);
  225. }
  226. if ($style == 'table') {
  227. if (is_array($header) && count($header) > 0) {
  228. foreach ($header as $index => $header_item) {
  229. $table->set_header(
  230. $index,
  231. isset($header_item[0]) ? $header_item[0] : null,
  232. isset($header_item[1]) ? $header_item[1] : null,
  233. isset($header_item[2]) ? $header_item[2] : null,
  234. isset($header_item[3]) ? $header_item[3] : null
  235. );
  236. }
  237. }
  238. $table->set_form_actions($form_actions);
  239. $table->display();
  240. } else {
  241. $table->display_grid();
  242. }
  243. }
  244. /**
  245. * Returns an HTML table with sortable column (through complete page refresh).
  246. *
  247. * @param array $header
  248. * @param array $content Array of row arrays
  249. * @param array $sorting_options
  250. * @param array $paging_options
  251. * @param array $query_vars
  252. * @param array $form_actions
  253. * @param string $style
  254. *
  255. * @return string HTML string for array
  256. */
  257. public static function return_sortable_table(
  258. $header,
  259. $content,
  260. $sorting_options = [],
  261. $paging_options = [],
  262. $query_vars = null,
  263. $form_actions = [],
  264. $style = 'table'
  265. ) {
  266. ob_start();
  267. self::display_sortable_table(
  268. $header,
  269. $content,
  270. $sorting_options,
  271. $paging_options,
  272. $query_vars,
  273. $form_actions,
  274. $style
  275. );
  276. $content = ob_get_contents();
  277. ob_end_clean();
  278. return $content;
  279. }
  280. /**
  281. * Shows a nice grid.
  282. *
  283. * @param string grid name (important to create css)
  284. * @param array header content
  285. * @param array array with the information to show
  286. * @param array $paging_options Keys are:
  287. * 'per_page_default' = items per page when switching from
  288. * full- list to per-page-view
  289. * 'per_page' = number of items to show per page
  290. * 'page_nr' = The page to display
  291. * 'hide_navigation' = true to hide the navigation
  292. * @param array $query_vars Additional variables to add in the query-string
  293. * @param array $form actions Additional variables to add in the query-string
  294. * @param mixed An array with bool values to know which columns show.
  295. * i.e: $visibility_options= array(true, false) we will only show the first column
  296. * Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
  297. */
  298. public static function display_sortable_grid(
  299. $name,
  300. $header,
  301. $content,
  302. $paging_options = [],
  303. $query_vars = null,
  304. $form_actions = [],
  305. $visibility_options = true,
  306. $sort_data = true,
  307. $grid_class = []
  308. ) {
  309. echo self::return_sortable_grid(
  310. $name,
  311. $header,
  312. $content,
  313. $paging_options,
  314. $query_vars,
  315. $form_actions,
  316. $visibility_options,
  317. $sort_data,
  318. $grid_class
  319. );
  320. }
  321. /**
  322. * Gets a nice grid in html string.
  323. *
  324. * @param string grid name (important to create css)
  325. * @param array header content
  326. * @param array array with the information to show
  327. * @param array $paging_options Keys are:
  328. * 'per_page_default' = items per page when switching from
  329. * full- list to per-page-view
  330. * 'per_page' = number of items to show per page
  331. * 'page_nr' = The page to display
  332. * 'hide_navigation' = true to hide the navigation
  333. * @param array $query_vars Additional variables to add in the query-string
  334. * @param array $form actions Additional variables to add in the query-string
  335. * @param mixed An array with bool values to know which columns show. i.e:
  336. * $visibility_options= array(true, false) we will only show the first column
  337. * Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
  338. * @param bool true for sorting data or false otherwise
  339. * @param array grid classes
  340. *
  341. * @return string html grid
  342. */
  343. public static function return_sortable_grid(
  344. $name,
  345. $header,
  346. $content,
  347. $paging_options = [],
  348. $query_vars = null,
  349. $form_actions = [],
  350. $visibility_options = true,
  351. $sort_data = true,
  352. $grid_class = [],
  353. $elementCount = 0
  354. ) {
  355. $column = 0;
  356. $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
  357. $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
  358. $table->total_number_of_items = intval($elementCount);
  359. if (is_array($query_vars)) {
  360. $table->set_additional_parameters($query_vars);
  361. }
  362. return $table->display_simple_grid(
  363. $visibility_options,
  364. $paging_options['hide_navigation'],
  365. $default_items_per_page,
  366. $sort_data,
  367. $grid_class
  368. );
  369. }
  370. /**
  371. * Displays a table with a special configuration.
  372. *
  373. * @param array $header Titles for the table header
  374. * each item in this array can contain 3 values
  375. * - 1st element: the column title
  376. * - 2nd element: true or false (column sortable?)
  377. * - 3th element: additional attributes for th-tag (eg for column-width)
  378. * - 4the element: additional attributes for the td-tags
  379. * @param array $content 2D-array with the tables content
  380. * @param array $sorting_options Keys are:
  381. * 'column' = The column to use as sort-key
  382. * 'direction' = SORT_ASC or SORT_DESC
  383. * @param array $paging_options Keys are:
  384. * 'per_page_default' = items per page when switching from full list to per-page-view
  385. * 'per_page' = number of items to show per page
  386. * 'page_nr' = The page to display
  387. * @param array $query_vars Additional variables to add in the query-string
  388. * @param array $column_show Array of binaries 1= show columns 0. hide a column
  389. * @param array $column_order An array of integers that let us decide how the columns are going to be sort.
  390. * i.e: $column_order=array('1''4','3','4'); The 2nd column will be order like the
  391. * 4th column
  392. * @param array $form_actions Set optional forms actions
  393. *
  394. * @author Julio Montoya
  395. */
  396. public static function display_sortable_config_table(
  397. $table_name,
  398. $header,
  399. $content,
  400. $sorting_options = [],
  401. $paging_options = [],
  402. $query_vars = null,
  403. $column_show = [],
  404. $column_order = [],
  405. $form_actions = []
  406. ) {
  407. $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
  408. $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
  409. $table = new SortableTableFromArrayConfig(
  410. $content,
  411. $column,
  412. $default_items_per_page,
  413. $table_name,
  414. $column_show,
  415. $column_order
  416. );
  417. if (is_array($query_vars)) {
  418. $table->set_additional_parameters($query_vars);
  419. }
  420. // Show or hide the columns header
  421. if (is_array($column_show)) {
  422. for ($i = 0; $i < count($column_show); $i++) {
  423. if (!empty($column_show[$i])) {
  424. $val0 = isset($header[$i][0]) ? $header[$i][0] : null;
  425. $val1 = isset($header[$i][1]) ? $header[$i][1] : null;
  426. $val2 = isset($header[$i][2]) ? $header[$i][2] : null;
  427. $val3 = isset($header[$i][3]) ? $header[$i][3] : null;
  428. $table->set_header($i, $val0, $val1, $val2, $val3);
  429. }
  430. }
  431. }
  432. $table->set_form_actions($form_actions);
  433. $table->display();
  434. }
  435. /**
  436. * Displays a normal message. It is recommended to use this public function
  437. * to display any normal information messages.
  438. *
  439. * @param string $message
  440. * @param bool $filter (true) or not (false)
  441. * @param bool $returnValue
  442. *
  443. * @deprecated Use <code>Display::addFlash(Display::return_message($message, 'normal'));</code>
  444. * Or <code>echo Display::return_message($message, 'normal')</code>
  445. */
  446. public static function display_normal_message(
  447. $message,
  448. $filter = true,
  449. $returnValue = false
  450. ) {
  451. $message = self::return_message($message, 'normal', $filter);
  452. if ($returnValue) {
  453. return $message;
  454. } else {
  455. echo $message;
  456. }
  457. }
  458. /**
  459. * Displays an warning message. Use this if you want to draw attention to something
  460. * This can also be used for instance with the hint in the exercises.
  461. *
  462. * @deprecated use Display::addFlash(Display::return_message($message, 'warning'));
  463. */
  464. public static function display_warning_message(
  465. $message,
  466. $filter = true,
  467. $returnValue = false
  468. ) {
  469. $message = self::return_message($message, 'warning', $filter);
  470. if ($returnValue) {
  471. return $message;
  472. } else {
  473. echo $message;
  474. }
  475. }
  476. /**
  477. * Displays an confirmation message. Use this if something has been done successfully.
  478. *
  479. * @param bool Filter (true) or not (false)
  480. *
  481. * @deprecated use Display::addFlash(Display::return_message($message, 'confirm'));
  482. */
  483. public static function display_confirmation_message(
  484. $message,
  485. $filter = true,
  486. $returnValue = false
  487. ) {
  488. $message = self::return_message($message, 'confirm', $filter);
  489. if ($returnValue) {
  490. return $message;
  491. } else {
  492. echo $message;
  493. }
  494. }
  495. /**
  496. * Displays an error message. It is recommended to use this public function if an error occurs.
  497. *
  498. * @param string $message - include any additional html
  499. * tags if you need them
  500. * @param bool Filter (true) or not (false)
  501. *
  502. * @deprecated use Display::addFlash(Display::return_message($message, 'error'));
  503. */
  504. public static function display_error_message(
  505. $message,
  506. $filter = true,
  507. $returnValue = false
  508. ) {
  509. $message = self::return_message($message, 'error', $filter);
  510. if ($returnValue) {
  511. return $message;
  512. } else {
  513. echo $message;
  514. }
  515. }
  516. /**
  517. * @param string $message
  518. * @param string $type
  519. * @param bool $filter
  520. */
  521. public static function return_message_and_translate(
  522. $message,
  523. $type = 'normal',
  524. $filter = true
  525. ) {
  526. $message = get_lang($message);
  527. echo self::return_message($message, $type, $filter);
  528. }
  529. /**
  530. * Returns a div html string with.
  531. *
  532. * @param string $message
  533. * @param string $type Example: confirm, normal, warning, error
  534. * @param bool $filter Whether to XSS-filter or not
  535. *
  536. * @return string Message wrapped into an HTML div
  537. */
  538. public static function return_message(
  539. $message,
  540. $type = 'normal',
  541. $filter = true
  542. ) {
  543. if (empty($message)) {
  544. return '';
  545. }
  546. if ($filter) {
  547. $message = api_htmlentities(
  548. $message,
  549. ENT_QUOTES,
  550. api_is_xml_http_request() ? 'UTF-8' : api_get_system_encoding()
  551. );
  552. }
  553. $class = '';
  554. switch ($type) {
  555. case 'warning':
  556. $class .= 'alert alert-warning';
  557. break;
  558. case 'error':
  559. $class .= 'alert alert-danger';
  560. break;
  561. case 'confirmation':
  562. case 'confirm':
  563. case 'success':
  564. $class .= 'alert alert-success';
  565. break;
  566. case 'normal':
  567. default:
  568. $class .= 'alert alert-info';
  569. }
  570. return self::div($message, ['class' => $class]);
  571. }
  572. /**
  573. * Returns an encrypted mailto hyperlink.
  574. *
  575. * @param string e-mail
  576. * @param string clickable text
  577. * @param string optional, class from stylesheet
  578. *
  579. * @return string encrypted mailto hyperlink
  580. */
  581. public static function encrypted_mailto_link(
  582. $email,
  583. $clickable_text = null,
  584. $style_class = ''
  585. ) {
  586. if (is_null($clickable_text)) {
  587. $clickable_text = $email;
  588. }
  589. // "mailto:" already present?
  590. if (substr($email, 0, 7) != 'mailto:') {
  591. $email = 'mailto:'.$email;
  592. }
  593. // Class (stylesheet) defined?
  594. if ($style_class != '') {
  595. $style_class = ' class="'.$style_class.'"';
  596. }
  597. // Encrypt email
  598. $hmail = '';
  599. for ($i = 0; $i < strlen($email); $i++) {
  600. $hmail .= '&#'.ord($email[
  601. $i]).';';
  602. }
  603. $hclickable_text = null;
  604. // Encrypt clickable text if @ is present
  605. if (strpos($clickable_text, '@')) {
  606. for ($i = 0; $i < strlen($clickable_text); $i++) {
  607. $hclickable_text .= '&#'.ord($clickable_text[
  608. $i]).';';
  609. }
  610. } else {
  611. $hclickable_text = @htmlspecialchars(
  612. $clickable_text,
  613. ENT_QUOTES,
  614. api_get_system_encoding()
  615. );
  616. }
  617. // Return encrypted mailto hyperlink
  618. return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$hclickable_text.'</a>';
  619. }
  620. /**
  621. * Returns an mailto icon hyperlink.
  622. *
  623. * @param string e-mail
  624. * @param string icon source file from the icon lib
  625. * @param int icon size from icon lib
  626. * @param string optional, class from stylesheet
  627. *
  628. * @return string encrypted mailto hyperlink
  629. */
  630. public static function icon_mailto_link(
  631. $email,
  632. $icon_file = "mail.png",
  633. $icon_size = 22,
  634. $style_class = ''
  635. ) {
  636. // "mailto:" already present?
  637. if (substr($email, 0, 7) != 'mailto:') {
  638. $email = 'mailto:'.$email;
  639. }
  640. // Class (stylesheet) defined?
  641. if ($style_class != '') {
  642. $style_class = ' class="'.$style_class.'"';
  643. }
  644. // Encrypt email
  645. $hmail = '';
  646. for ($i = 0; $i < strlen($email); $i++) {
  647. $hmail .= '&#'.ord($email[
  648. $i]).';';
  649. }
  650. // icon html code
  651. $icon_html_source = self::return_icon(
  652. $icon_file,
  653. $hmail,
  654. '',
  655. $icon_size
  656. );
  657. // Return encrypted mailto hyperlink
  658. return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$icon_html_source.'</a>';
  659. }
  660. /**
  661. * Prints an <option>-list with all letters (A-Z).
  662. *
  663. * @param string $selected_letter The letter that should be selected
  664. *
  665. * @todo This is English language specific implementation.
  666. * It should be adapted for the other languages.
  667. *
  668. * @return string
  669. */
  670. public static function get_alphabet_options($selectedLetter = '')
  671. {
  672. $result = '';
  673. for ($i = 65; $i <= 90; $i++) {
  674. $letter = chr($i);
  675. $result .= '<option value="'.$letter.'"';
  676. if ($selectedLetter == $letter) {
  677. $result .= ' selected="selected"';
  678. }
  679. $result .= '>'.$letter.'</option>';
  680. }
  681. return $result;
  682. }
  683. /**
  684. * Get the options withing a select box within the given values.
  685. *
  686. * @param int Min value
  687. * @param int Max value
  688. * @param int Default value
  689. *
  690. * @return string HTML select options
  691. */
  692. public static function get_numeric_options($min, $max, $selected_num = 0)
  693. {
  694. $result = '';
  695. for ($i = $min; $i <= $max; $i++) {
  696. $result .= '<option value="'.$i.'"';
  697. if (is_int($selected_num)) {
  698. if ($selected_num == $i) {
  699. $result .= ' selected="selected"';
  700. }
  701. }
  702. $result .= '>'.$i.'</option>';
  703. }
  704. return $result;
  705. }
  706. /**
  707. * This public function displays an icon.
  708. *
  709. * @param string The filename of the file (in the main/img/ folder
  710. * @param string The alt text (probably a language variable)
  711. * @param array additional attributes (for instance height, width, onclick, ...)
  712. * @param int The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
  713. */
  714. public static function display_icon(
  715. $image,
  716. $alt_text = '',
  717. $additional_attributes = [],
  718. $size = null
  719. ) {
  720. echo self::return_icon($image, $alt_text, $additional_attributes, $size);
  721. }
  722. /**
  723. * Gets the path of an icon.
  724. *
  725. * @param string $icon
  726. * @param int $size
  727. *
  728. * @return string
  729. */
  730. public static function returnIconPath($icon, $size = ICON_SIZE_SMALL)
  731. {
  732. return self::return_icon($icon, null, null, $size, null, true, false);
  733. }
  734. /**
  735. * This public function returns the htmlcode for an icon.
  736. *
  737. * @param string The filename of the file (in the main/img/ folder
  738. * @param string The alt text (probably a language variable)
  739. * @param array Additional attributes (for instance height, width, onclick, ...)
  740. * @param int The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
  741. *
  742. * @return string An HTML string of the right <img> tag
  743. *
  744. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University 2006
  745. * @author Julio Montoya 2010 Function improved, adding image constants
  746. * @author Yannick Warnier 2011 Added size handler
  747. *
  748. * @version Feb 2011
  749. */
  750. public static function return_icon(
  751. $image,
  752. $alt_text = '',
  753. $additional_attributes = [],
  754. $size = ICON_SIZE_SMALL,
  755. $show_text = true,
  756. $return_only_path = false,
  757. $loadThemeIcon = true
  758. ) {
  759. $code_path = api_get_path(SYS_PUBLIC_PATH);
  760. $w_code_path = api_get_path(WEB_PUBLIC_PATH);
  761. // The following path is checked to see if the file exist. It's
  762. // important to use the public path (i.e. web/css/) rather than the
  763. // internal path (/app/Resource/public/css/) because the path used
  764. // in the end must be the public path
  765. $alternateCssPath = api_get_path(SYS_PUBLIC_PATH).'css/';
  766. $alternateWebCssPath = api_get_path(WEB_PUBLIC_PATH).'css/';
  767. // Avoid issues with illegal string offset for legacy calls to this
  768. // method with an empty string rather than null or an empty array
  769. if (empty($additional_attributes)) {
  770. $additional_attributes = [];
  771. }
  772. $image = trim($image);
  773. if (isset($size)) {
  774. $size = intval($size);
  775. } else {
  776. $size = ICON_SIZE_SMALL;
  777. }
  778. $size_extra = $size.'/';
  779. $icon = $w_code_path.'img/'.$image;
  780. $theme = 'themes/chamilo/icons/';
  781. if ($loadThemeIcon) {
  782. // @todo with chamilo 2 code
  783. $theme = 'themes/'.api_get_visual_theme().'/icons/';
  784. if (is_file($alternateCssPath.$theme.$image)) {
  785. $icon = $alternateWebCssPath.$theme.$image;
  786. }
  787. // Checking the theme icons folder example: app/Resources/public/css/themes/chamilo/icons/XXX
  788. if (is_file($alternateCssPath.$theme.$size_extra.$image)) {
  789. $icon = $alternateWebCssPath.$theme.$size_extra.$image;
  790. } elseif (is_file($code_path.'img/icons/'.$size_extra.$image)) {
  791. //Checking the main/img/icons/XXX/ folder
  792. $icon = $w_code_path.'img/icons/'.$size_extra.$image;
  793. }
  794. } else {
  795. if (is_file($code_path.'img/icons/'.$size_extra.$image)) {
  796. // Checking the main/img/icons/XXX/ folder
  797. $icon = $w_code_path.'img/icons/'.$size_extra.$image;
  798. }
  799. }
  800. // Special code to enable SVG - refs #7359 - Needs more work
  801. // The code below does something else to "test out" SVG: for each icon,
  802. // it checks if there is an SVG version. If so, it uses it.
  803. // When moving this to production, the return_icon() calls should
  804. // ask for the SVG version directly
  805. $svgIcons = api_get_setting('icons_mode_svg');
  806. if ($svgIcons == 'true' && $return_only_path == false) {
  807. $svgImage = substr($image, 0, -3).'svg';
  808. if (is_file($code_path.$theme.'svg/'.$svgImage)) {
  809. $icon = $w_code_path.$theme.'svg/'.$svgImage;
  810. } elseif (is_file($code_path.'img/icons/svg/'.$svgImage)) {
  811. $icon = $w_code_path.'img/icons/svg/'.$svgImage;
  812. }
  813. if (empty($additional_attributes['height'])) {
  814. $additional_attributes['height'] = $size;
  815. }
  816. if (empty($additional_attributes['width'])) {
  817. $additional_attributes['width'] = $size;
  818. }
  819. }
  820. $icon = api_get_cdn_path($icon);
  821. if ($return_only_path) {
  822. return $icon;
  823. }
  824. $img = self::img($icon, $alt_text, $additional_attributes);
  825. if (SHOW_TEXT_NEAR_ICONS == true && !empty($alt_text)) {
  826. if ($show_text) {
  827. $img = "$img $alt_text";
  828. }
  829. }
  830. return $img;
  831. }
  832. /**
  833. * Returns the htmlcode for an image.
  834. *
  835. * @param string $image_path the filename of the file (in the main/img/ folder
  836. * @param string $alt_text the alt text (probably a language variable)
  837. * @param array $additional_attributes (for instance height, width, onclick, ...)
  838. * @param bool $filterPath Optional. Whether filter the image path. Default is true
  839. *
  840. * @return string
  841. *
  842. * @author Julio Montoya 2010
  843. */
  844. public static function img(
  845. $image_path,
  846. $alt_text = '',
  847. $additional_attributes = null,
  848. $filterPath = true
  849. ) {
  850. if (empty($image_path)) {
  851. // For some reason, the call to img() happened without a proper
  852. // image. Log the error and return an empty string to avoid
  853. // breaking the HTML
  854. $trace = debug_backtrace();
  855. $caller = $trace[1];
  856. //error_log('No image provided in Display::img(). Caller info: '.print_r($caller, 1));
  857. return '';
  858. }
  859. // Sanitizing the parameter $image_path
  860. if ($filterPath) {
  861. $image_path = Security::filter_img_path($image_path);
  862. }
  863. // alt text = the image name if there is none provided (for XHTML compliance)
  864. if ($alt_text == '') {
  865. $alt_text = basename($image_path);
  866. }
  867. if (empty($additional_attributes)) {
  868. $additional_attributes = [];
  869. }
  870. $additional_attributes['src'] = $image_path;
  871. if (empty($additional_attributes['alt'])) {
  872. $additional_attributes['alt'] = $alt_text;
  873. }
  874. if (empty($additional_attributes['title'])) {
  875. $additional_attributes['title'] = $alt_text;
  876. }
  877. return self::tag('img', '', $additional_attributes);
  878. }
  879. /**
  880. * Returns the htmlcode for a tag (h3, h1, div, a, button), etc.
  881. *
  882. * @param string $tag the tag name
  883. * @param string $content the tag's content
  884. * @param array $additional_attributes (for instance height, width, onclick, ...)
  885. *
  886. * @return string
  887. *
  888. * @author Julio Montoya 2010
  889. */
  890. public static function tag($tag, $content, $additional_attributes = [])
  891. {
  892. $attribute_list = '';
  893. // Managing the additional attributes
  894. if (!empty($additional_attributes) && is_array($additional_attributes)) {
  895. $attribute_list = '';
  896. foreach ($additional_attributes as $key => &$value) {
  897. $attribute_list .= $key.'="'.$value.'" ';
  898. }
  899. }
  900. //some tags don't have this </XXX>
  901. if (in_array($tag, ['img', 'input', 'br'])) {
  902. $return_value = '<'.$tag.' '.$attribute_list.' />';
  903. } else {
  904. $return_value = '<'.$tag.' '.$attribute_list.' >'.$content.'</'.$tag.'>';
  905. }
  906. return $return_value;
  907. }
  908. /**
  909. * Creates a URL anchor.
  910. *
  911. * @param string $name
  912. * @param string $url
  913. * @param array $attributes
  914. *
  915. * @return string
  916. */
  917. public static function url($name, $url, $attributes = [])
  918. {
  919. if (!empty($url)) {
  920. $url = preg_replace('#&amp;#', '&', $url);
  921. $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  922. $attributes['href'] = $url;
  923. }
  924. return self::tag('a', $name, $attributes);
  925. }
  926. /**
  927. * Creates a div tag.
  928. *
  929. * @param string $content
  930. * @param array $attributes
  931. *
  932. * @return string
  933. */
  934. public static function div($content, $attributes = [])
  935. {
  936. return self::tag('div', $content, $attributes);
  937. }
  938. /**
  939. * Creates a span tag.
  940. */
  941. public static function span($content, $attributes = [])
  942. {
  943. return self::tag('span', $content, $attributes);
  944. }
  945. /**
  946. * Displays an HTML input tag.
  947. */
  948. public static function input($type, $name, $value, $attributes = [])
  949. {
  950. if (isset($type)) {
  951. $attributes['type'] = $type;
  952. }
  953. if (isset($name)) {
  954. $attributes['name'] = $name;
  955. }
  956. if (isset($value)) {
  957. $attributes['value'] = $value;
  958. }
  959. return self::tag('input', '', $attributes);
  960. }
  961. /**
  962. * @param $name
  963. * @param $value
  964. * @param array $attributes
  965. *
  966. * @return string
  967. */
  968. public static function button($name, $value, $attributes = [])
  969. {
  970. if (!empty($name)) {
  971. $attributes['name'] = $name;
  972. }
  973. return self::tag('button', $value, $attributes);
  974. }
  975. /**
  976. * Displays an HTML select tag.
  977. *
  978. * @param string $name
  979. * @param array $values
  980. * @param int $default
  981. * @param array $extra_attributes
  982. * @param bool $show_blank_item
  983. * @param null $blank_item_text
  984. *
  985. * @return string
  986. */
  987. public static function select(
  988. $name,
  989. $values,
  990. $default = -1,
  991. $extra_attributes = [],
  992. $show_blank_item = true,
  993. $blank_item_text = ''
  994. ) {
  995. $html = '';
  996. $extra = '';
  997. $default_id = 'id="'.$name.'" ';
  998. foreach ($extra_attributes as $key => $parameter) {
  999. if ($key == 'id') {
  1000. $default_id = '';
  1001. }
  1002. $extra .= $key.'="'.$parameter.'" ';
  1003. }
  1004. $html .= '<select name="'.$name.'" '.$default_id.' '.$extra.'>';
  1005. if ($show_blank_item) {
  1006. if (empty($blank_item_text)) {
  1007. $blank_item_text = get_lang('Select');
  1008. } else {
  1009. $blank_item_text = Security::remove_XSS($blank_item_text);
  1010. }
  1011. $html .= self::tag(
  1012. 'option',
  1013. '-- '.$blank_item_text.' --',
  1014. ['value' => '-1']
  1015. );
  1016. }
  1017. if ($values) {
  1018. foreach ($values as $key => $value) {
  1019. if (is_array($value) && isset($value['name'])) {
  1020. $value = $value['name'];
  1021. }
  1022. $html .= '<option value="'.$key.'"';
  1023. if (is_array($default)) {
  1024. foreach ($default as $item) {
  1025. if ($item == $key) {
  1026. $html .= ' selected="selected"';
  1027. break;
  1028. }
  1029. }
  1030. } else {
  1031. if ($default == $key) {
  1032. $html .= ' selected="selected"';
  1033. }
  1034. }
  1035. $html .= '>'.$value.'</option>';
  1036. }
  1037. }
  1038. $html .= '</select>';
  1039. return $html;
  1040. }
  1041. /**
  1042. * Creates a tab menu
  1043. * Requirements: declare the jquery, jquery-ui libraries + the jquery-ui.css
  1044. * in the $htmlHeadXtra variable before the display_header
  1045. * Add this script.
  1046. *
  1047. * @example
  1048. * <script>
  1049. </script>
  1050. * @param array $headers list of the tab titles
  1051. * @param array $items
  1052. * @param string $id id of the container of the tab in the example "tabs"
  1053. * @param array $attributes for the ul
  1054. * @param array $ul_attributes
  1055. *
  1056. * @return string
  1057. */
  1058. public static function tabs(
  1059. $headers,
  1060. $items,
  1061. $id = 'tabs',
  1062. $attributes = [],
  1063. $ul_attributes = []
  1064. ) {
  1065. if (empty($headers) || count($headers) == 0) {
  1066. return '';
  1067. }
  1068. $lis = '';
  1069. $i = 1;
  1070. foreach ($headers as $item) {
  1071. $active = '';
  1072. if ($i == 1) {
  1073. $active = ' active';
  1074. }
  1075. $item = self::tag(
  1076. 'a',
  1077. $item,
  1078. [
  1079. 'href' => '#'.$id.'-'.$i,
  1080. 'role' => 'tab',
  1081. 'data-toggle' => 'tab',
  1082. 'id' => $id.$i,
  1083. ]
  1084. );
  1085. $ul_attributes['role'] = 'presentation';
  1086. $ul_attributes['class'] = $active;
  1087. $lis .= self::tag('li', $item, $ul_attributes);
  1088. $i++;
  1089. }
  1090. $ul = self::tag(
  1091. 'ul',
  1092. $lis,
  1093. [
  1094. 'class' => 'nav nav-tabs tabs-margin',
  1095. 'role' => 'tablist',
  1096. 'id' => 'ul_'.$id,
  1097. ]
  1098. );
  1099. $i = 1;
  1100. $divs = '';
  1101. foreach ($items as $content) {
  1102. $active = '';
  1103. if ($i == 1) {
  1104. $active = ' active';
  1105. }
  1106. $divs .= self::tag(
  1107. 'div',
  1108. $content,
  1109. ['id' => $id.'-'.$i, 'class' => 'tab-pane '.$active, 'role' => 'tabpanel']
  1110. );
  1111. $i++;
  1112. }
  1113. $attributes['id'] = $id;
  1114. $attributes['role'] = 'tabpanel';
  1115. $attributes['class'] = 'tab-wrapper';
  1116. $main_div = self::tag(
  1117. 'div',
  1118. $ul.self::tag('div', $divs, ['class' => 'tab-content']),
  1119. $attributes
  1120. );
  1121. return $main_div;
  1122. }
  1123. /**
  1124. * @param $headers
  1125. * @param null $selected
  1126. *
  1127. * @return string
  1128. */
  1129. public static function tabsOnlyLink($headers, $selected = null)
  1130. {
  1131. $id = uniqid();
  1132. $i = 1;
  1133. $lis = null;
  1134. foreach ($headers as $item) {
  1135. $class = null;
  1136. if ($i == $selected) {
  1137. $class = 'active';
  1138. }
  1139. $item = self::tag(
  1140. 'a',
  1141. $item['content'],
  1142. ['id' => $id.'-'.$i, 'href' => $item['url']]
  1143. );
  1144. $lis .= self::tag('li', $item, ['class' => $class]);
  1145. $i++;
  1146. }
  1147. return self::tag(
  1148. 'ul',
  1149. $lis,
  1150. ['class' => 'nav nav-tabs tabs-margin']
  1151. );
  1152. }
  1153. /**
  1154. * In order to display a grid using jqgrid you have to:.
  1155. *
  1156. * @example
  1157. * After your Display::display_header function you have to add the nex javascript code:
  1158. * <script>
  1159. * echo Display::grid_js('my_grid_name', $url,$columns, $column_model, $extra_params,[]);
  1160. * // for more information of this function check the grid_js() function
  1161. * </script>
  1162. * //Then you have to call the grid_html
  1163. * echo Display::grid_html('my_grid_name');
  1164. * As you can see both function use the same "my_grid_name" this is very important otherwise nothing will work
  1165. *
  1166. * @param string the div id, this value must be the same with the first parameter of Display::grid_js()
  1167. *
  1168. * @return string html
  1169. */
  1170. public static function grid_html($div_id)
  1171. {
  1172. $table = self::tag('table', '', ['id' => $div_id]);
  1173. $table .= self::tag('div', '', ['id' => $div_id.'_pager']);
  1174. return $table;
  1175. }
  1176. /**
  1177. * @param string $label
  1178. * @param string $form_item
  1179. *
  1180. * @return string
  1181. */
  1182. public static function form_row($label, $form_item)
  1183. {
  1184. $label = self::span($label, ['class' => 'control-label']);
  1185. $form_item = self::div($form_item, ['class' => 'controls']);
  1186. return self::div($label.$form_item, ['class' => 'control-group']);
  1187. }
  1188. /**
  1189. * This is a wrapper to use the jqgrid in Chamilo.
  1190. * For the other jqgrid options visit http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
  1191. * This function need to be in the ready jquery function
  1192. * example --> $(function() { <?php echo Display::grid_js('grid' ...); ?> }
  1193. * In order to work this function needs the Display::grid_html function with the same div id.
  1194. *
  1195. * @param string $div_id div id
  1196. * @param string $url url where the jqgrid will ask for data (if datatype = json)
  1197. * @param array $column_names Visible columns (you should use get_lang).
  1198. * An array in which we place the names of the columns.
  1199. * This is the text that appears in the head of the grid (Header layer).
  1200. * Example: colname {name:'date', index:'date', width:120, align:'right'},
  1201. * @param array $column_model the column model : Array which describes the parameters of the columns.
  1202. * This is the most important part of the grid.
  1203. * For a full description of all valid values see colModel API. See the url above.
  1204. * @param array $extra_params extra parameters
  1205. * @param array $data data that will be loaded
  1206. * @param string $formatter A string that will be appended to the JSON returned
  1207. * @param bool $fixed_width not implemented yet
  1208. *
  1209. * @return string the js code
  1210. */
  1211. public static function grid_js(
  1212. $div_id,
  1213. $url,
  1214. $column_names,
  1215. $column_model,
  1216. $extra_params,
  1217. $data = [],
  1218. $formatter = '',
  1219. $fixed_width = false
  1220. ) {
  1221. $obj = new stdClass();
  1222. $obj->first = 'first';
  1223. if (!empty($url)) {
  1224. $obj->url = $url;
  1225. }
  1226. //This line should only be used/modified in case of having characters
  1227. // encoding problems - see #6159
  1228. //$column_names = array_map("utf8_encode", $column_names);
  1229. $obj->colNames = $column_names;
  1230. $obj->colModel = $column_model;
  1231. $obj->pager = '#'.$div_id.'_pager';
  1232. $obj->datatype = 'json';
  1233. $obj->viewrecords = 'true';
  1234. $all_value = 10000000;
  1235. // Default row quantity
  1236. if (!isset($extra_params['rowList'])) {
  1237. $extra_params['rowList'] = [20, 50, 100, 500, 1000, $all_value];
  1238. }
  1239. $json = '';
  1240. if (!empty($extra_params['datatype'])) {
  1241. $obj->datatype = $extra_params['datatype'];
  1242. }
  1243. // Row even odd style.
  1244. $obj->altRows = true;
  1245. if (!empty($extra_params['altRows'])) {
  1246. $obj->altRows = $extra_params['altRows'];
  1247. }
  1248. if (!empty($extra_params['sortname'])) {
  1249. $obj->sortname = $extra_params['sortname'];
  1250. }
  1251. if (!empty($extra_params['sortorder'])) {
  1252. $obj->sortorder = $extra_params['sortorder'];
  1253. }
  1254. if (!empty($extra_params['rowList'])) {
  1255. $obj->rowList = $extra_params['rowList'];
  1256. }
  1257. // Sets how many records we want to view in the grid
  1258. $obj->rowNum = 20;
  1259. if (!empty($extra_params['rowNum'])) {
  1260. $obj->rowNum = $extra_params['rowNum'];
  1261. } else {
  1262. // Try to load max rows from Session
  1263. $urlInfo = parse_url($url);
  1264. if (isset($urlInfo['query'])) {
  1265. parse_str($urlInfo['query'], $query);
  1266. if (isset($query['a'])) {
  1267. $action = $query['a'];
  1268. // This value is set in model.ajax.php
  1269. $savedRows = Session::read('max_rows_'.$action);
  1270. if (!empty($savedRows)) {
  1271. $obj->rowNum = $savedRows;
  1272. }
  1273. }
  1274. }
  1275. }
  1276. if (!empty($extra_params['viewrecords'])) {
  1277. $obj->viewrecords = $extra_params['viewrecords'];
  1278. }
  1279. $beforeSelectRow = null;
  1280. if (isset($extra_params['beforeSelectRow'])) {
  1281. $beforeSelectRow = "beforeSelectRow: ".$extra_params['beforeSelectRow'].", ";
  1282. unset($extra_params['beforeSelectRow']);
  1283. }
  1284. // Adding extra params
  1285. if (!empty($extra_params)) {
  1286. foreach ($extra_params as $key => $element) {
  1287. // the groupHeaders key gets a special treatment
  1288. if ($key != 'groupHeaders') {
  1289. $obj->$key = $element;
  1290. }
  1291. }
  1292. }
  1293. // Adding static data.
  1294. if (!empty($data)) {
  1295. $data_var = $div_id.'_data';
  1296. $json .= ' var '.$data_var.' = '.json_encode($data).';';
  1297. $obj->data = $data_var;
  1298. $obj->datatype = 'local';
  1299. $json .= "\n";
  1300. }
  1301. $obj->end = 'end';
  1302. $json_encode = json_encode($obj);
  1303. if (!empty($data)) {
  1304. //Converts the "data":"js_variable" to "data":js_variable,
  1305. // otherwise it will not work
  1306. $json_encode = str_replace('"data":"'.$data_var.'"', '"data":'.$data_var.'', $json_encode);
  1307. }
  1308. // Fixing true/false js values that doesn't need the ""
  1309. $json_encode = str_replace(':"true"', ':true', $json_encode);
  1310. // wrap_cell is not a valid jqgrid attributes is a hack to wrap a text
  1311. $json_encode = str_replace('"wrap_cell":true', 'cellattr : function(rowId, value, rowObject, colModel, arrData) { return \'class = "jqgrid_whitespace"\'; }', $json_encode);
  1312. $json_encode = str_replace(':"false"', ':false', $json_encode);
  1313. $json_encode = str_replace('"formatter":"action_formatter"', 'formatter:action_formatter', $json_encode);
  1314. $json_encode = str_replace('"formatter":"extra_formatter"', 'formatter:extra_formatter', $json_encode);
  1315. $json_encode = str_replace(['{"first":"first",', '"end":"end"}'], '', $json_encode);
  1316. // Creating the jqgrid element.
  1317. $json .= '$("#'.$div_id.'").jqGrid({';
  1318. //$json .= $beforeSelectRow;
  1319. $json .= $json_encode;
  1320. $json .= '});';
  1321. // Grouping headers option
  1322. if (isset($extra_params['groupHeaders'])) {
  1323. $groups = '';
  1324. foreach ($extra_params['groupHeaders'] as $group) {
  1325. //{ "startColumnName" : "courses", "numberOfColumns" : 1, "titleText" : "Order Info" },
  1326. $groups .= '{ "startColumnName" : "'.$group['startColumnName'].'", "numberOfColumns" : '.$group['numberOfColumns'].', "titleText" : "'.$group['titleText'].'" },';
  1327. }
  1328. $json .= '$("#'.$div_id.'").jqGrid("setGroupHeaders", {
  1329. "useColSpanStyle" : false,
  1330. "groupHeaders" : [
  1331. '.$groups.'
  1332. ]
  1333. });';
  1334. }
  1335. $all_text = addslashes(get_lang('All'));
  1336. $json .= '$("'.$obj->pager.' option[value='.$all_value.']").text("'.$all_text.'");';
  1337. $json .= "\n";
  1338. // Adding edit/delete icons.
  1339. $json .= $formatter;
  1340. return $json;
  1341. }
  1342. /**
  1343. * @param array $headers
  1344. * @param array $rows
  1345. * @param array $attributes
  1346. *
  1347. * @return string
  1348. */
  1349. public static function table($headers, $rows, $attributes = [])
  1350. {
  1351. if (empty($attributes)) {
  1352. $attributes['class'] = 'data_table';
  1353. }
  1354. $table = new HTML_Table($attributes);
  1355. $row = 0;
  1356. $column = 0;
  1357. // Course headers
  1358. if (!empty($headers)) {
  1359. foreach ($headers as $item) {
  1360. $table->setHeaderContents($row, $column, $item);
  1361. $column++;
  1362. }
  1363. $row = 1;
  1364. $column = 0;
  1365. }
  1366. if (!empty($rows)) {
  1367. foreach ($rows as $content) {
  1368. $table->setCellContents($row, $column, $content);
  1369. $row++;
  1370. }
  1371. }
  1372. return $table->toHtml();
  1373. }
  1374. /**
  1375. * Returns the "what's new" icon notifications.
  1376. *
  1377. * The general logic of this function is to track the last time the user
  1378. * entered the course and compare to what has changed inside this course
  1379. * since then, based on the item_property table inside this course. Note that,
  1380. * if the user never entered the course before, he will not see notification
  1381. * icons. This function takes session ID into account (if any) and only shows
  1382. * the corresponding notifications.
  1383. *
  1384. * @param array $courseInfo Course information array, containing at least elements 'db' and 'k'
  1385. * @param bool $loadAjax
  1386. *
  1387. * @return string The HTML link to be shown next to the course
  1388. */
  1389. public static function show_notification($courseInfo, $loadAjax = true)
  1390. {
  1391. if (empty($courseInfo)) {
  1392. return '';
  1393. }
  1394. $t_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  1395. $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
  1396. $tool_edit_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1397. $course_code = Database::escape_string($courseInfo['code']);
  1398. $user_id = api_get_user_id();
  1399. $course_id = (int) $courseInfo['real_id'];
  1400. $sessionId = (int) $courseInfo['id_session'];
  1401. $status = (int) $courseInfo['status'];
  1402. $loadNotificationsByAjax = api_get_configuration_value('user_portal_load_notification_by_ajax');
  1403. if ($loadNotificationsByAjax) {
  1404. if ($loadAjax) {
  1405. $id = 'notification_'.$course_id.'_'.$sessionId.'_'.$status;
  1406. Session::write($id, true);
  1407. return '<span id ="'.$id.'" class="course_notification"></span>';
  1408. }
  1409. }
  1410. // Get the user's last access dates to all tools of this course
  1411. $sql = "SELECT *
  1412. FROM $t_track_e_access
  1413. WHERE
  1414. c_id = $course_id AND
  1415. access_user_id = '$user_id' AND
  1416. access_session_id ='".$sessionId."'
  1417. ORDER BY access_date DESC
  1418. LIMIT 1
  1419. ";
  1420. $result = Database::query($sql);
  1421. // latest date by default is the creation date
  1422. $latestDate = $courseInfo['creation_date'];
  1423. if (Database::num_rows($result)) {
  1424. $row = Database::fetch_array($result, 'ASSOC');
  1425. $latestDate = $row['access_date'];
  1426. }
  1427. $sessionCondition = api_get_session_condition(
  1428. $sessionId,
  1429. true,
  1430. false,
  1431. 'session_id'
  1432. );
  1433. $hideTools = [TOOL_NOTEBOOK, TOOL_CHAT];
  1434. // Get current tools in course
  1435. $sql = "SELECT name, link, image
  1436. FROM $course_tool_table
  1437. WHERE
  1438. c_id = $course_id AND
  1439. visibility = '1' AND
  1440. name NOT IN ('".implode("','", $hideTools)."')
  1441. ";
  1442. $result = Database::query($sql);
  1443. $tools = Database::store_result($result);
  1444. $group_ids = GroupManager::get_group_ids($courseInfo['real_id'], $user_id);
  1445. $group_ids[] = 0; //add group 'everyone'
  1446. $notifications = [];
  1447. if ($tools) {
  1448. foreach ($tools as $tool) {
  1449. $toolName = $tool['name'];
  1450. $toolName = Database::escape_string($toolName);
  1451. // Fix to get student publications
  1452. $toolCondition = " tool = '$toolName' AND ";
  1453. if ($toolName == 'student_publication' || $toolName == 'work') {
  1454. $toolCondition = " (tool = 'work' OR tool = 'student_publication') AND ";
  1455. }
  1456. $toolName = addslashes($toolName);
  1457. $sql = "SELECT * FROM $tool_edit_table
  1458. WHERE
  1459. c_id = $course_id AND
  1460. $toolCondition
  1461. lastedit_type NOT LIKE '%Deleted%' AND
  1462. lastedit_type NOT LIKE '%deleted%' AND
  1463. lastedit_type NOT LIKE '%DocumentInvisible%' AND
  1464. lastedit_date > '$latestDate' AND
  1465. lastedit_user_id != $user_id $sessionCondition AND
  1466. visibility != 2 AND
  1467. (to_user_id IN ('$user_id', '0') OR to_user_id IS NULL) AND
  1468. (to_group_id IN ('".implode("','", $group_ids)."') OR to_group_id IS NULL)
  1469. ORDER BY lastedit_date DESC
  1470. LIMIT 1";
  1471. $result = Database::query($sql);
  1472. $latestChange = Database::fetch_array($result, 'ASSOC');
  1473. if ($latestChange) {
  1474. $latestChange['link'] = $tool['link'];
  1475. $latestChange['image'] = $tool['image'];
  1476. $latestChange['tool'] = $tool['name'];
  1477. $notifications[$toolName] = $latestChange;
  1478. }
  1479. }
  1480. }
  1481. // Show all tool icons where there is something new.
  1482. $return = '';
  1483. foreach ($notifications as $notification) {
  1484. $toolName = $notification['tool'];
  1485. if (!(
  1486. $notification['visibility'] == '1' ||
  1487. ($status == '1' && $notification['visibility'] == '0') ||
  1488. !isset($notification['visibility'])
  1489. )
  1490. ) {
  1491. continue;
  1492. }
  1493. if ($toolName == TOOL_SURVEY) {
  1494. $survey_info = SurveyManager::get_survey($notification['ref'], 0, $course_code);
  1495. if (!empty($survey_info)) {
  1496. $invited_users = SurveyUtil::get_invited_users(
  1497. $survey_info['code'],
  1498. $course_code
  1499. );
  1500. if (!in_array($user_id, $invited_users['course_users'])) {
  1501. continue;
  1502. }
  1503. }
  1504. }
  1505. if ($notification['tool'] == TOOL_LEARNPATH) {
  1506. if (!learnpath::is_lp_visible_for_student($notification['ref'], $user_id, $course_code)) {
  1507. continue;
  1508. }
  1509. }
  1510. if ($notification['tool'] == TOOL_DROPBOX) {
  1511. $notification['link'] = 'dropbox/dropbox_download.php?id='.$notification['ref'];
  1512. }
  1513. if ($notification['tool'] == 'work' &&
  1514. $notification['lastedit_type'] == 'DirectoryCreated'
  1515. ) {
  1516. $notification['lastedit_type'] = 'WorkAdded';
  1517. }
  1518. $lastDate = api_get_local_time($notification['lastedit_date']);
  1519. $type = $notification['lastedit_type'];
  1520. if ($type == 'CalendareventVisible') {
  1521. $type = 'Visible';
  1522. }
  1523. $label = get_lang('TitleNotification').": ".get_lang($type)." ($lastDate)";
  1524. if (strpos($notification['link'], '?') === false) {
  1525. $notification['link'] = $notification['link'].'?notification=1';
  1526. } else {
  1527. $notification['link'] = $notification['link'].'&notification=1';
  1528. }
  1529. $image = substr($notification['image'], 0, -4).'.png';
  1530. $return .= self::url(
  1531. self::return_icon($image, $label),
  1532. api_get_path(WEB_CODE_PATH).
  1533. $notification['link'].'&cidReq='.$course_code.
  1534. '&ref='.$notification['ref'].
  1535. '&gidReq='.$notification['to_group_id'].
  1536. '&id_session='.$sessionId
  1537. ).PHP_EOL;
  1538. }
  1539. return $return;
  1540. }
  1541. /**
  1542. * Get the session box details as an array.
  1543. *
  1544. * @param int Session ID
  1545. *
  1546. * @return array Empty array or session array
  1547. * ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
  1548. */
  1549. public static function getSessionTitleBox($session_id)
  1550. {
  1551. global $nosession;
  1552. if (!$nosession) {
  1553. global $now, $date_start, $date_end;
  1554. }
  1555. $output = [];
  1556. if (!$nosession) {
  1557. $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
  1558. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1559. // Request for the name of the general coach
  1560. $sql = 'SELECT tu.lastname, tu.firstname, ts.*
  1561. FROM '.$tbl_session.' ts
  1562. LEFT JOIN '.$main_user_table.' tu
  1563. ON ts.id_coach = tu.user_id
  1564. WHERE ts.id = '.intval($session_id);
  1565. $rs = Database::query($sql);
  1566. $session_info = Database::store_result($rs, 'ASSOC');
  1567. $session_info = $session_info[0];
  1568. $session = [];
  1569. $session['category_id'] = $session_info['session_category_id'];
  1570. $session['title'] = $session_info['name'];
  1571. $session['id_coach'] = $session_info['id_coach'];
  1572. $session['coach'] = '';
  1573. $session['dates'] = '';
  1574. if (api_get_setting('show_session_coach') === 'true') {
  1575. $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info['firstname'], $session_info['lastname']);
  1576. }
  1577. if (($session_info['access_end_date'] == '0000-00-00 00:00:00' &&
  1578. $session_info['access_start_date'] == '0000-00-00 00:00:00') ||
  1579. (empty($session_info['access_end_date']) && empty($session_info['access_start_date']))
  1580. ) {
  1581. if (isset($session_info['duration']) && !empty($session_info['duration'])) {
  1582. $daysLeft = SessionManager::getDayLeftInSession($session_info, api_get_user_id());
  1583. $session['duration'] = $daysLeft >= 0
  1584. ? sprintf(get_lang('SessionDurationXDaysLeft'), $daysLeft)
  1585. : get_lang('YourSessionTimeHasExpired');
  1586. }
  1587. $active = true;
  1588. } else {
  1589. $dates = SessionManager::parseSessionDates($session_info, true);
  1590. $session['dates'] = $dates['access'];
  1591. if (api_get_setting('show_session_coach') === 'true') {
  1592. $session['coach'] = api_get_person_name(
  1593. $session_info['firstname'],
  1594. $session_info['lastname']
  1595. );
  1596. }
  1597. $active = $date_start <= $now && $date_end >= $now;
  1598. }
  1599. $session['active'] = $active;
  1600. $session['session_category_id'] = $session_info['session_category_id'];
  1601. $session['visibility'] = $session_info['visibility'];
  1602. $session['num_users'] = $session_info['nbr_users'];
  1603. $session['num_courses'] = $session_info['nbr_courses'];
  1604. $session['description'] = $session_info['description'];
  1605. $session['show_description'] = $session_info['show_description'];
  1606. $entityManager = Database::getManager();
  1607. $fieldValuesRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldValues');
  1608. $extraFieldValues = $fieldValuesRepo->getVisibleValues(ExtraField::SESSION_FIELD_TYPE, $session_id);
  1609. $session['extra_fields'] = [];
  1610. /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
  1611. foreach ($extraFieldValues as $value) {
  1612. if (empty($value)) {
  1613. continue;
  1614. }
  1615. $session['extra_fields'][] = [
  1616. 'field' => [
  1617. 'variable' => $value->getField()->getVariable(),
  1618. 'display_text' => $value->getField()->getDisplayText(),
  1619. ],
  1620. 'value' => $value->getValue(),
  1621. ];
  1622. }
  1623. $output = $session;
  1624. }
  1625. return $output;
  1626. }
  1627. /**
  1628. * Return the five star HTML.
  1629. *
  1630. * @param string $id of the rating ul element
  1631. * @param string $url that will be added (for jquery see hot_courses.tpl)
  1632. * @param array $point_info point info array see function CourseManager::get_course_ranking()
  1633. * @param bool $add_div_wrapper add a div wrapper
  1634. *
  1635. * @return string
  1636. */
  1637. public static function return_rating_system(
  1638. $id,
  1639. $url,
  1640. $point_info = [],
  1641. $add_div_wrapper = true
  1642. ) {
  1643. $number_of_users_who_voted = isset($point_info['users_who_voted']) ? $point_info['users_who_voted'] : null;
  1644. $percentage = isset($point_info['point_average']) ? $point_info['point_average'] : 0;
  1645. if (!empty($percentage)) {
  1646. $percentage = $percentage * 125 / 100;
  1647. }
  1648. $accesses = isset($point_info['accesses']) ? $point_info['accesses'] : 0;
  1649. $star_label = sprintf(get_lang('XStarsOutOf5'), $point_info['point_average_star']);
  1650. $html = '<ul id="'.$id.'" class="star-rating">
  1651. <li class="current-rating" style="width:'.$percentage.'px;"></li>
  1652. <li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=1" title="'.$star_label.'" class="one-star">1</a></li>
  1653. <li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=2" title="'.$star_label.'" class="two-stars">2</a></li>
  1654. <li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=3" title="'.$star_label.'" class="three-stars">3</a></li>
  1655. <li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=4" title="'.$star_label.'" class="four-stars">4</a></li>
  1656. <li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=5" title="'.$star_label.'" class="five-stars">5</a></li>
  1657. </ul>';
  1658. $labels = [];
  1659. $labels[] = $number_of_users_who_voted == 1 ? $number_of_users_who_voted.' '.get_lang('Vote') : $number_of_users_who_voted.' '.get_lang('Votes');
  1660. $labels[] = $accesses == 1 ? $accesses.' '.get_lang('Visit') : $accesses.' '.get_lang('Visits');
  1661. $labels[] = $point_info['user_vote'] ? get_lang('YourVote').' ['.$point_info['user_vote'].']' : get_lang('YourVote').' [?] ';
  1662. if (!$add_div_wrapper && api_is_anonymous()) {
  1663. $labels[] = self::tag('span', get_lang('LoginToVote'), ['class' => 'error']);
  1664. }
  1665. $html .= self::div(implode(' | ', $labels), ['id' => 'vote_label_'.$id, 'class' => 'vote_label_info']);
  1666. $html .= ' '.self::span(' ', ['id' => 'vote_label2_'.$id]);
  1667. if ($add_div_wrapper) {
  1668. $html = self::div($html, ['id' => 'rating_wrapper_'.$id]);
  1669. }
  1670. return $html;
  1671. }
  1672. /**
  1673. * @param string $title
  1674. * @param string $second_title
  1675. * @param string $size
  1676. * @param bool $filter
  1677. *
  1678. * @return string
  1679. */
  1680. public static function page_header($title, $second_title = null, $size = 'h2', $filter = true)
  1681. {
  1682. if ($filter) {
  1683. $title = Security::remove_XSS($title);
  1684. }
  1685. if (!empty($second_title)) {
  1686. if ($filter) {
  1687. $second_title = Security::remove_XSS($second_title);
  1688. }
  1689. $title .= "<small> $second_title</small>";
  1690. }
  1691. return '<'.$size.' class="page-header">'.$title.'</'.$size.'>';
  1692. }
  1693. public static function page_header_and_translate($title, $second_title = null)
  1694. {
  1695. $title = get_lang($title);
  1696. return self::page_header($title, $second_title);
  1697. }
  1698. public static function page_subheader_and_translate($title, $second_title = null)
  1699. {
  1700. $title = get_lang($title);
  1701. return self::page_subheader($title, $second_title);
  1702. }
  1703. public static function page_subheader($title, $second_title = null, $size = 'h3')
  1704. {
  1705. if (!empty($second_title)) {
  1706. $second_title = Security::remove_XSS($second_title);
  1707. $title .= "<small> $second_title<small>";
  1708. }
  1709. return '<'.$size.'>'.Security::remove_XSS($title).'</'.$size.'>';
  1710. }
  1711. public static function page_subheader2($title, $second_title = null)
  1712. {
  1713. return self::page_header($title, $second_title, 'h4');
  1714. }
  1715. public static function page_subheader3($title, $second_title = null)
  1716. {
  1717. return self::page_header($title, $second_title, 'h5');
  1718. }
  1719. /**
  1720. * @param array $list
  1721. *
  1722. * @return null|string
  1723. */
  1724. public static function description($list)
  1725. {
  1726. $html = null;
  1727. if (!empty($list)) {
  1728. $html = '<dl class="dl-horizontal">';
  1729. foreach ($list as $item) {
  1730. $html .= '<dt>'.$item['title'].'</dt>';
  1731. $html .= '<dd>'.$item['content'].'</dd>';
  1732. }
  1733. $html .= '</dl>';
  1734. }
  1735. return $html;
  1736. }
  1737. /**
  1738. * @param $percentage
  1739. * @param bool $show_percentage
  1740. * @param null $extra_info
  1741. *
  1742. * @return string
  1743. */
  1744. public static function bar_progress($percentage, $show_percentage = true, $extra_info = null)
  1745. {
  1746. $percentage = intval($percentage);
  1747. $div = '<div class="progress">
  1748. <div
  1749. class="progress-bar progress-bar-striped"
  1750. role="progressbar"
  1751. aria-valuenow="'.$percentage.'"
  1752. aria-valuemin="0"
  1753. aria-valuemax="100"
  1754. style="width: '.$percentage.'%;"
  1755. >';
  1756. if ($show_percentage) {
  1757. $div .= $percentage.'%';
  1758. } else {
  1759. if (!empty($extra_info)) {
  1760. $div .= $extra_info;
  1761. }
  1762. }
  1763. $div .= '</div>';
  1764. return $div;
  1765. }
  1766. /**
  1767. * @param string $count
  1768. * @param string $type
  1769. *
  1770. * @return null|string
  1771. */
  1772. public static function badge($count, $type = "warning")
  1773. {
  1774. $class = '';
  1775. switch ($type) {
  1776. case 'success':
  1777. $class = 'badge-success';
  1778. break;
  1779. case 'warning':
  1780. $class = 'badge-warning';
  1781. break;
  1782. case 'important':
  1783. $class = 'badge-important';
  1784. break;
  1785. case 'info':
  1786. $class = 'badge-info';
  1787. break;
  1788. case 'inverse':
  1789. $class = 'badge-inverse';
  1790. break;
  1791. }
  1792. if (!empty($count)) {
  1793. return ' <span class="badge '.$class.'">'.$count.'</span>';
  1794. }
  1795. return null;
  1796. }
  1797. /**
  1798. * @param array $badge_list
  1799. *
  1800. * @return string
  1801. */
  1802. public static function badge_group($badge_list)
  1803. {
  1804. $html = '<div class="badge-group">';
  1805. foreach ($badge_list as $badge) {
  1806. $html .= $badge;
  1807. }
  1808. $html .= '</div>';
  1809. return $html;
  1810. }
  1811. /**
  1812. * @param string $content
  1813. * @param string $type
  1814. *
  1815. * @return string
  1816. */
  1817. public static function label($content, $type = 'default')
  1818. {
  1819. switch ($type) {
  1820. case 'success':
  1821. $class = 'success';
  1822. break;
  1823. case 'warning':
  1824. $class = 'warning';
  1825. break;
  1826. case 'important':
  1827. case 'danger':
  1828. $class = 'danger';
  1829. break;
  1830. case 'info':
  1831. $class = 'info';
  1832. break;
  1833. case 'primary':
  1834. $class = 'primary';
  1835. break;
  1836. default:
  1837. $class = 'secondary';
  1838. break;
  1839. }
  1840. $html = '';
  1841. if (!empty($content)) {
  1842. $html = '<span class="badge badge-'.$class.'">';
  1843. $html .= $content;
  1844. $html .= '</span>';
  1845. }
  1846. return $html;
  1847. }
  1848. /**
  1849. * @param array $items
  1850. * @param string $class
  1851. *
  1852. * @return null|string
  1853. */
  1854. public static function actions($items, $class = 'new_actions')
  1855. {
  1856. $html = null;
  1857. if (!empty($items)) {
  1858. $html = '<div class="'.$class.'"><ul class="nav nav-pills">';
  1859. foreach ($items as $value) {
  1860. $class = null;
  1861. if (isset($value['active']) && $value['active']) {
  1862. $class = 'class ="active"';
  1863. }
  1864. if (basename($_SERVER['REQUEST_URI']) == basename($value['url'])) {
  1865. $class = 'class ="active"';
  1866. }
  1867. $html .= "<li $class >";
  1868. $attributes = isset($value['url_attributes']) ? $value['url_attributes'] : [];
  1869. $html .= self::url($value['content'], $value['url'], $attributes);
  1870. $html .= '</li>';
  1871. }
  1872. $html .= '</ul></div>';
  1873. $html .= '<br />';
  1874. }
  1875. return $html;
  1876. }
  1877. /**
  1878. * Prints a tooltip.
  1879. *
  1880. * @param string $text
  1881. * @param string $tip
  1882. *
  1883. * @return string
  1884. */
  1885. public static function tip($text, $tip)
  1886. {
  1887. if (empty($tip)) {
  1888. return $text;
  1889. }
  1890. return self::span(
  1891. $text,
  1892. ['class' => 'boot-tooltip', 'title' => strip_tags($tip)]
  1893. );
  1894. }
  1895. /**
  1896. * @param array $buttons
  1897. *
  1898. * @return string
  1899. */
  1900. public static function groupButton($buttons)
  1901. {
  1902. $html = '<div class="btn-group" role="group">';
  1903. foreach ($buttons as $button) {
  1904. $html .= $button;
  1905. }
  1906. $html .= '</div>';
  1907. return $html;
  1908. }
  1909. /**
  1910. * @todo use twig
  1911. *
  1912. * @param string $title
  1913. * @param array $elements
  1914. * @param bool $alignToRight
  1915. *
  1916. * @return string
  1917. */
  1918. public static function groupButtonWithDropDown($title, $elements, $alignToRight = false)
  1919. {
  1920. $html = '<div class="btn-group">
  1921. <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">
  1922. '.$title.'
  1923. <span class="caret"></span></button>
  1924. <ul class="dropdown-menu '.($alignToRight ? 'dropdown-menu-right' : '').'">';
  1925. foreach ($elements as $item) {
  1926. $html .= self::tag('li', self::url($item['title'], $item['href']));
  1927. }
  1928. $html .= '</ul>
  1929. </div>';
  1930. return $html;
  1931. }
  1932. /**
  1933. * @param string $file
  1934. * @param array $params
  1935. *
  1936. * @return null|string
  1937. */
  1938. public static function getMediaPlayer($file, $params = [])
  1939. {
  1940. $fileInfo = pathinfo($file);
  1941. switch ($fileInfo['extension']) {
  1942. case 'mp3':
  1943. case 'webm':
  1944. $autoplay = null;
  1945. if (isset($params['autoplay']) && $params['autoplay'] == 'true') {
  1946. $autoplay = 'autoplay';
  1947. }
  1948. $width = isset($params['width']) ? 'width="'.$params['width'].'"' : null;
  1949. $id = isset($params['id']) ? $params['id'] : $fileInfo['basename'];
  1950. $class = isset($params['class']) ? ' class="'.$params['class'].'"' : null;
  1951. $html = '<audio id="'.$id.'" '.$class.' controls '.$autoplay.' '.$width.' src="'.$params['url'].'" >';
  1952. $html .= '<object width="'.$width.'" height="50" type="application/x-shockwave-flash" data="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf">
  1953. <param name="movie" value="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf" />
  1954. <param name="flashvars" value="controls=true&file='.$params['url'].'" />
  1955. </object>';
  1956. $html .= '</audio>';
  1957. return $html;
  1958. break;
  1959. case 'wav':
  1960. case 'ogg':
  1961. $html = '<audio width="300px" controls src="'.$params['url'].'" >';
  1962. return $html;
  1963. break;
  1964. }
  1965. return null;
  1966. }
  1967. /**
  1968. * @param int $nextValue
  1969. * @param array $list
  1970. * @param int $current
  1971. * @param int $fixedValue
  1972. * @param array $conditions
  1973. * @param string $link
  1974. * @param bool $isMedia
  1975. * @param bool $addHeaders
  1976. * @param array $linkAttributes
  1977. *
  1978. * @return string
  1979. */
  1980. public static function progressPaginationBar(
  1981. $nextValue,
  1982. $list,
  1983. $current,
  1984. $fixedValue = null,
  1985. $conditions = [],
  1986. $link = null,
  1987. $isMedia = false,
  1988. $addHeaders = true,
  1989. $linkAttributes = []
  1990. ) {
  1991. if ($addHeaders) {
  1992. $pagination_size = 'pagination-mini';
  1993. $html = '<div class="exercise_pagination pagination '.$pagination_size.'"><ul>';
  1994. } else {
  1995. $html = null;
  1996. }
  1997. $affectAllItems = false;
  1998. if ($isMedia && isset($fixedValue) && ($nextValue + 1 == $current)) {
  1999. $affectAllItems = true;
  2000. }
  2001. $localCounter = 0;
  2002. foreach ($list as $itemId) {
  2003. $isCurrent = false;
  2004. if ($affectAllItems) {
  2005. $isCurrent = true;
  2006. } else {
  2007. if (!$isMedia) {
  2008. $isCurrent = $current == ($localCounter + $nextValue + 1) ? true : false;
  2009. }
  2010. }
  2011. $html .= self::parsePaginationItem(
  2012. $itemId,
  2013. $isCurrent,
  2014. $conditions,
  2015. $link,
  2016. $nextValue,
  2017. $isMedia,
  2018. $localCounter,
  2019. $fixedValue,
  2020. $linkAttributes
  2021. );
  2022. $localCounter++;
  2023. }
  2024. if ($addHeaders) {
  2025. $html .= '</ul></div>';
  2026. }
  2027. return $html;
  2028. }
  2029. /**
  2030. * @param int $itemId
  2031. * @param bool $isCurrent
  2032. * @param array $conditions
  2033. * @param string $link
  2034. * @param int $nextValue
  2035. * @param bool $isMedia
  2036. * @param int $localCounter
  2037. * @param int $fixedValue
  2038. * @param array $linkAttributes
  2039. *
  2040. * @return string
  2041. */
  2042. public static function parsePaginationItem(
  2043. $itemId,
  2044. $isCurrent,
  2045. $conditions,
  2046. $link,
  2047. $nextValue = 0,
  2048. $isMedia = false,
  2049. $localCounter = null,
  2050. $fixedValue = null,
  2051. $linkAttributes = []
  2052. ) {
  2053. $defaultClass = 'before';
  2054. $class = $defaultClass;
  2055. foreach ($conditions as $condition) {
  2056. $array = isset($condition['items']) ? $condition['items'] : [];
  2057. $class_to_applied = $condition['class'];
  2058. $type = isset($condition['type']) ? $condition['type'] : 'positive';
  2059. $mode = isset($condition['mode']) ? $condition['mode'] : 'add';
  2060. switch ($type) {
  2061. case 'positive':
  2062. if (in_array($itemId, $array)) {
  2063. if ($mode == 'overwrite') {
  2064. $class = " $defaultClass $class_to_applied";
  2065. } else {
  2066. $class .= " $class_to_applied";
  2067. }
  2068. }
  2069. break;
  2070. case 'negative':
  2071. if (!in_array($itemId, $array)) {
  2072. if ($mode == 'overwrite') {
  2073. $class = " $defaultClass $class_to_applied";
  2074. } else {
  2075. $class .= " $class_to_applied";
  2076. }
  2077. }
  2078. break;
  2079. }
  2080. }
  2081. if ($isCurrent) {
  2082. $class = 'before current';
  2083. }
  2084. if ($isMedia && $isCurrent) {
  2085. $class = 'before current';
  2086. }
  2087. if (empty($link)) {
  2088. $link_to_show = '#';
  2089. } else {
  2090. $link_to_show = $link.($nextValue + $localCounter);
  2091. }
  2092. $label = $nextValue + $localCounter + 1;
  2093. if ($isMedia) {
  2094. $label = ($fixedValue + 1).' '.chr(97 + $localCounter);
  2095. $link_to_show = $link.$fixedValue.'#questionanchor'.$itemId;
  2096. }
  2097. $link = self::url($label.' ', $link_to_show, $linkAttributes);
  2098. return '<li class = "'.$class.'">'.$link.'</li>';
  2099. }
  2100. /**
  2101. * @param int $current
  2102. * @param int $total
  2103. *
  2104. * @return string
  2105. */
  2106. public static function paginationIndicator($current, $total)
  2107. {
  2108. $html = null;
  2109. if (!empty($current) && !empty($total)) {
  2110. $label = sprintf(get_lang('PaginationXofY'), $current, $total);
  2111. $html = self::url($label, '#', ['class' => 'btn disabled']);
  2112. }
  2113. return $html;
  2114. }
  2115. /**
  2116. * Adds a message in the queue.
  2117. *
  2118. * @param string $message
  2119. */
  2120. public static function addFlash($message)
  2121. {
  2122. $messages = Session::read('flash_messages');
  2123. if (empty($messages)) {
  2124. $messages[] = $message;
  2125. } else {
  2126. array_push($messages, $message);
  2127. }
  2128. Session::write('flash_messages', $messages);
  2129. }
  2130. /**
  2131. * @return string
  2132. */
  2133. public static function getFlashToString()
  2134. {
  2135. $messages = Session::read('flash_messages');
  2136. $messageToString = '';
  2137. if (!empty($messages)) {
  2138. foreach ($messages as $message) {
  2139. $messageToString .= $message;
  2140. }
  2141. }
  2142. return $messageToString;
  2143. }
  2144. /**
  2145. * Shows the message from the session.
  2146. */
  2147. public static function showFlash()
  2148. {
  2149. echo self::getFlashToString();
  2150. }
  2151. /**
  2152. * Destroys the message session.
  2153. */
  2154. public static function cleanFlashMessages()
  2155. {
  2156. Session::erase('flash_messages');
  2157. }
  2158. /**
  2159. * Get the profile edition link for a user.
  2160. *
  2161. * @param int $userId The user id
  2162. * @param bool $asAdmin Optional. Whether get the URL for the platform admin
  2163. *
  2164. * @return string The link
  2165. */
  2166. public static function getProfileEditionLink($userId, $asAdmin = false)
  2167. {
  2168. $editProfileUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
  2169. if ($asAdmin) {
  2170. $editProfileUrl = api_get_path(WEB_CODE_PATH)."admin/user_edit.php?user_id=".intval($userId);
  2171. }
  2172. if (api_get_setting('sso_authentication') === 'true') {
  2173. $subSSOClass = api_get_setting('sso_authentication_subclass');
  2174. $objSSO = null;
  2175. if (!empty($subSSOClass)) {
  2176. $file = api_get_path(SYS_CODE_PATH)."auth/sso/sso.$subSSOClass.class.php";
  2177. if (file_exists($file)) {
  2178. require_once $file;
  2179. $subSSOClass = 'sso'.$subSSOClass;
  2180. $objSSO = new $subSSOClass();
  2181. } else {
  2182. throw new Exception("$subSSOClass file not set");
  2183. }
  2184. } else {
  2185. $objSSO = new sso();
  2186. }
  2187. $editProfileUrl = $objSSO->generateProfileEditingURL(
  2188. $userId,
  2189. $asAdmin
  2190. );
  2191. }
  2192. return $editProfileUrl;
  2193. }
  2194. /**
  2195. * Get the vCard for a user.
  2196. *
  2197. * @param int $userId The user id
  2198. *
  2199. * @return string *.*vcf file
  2200. */
  2201. public static function getVCardUserLink($userId)
  2202. {
  2203. $vCardUrl = api_get_path(WEB_PATH).'main/social/vcard_export.php?userId='.intval($userId);
  2204. return $vCardUrl;
  2205. }
  2206. /**
  2207. * @param string $content
  2208. * @param string $title
  2209. * @param string $footer
  2210. * @param string $type primary|success|info|warning|danger
  2211. * @param string $extra
  2212. * @param string $id
  2213. * @param string $customColor
  2214. *
  2215. * @return string
  2216. */
  2217. public static function panel(
  2218. $content,
  2219. $title = '',
  2220. $footer = '',
  2221. $type = 'default',
  2222. $extra = '',
  2223. $id = '',
  2224. $customColor = ''
  2225. ) {
  2226. $headerStyle = '';
  2227. if (!empty($customColor)) {
  2228. $headerStyle = 'style = "color: white; background-color: '.$customColor.'" ';
  2229. }
  2230. $title = !empty($title) ? '<div class="panel-heading" '.$headerStyle.' ><h3 class="panel-title">'.$title.'</h3>'.$extra.'</div>' : '';
  2231. $footer = !empty($footer) ? '<div class="panel-footer">'.$footer.'</div>' : '';
  2232. $typeList = ['primary', 'success', 'info', 'warning', 'danger'];
  2233. $style = !in_array($type, $typeList) ? 'default' : $type;
  2234. if (!empty($id)) {
  2235. $id = " id='$id'";
  2236. }
  2237. return '
  2238. <div '.$id.' class="panel panel-'.$style.'">
  2239. '.$title.'
  2240. '.self::contentPanel($content).'
  2241. '.$footer.'
  2242. </div>'
  2243. ;
  2244. }
  2245. /**
  2246. * @param string $content
  2247. *
  2248. * @return string
  2249. */
  2250. public static function contentPanel($content)
  2251. {
  2252. if (empty($content)) {
  2253. return '';
  2254. }
  2255. return '<div class="panel-body">'.$content.'</div>';
  2256. }
  2257. /**
  2258. * Get the button HTML with an Awesome Font icon.
  2259. *
  2260. * @param string $text The button content
  2261. * @param string $url The url to button
  2262. * @param string $icon The Awesome Font class for icon
  2263. * @param string $type Optional. The button Bootstrap class. Default 'default' class
  2264. * @param array $attributes The additional attributes
  2265. * @param bool $includeText
  2266. *
  2267. * @return string The button HTML
  2268. */
  2269. public static function toolbarButton(
  2270. $text,
  2271. $url,
  2272. $icon = 'check',
  2273. $type = 'default',
  2274. array $attributes = [],
  2275. $includeText = true
  2276. ) {
  2277. $buttonClass = "btn btn-$type";
  2278. $icon = self::tag('i', null, ['class' => "fa fa-$icon fa-fw", 'aria-hidden' => 'true']);
  2279. $attributes['class'] = isset($attributes['class']) ? "$buttonClass {$attributes['class']}" : $buttonClass;
  2280. $attributes['title'] = isset($attributes['title']) ? $attributes['title'] : $text;
  2281. if (!$includeText) {
  2282. $text = '<span class="sr-only">'.$text.'</span>';
  2283. }
  2284. return self::url("$icon $text", $url, $attributes);
  2285. }
  2286. /**
  2287. * @param string $id
  2288. * @param array $content
  2289. * @param array $colsWidth Optional. Columns width
  2290. *
  2291. * @return string
  2292. */
  2293. public static function toolbarAction($id, $content, $colsWidth = [])
  2294. {
  2295. $col = count($content);
  2296. if (!$colsWidth) {
  2297. $width = 12 / $col;
  2298. array_walk($content, function () use ($width, &$colsWidth) {
  2299. $colsWidth[] = $width;
  2300. });
  2301. }
  2302. $html = '<div id="'.$id.'" class="actions">';
  2303. $html .= '<div class="row">';
  2304. for ($i = 0; $i < $col; $i++) {
  2305. $class = 'col-sm-'.$colsWidth[$i];
  2306. if ($col > 1) {
  2307. if ($i > 0 && $i < count($content) - 1) {
  2308. $class .= ' text-center';
  2309. } elseif ($i === count($content) - 1) {
  2310. $class .= ' text-right';
  2311. }
  2312. }
  2313. $html .= '<div class="'.$class.'">'.$content[$i].'</div>';
  2314. }
  2315. $html .= '</div>';
  2316. $html .= '</div>';
  2317. return $html;
  2318. }
  2319. /**
  2320. * Get a HTML code for a icon by Font Awesome.
  2321. *
  2322. * @param string $name The icon name
  2323. * @param int|string $size Optional. The size for the icon. (Example: lg, 2, 3, 4, 5)
  2324. * @param bool $fixWidth Optional. Whether add the fw class
  2325. * @param string $additionalClass Optional. Additional class
  2326. *
  2327. * @return string
  2328. */
  2329. public static function returnFontAwesomeIcon(
  2330. $name,
  2331. $size = '',
  2332. $fixWidth = false,
  2333. $additionalClass = ''
  2334. ) {
  2335. $className = "fa fa-$name";
  2336. if ($fixWidth) {
  2337. $className .= ' fa-fw';
  2338. }
  2339. switch ($size) {
  2340. case 'lg':
  2341. $className .= ' fa-lg';
  2342. break;
  2343. case 2:
  2344. case 3:
  2345. case 4:
  2346. case 5:
  2347. $className .= " fa-{$size}x";
  2348. break;
  2349. }
  2350. if (!empty($additionalClass)) {
  2351. $className .= " $additionalClass";
  2352. }
  2353. $icon = self::tag('em', null, ['class' => $className]);
  2354. return "$icon ";
  2355. }
  2356. /**
  2357. * @param string $title
  2358. * @param string $content
  2359. * @param null $id
  2360. * @param array $params
  2361. * @param null $idAccordion
  2362. * @param null $idCollapse
  2363. * @param bool|true $open
  2364. * @param bool|false $fullClickable
  2365. *
  2366. * @return null|string
  2367. *
  2368. * @todo rework function to easy use
  2369. */
  2370. public static function panelCollapse(
  2371. $title,
  2372. $content,
  2373. $id = null,
  2374. $params = [],
  2375. $idAccordion = null,
  2376. $idCollapse = null,
  2377. $open = true,
  2378. $fullClickable = false
  2379. ) {
  2380. if (!empty($idAccordion)) {
  2381. $headerClass = '';
  2382. $headerClass .= $fullClickable ? 'center-block ' : '';
  2383. $headerClass .= $open ? '' : 'collapsed';
  2384. $contentClass = 'panel-collapse collapse ';
  2385. $contentClass .= $open ? 'in' : '';
  2386. $ariaExpanded = $open ? 'true' : 'false';
  2387. $html = <<<HTML
  2388. <div class="panel-group" id="$idAccordion" role="tablist" aria-multiselectable="true">
  2389. <div class="panel panel-default" id="$id">
  2390. <div class="panel-heading" role="tab">
  2391. <h4 class="panel-title">
  2392. <a class="$headerClass" role="button" data-toggle="collapse" data-parent="#$idAccordion" href="#$idCollapse" aria-expanded="$ariaExpanded" aria-controls="$idCollapse">$title</a>
  2393. </h4>
  2394. </div>
  2395. <div id="$idCollapse" class="$contentClass" role="tabpanel">
  2396. <div class="panel-body">$content</div>
  2397. </div>
  2398. </div>
  2399. </div>
  2400. HTML;
  2401. } else {
  2402. if (!empty($id)) {
  2403. $params['id'] = $id;
  2404. }
  2405. $params['class'] = 'panel panel-default';
  2406. $html = null;
  2407. if (!empty($title)) {
  2408. $html .= '<div class="panel-heading">'.$title.'</div>'.PHP_EOL;
  2409. }
  2410. $html .= '<div class="panel-body">'.$content.'</div>'.PHP_EOL;
  2411. $html = self::div($html, $params);
  2412. }
  2413. return $html;
  2414. }
  2415. /**
  2416. * Returns the string "1 day ago" with a link showing the exact date time.
  2417. *
  2418. * @param string $dateTime in UTC or a DateTime in UTC
  2419. *
  2420. * @return string
  2421. */
  2422. public static function dateToStringAgoAndLongDate($dateTime)
  2423. {
  2424. if (empty($dateTime) || $dateTime === '0000-00-00 00:00:00') {
  2425. return '';
  2426. }
  2427. if ($dateTime instanceof \DateTime) {
  2428. $dateTime = $dateTime->format('Y-m-d H:i:s');
  2429. }
  2430. return self::tip(
  2431. date_to_str_ago($dateTime),
  2432. api_convert_and_format_date($dateTime, DATE_TIME_FORMAT_LONG)
  2433. //api_get_local_time($dateTime)
  2434. );
  2435. }
  2436. /**
  2437. * @param array $userInfo
  2438. * @param string $status
  2439. * @param string $toolbar
  2440. *
  2441. * @return string
  2442. */
  2443. public static function getUserCard($userInfo, $status = '', $toolbar = '')
  2444. {
  2445. if (empty($userInfo)) {
  2446. return '';
  2447. }
  2448. if (!empty($status)) {
  2449. $status = '<div class="items-user-status">'.$status.'</div>';
  2450. }
  2451. if (!empty($toolbar)) {
  2452. $toolbar = '<div class="btn-group pull-right">'.$toolbar.'</div>';
  2453. }
  2454. return '<div id="user_card_'.$userInfo['id'].'" class="col-md-12">
  2455. <div class="row">
  2456. <div class="col-md-2">
  2457. <img src="'.$userInfo['avatar'].'" class="img-responsive img-circle">
  2458. </div>
  2459. <div class="col-md-10">
  2460. <p>'.$userInfo['complete_name'].'</p>
  2461. <div class="row">
  2462. <div class="col-md-2">
  2463. '.$status.'
  2464. </div>
  2465. <div class="col-md-10">
  2466. '.$toolbar.'
  2467. </div>
  2468. </div>
  2469. </div>
  2470. </div>
  2471. <hr />
  2472. </div>';
  2473. }
  2474. /**
  2475. * Displays the reduced page header (without banner).
  2476. */
  2477. private static function set_header()
  2478. {
  2479. global $show_learnpath, $tool_name;
  2480. self::$global_template = new Template(
  2481. $tool_name,
  2482. false,
  2483. false,
  2484. $show_learnpath
  2485. );
  2486. }
  2487. }