link.lib.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CLink;
  4. /**
  5. * Function library for the links tool.
  6. *
  7. * This is a complete remake of the original link tool.
  8. * New features:
  9. * - Organize links into categories;
  10. * - favorites/bookmarks interface;
  11. * - move links up/down within a category;
  12. * - move categories up/down;
  13. * - expand/collapse all categories;
  14. * - add link to 'root' category => category-less link is always visible.
  15. *
  16. * @author Patrick Cool, complete remake (December 2003 - January 2004)
  17. * @author René Haentjens, CSV file import (October 2004)
  18. *
  19. * @package chamilo.link
  20. */
  21. class Link extends Model
  22. {
  23. public $table;
  24. public $is_course_model = true;
  25. public $columns = [
  26. 'id',
  27. 'c_id',
  28. 'url',
  29. 'title',
  30. 'description',
  31. 'category_id',
  32. 'display_order',
  33. 'on_homepage',
  34. 'target',
  35. 'session_id',
  36. ];
  37. public $required = ['url', 'title'];
  38. private $course;
  39. /**
  40. * Link constructor.
  41. */
  42. public function __construct()
  43. {
  44. $this->table = Database::get_course_table(TABLE_LINK);
  45. }
  46. /**
  47. * @param array $course
  48. */
  49. public function setCourse($course)
  50. {
  51. $this->course = $course;
  52. }
  53. /**
  54. * @return array
  55. */
  56. public function getCourse()
  57. {
  58. return !empty($this->course) ? $this->course : api_get_course_info();
  59. }
  60. /**
  61. * Organize the saving of a link, using the parent's save method and
  62. * updating the item_property table.
  63. *
  64. * @param array $params
  65. * @param bool $show_query Whether to show the query in logs when
  66. * calling parent's save method
  67. *
  68. * @return bool True if link could be saved, false otherwise
  69. */
  70. public function save($params, $show_query = null)
  71. {
  72. $course_info = $this->getCourse();
  73. $courseId = $course_info['real_id'];
  74. $params['session_id'] = api_get_session_id();
  75. $params['category_id'] = isset($params['category_id']) ? $params['category_id'] : 0;
  76. $sql = "SELECT MAX(display_order)
  77. FROM ".$this->table."
  78. WHERE
  79. c_id = $courseId AND
  80. category_id = '".intval($params['category_id'])."'";
  81. $result = Database:: query($sql);
  82. list($orderMax) = Database:: fetch_row($result);
  83. $order = $orderMax + 1;
  84. $params['display_order'] = $order;
  85. $id = parent::save($params, $show_query);
  86. if (!empty($id)) {
  87. // iid
  88. $sql = "UPDATE ".$this->table." SET id = iid WHERE iid = $id";
  89. Database::query($sql);
  90. api_item_property_update(
  91. $course_info,
  92. TOOL_LINK,
  93. $id,
  94. 'LinkAdded',
  95. api_get_user_id()
  96. );
  97. api_set_default_visibility($id, TOOL_LINK);
  98. }
  99. return $id;
  100. }
  101. /**
  102. * Update a link in the database.
  103. *
  104. * @param int $linkId The ID of the link to update
  105. * @param string $linkUrl The new URL to be saved
  106. * @param int $courseId
  107. * @param int $sessionId
  108. *
  109. * @return bool
  110. */
  111. public function updateLink(
  112. $linkId,
  113. $linkUrl,
  114. $courseId = null,
  115. $sessionId = null
  116. ) {
  117. $tblLink = Database::get_course_table(TABLE_LINK);
  118. $linkUrl = Database::escape_string($linkUrl);
  119. $linkId = intval($linkId);
  120. if (is_null($courseId)) {
  121. $courseId = api_get_course_int_id();
  122. }
  123. $courseId = intval($courseId);
  124. if (is_null($sessionId)) {
  125. $sessionId = api_get_session_id();
  126. }
  127. $sessionId = intval($sessionId);
  128. if ($linkUrl != '') {
  129. $sql = "UPDATE $tblLink SET
  130. url = '$linkUrl'
  131. WHERE id = $linkId AND c_id = $courseId AND session_id = $sessionId";
  132. $resLink = Database::query($sql);
  133. return $resLink;
  134. }
  135. return false;
  136. }
  137. /**
  138. * Used to add a link or a category.
  139. *
  140. * @param string $type , "link" or "category"
  141. *
  142. * @todo replace strings by constants
  143. *
  144. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  145. *
  146. * @return bool True on success, false on failure
  147. */
  148. public static function addlinkcategory($type)
  149. {
  150. $ok = true;
  151. $_course = api_get_course_info();
  152. $course_id = $_course['real_id'];
  153. $session_id = api_get_session_id();
  154. if ($type == 'link') {
  155. $title = Security::remove_XSS(stripslashes($_POST['title']));
  156. $urllink = Security::remove_XSS($_POST['url']);
  157. $description = Security::remove_XSS($_POST['description']);
  158. $selectcategory = Security::remove_XSS($_POST['category_id']);
  159. $onhomepage = 0;
  160. if (isset($_POST['on_homepage'])) {
  161. $onhomepage = Security::remove_XSS($_POST['on_homepage']);
  162. }
  163. $target = '_self'; // Default target.
  164. if (!empty($_POST['target'])) {
  165. $target = Security::remove_XSS($_POST['target']);
  166. }
  167. $urllink = trim($urllink);
  168. $title = trim($title);
  169. $description = trim($description);
  170. // We ensure URL to be absolute.
  171. if (strpos($urllink, '://') === false) {
  172. $urllink = 'http://'.$urllink;
  173. }
  174. // If the title is empty, we use the URL as title.
  175. if ($title == '') {
  176. $title = $urllink;
  177. }
  178. // If the URL is invalid, an error occurs.
  179. if (!api_valid_url($urllink, true)) {
  180. // A check against an absolute URL
  181. Display::addFlash(Display::return_message(get_lang('GiveURL'), 'error'));
  182. return false;
  183. } else {
  184. // Looking for the largest order number for this category.
  185. $link = new Link();
  186. $params = [
  187. 'c_id' => $course_id,
  188. 'url' => $urllink,
  189. 'title' => $title,
  190. 'description' => $description,
  191. 'category_id' => $selectcategory,
  192. 'on_homepage' => $onhomepage,
  193. 'target' => $target,
  194. 'session_id' => $session_id,
  195. ];
  196. $link_id = $link->save($params);
  197. if ((api_get_setting('search_enabled') == 'true') &&
  198. $link_id && extension_loaded('xapian')
  199. ) {
  200. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  201. $course_int_id = $_course['real_id'];
  202. $courseCode = $_course['code'];
  203. $specific_fields = get_specific_field_list();
  204. $ic_slide = new IndexableChunk();
  205. // Add all terms to db.
  206. $all_specific_terms = '';
  207. foreach ($specific_fields as $specific_field) {
  208. if (isset($_REQUEST[$specific_field['code']])) {
  209. $sterms = trim($_REQUEST[$specific_field['code']]);
  210. if (!empty($sterms)) {
  211. $all_specific_terms .= ' '.$sterms;
  212. $sterms = explode(',', $sterms);
  213. foreach ($sterms as $sterm) {
  214. $ic_slide->addTerm(
  215. trim($sterm),
  216. $specific_field['code']
  217. );
  218. add_specific_field_value(
  219. $specific_field['id'],
  220. $courseCode,
  221. TOOL_LINK,
  222. $link_id,
  223. $sterm
  224. );
  225. }
  226. }
  227. }
  228. }
  229. // Build the chunk to index.
  230. $ic_slide->addValue('title', $title);
  231. $ic_slide->addCourseId($courseCode);
  232. $ic_slide->addToolId(TOOL_LINK);
  233. $xapian_data = [
  234. SE_COURSE_ID => $courseCode,
  235. SE_TOOL_ID => TOOL_LINK,
  236. SE_DATA => [
  237. 'link_id' => (int) $link_id,
  238. ],
  239. SE_USER => (int) api_get_user_id(),
  240. ];
  241. $ic_slide->xapian_data = serialize($xapian_data);
  242. $description = $all_specific_terms.' '.$description;
  243. $ic_slide->addValue('content', $description);
  244. // Add category name if set.
  245. if (isset($selectcategory) && $selectcategory > 0) {
  246. $table_link_category = Database::get_course_table(
  247. TABLE_LINK_CATEGORY
  248. );
  249. $sql_cat = 'SELECT * FROM %s WHERE id=%d AND c_id = %d LIMIT 1';
  250. $sql_cat = sprintf(
  251. $sql_cat,
  252. $table_link_category,
  253. (int) $selectcategory,
  254. $course_int_id
  255. );
  256. $result = Database:: query($sql_cat);
  257. if (Database:: num_rows($result) == 1) {
  258. $row = Database:: fetch_array($result);
  259. $ic_slide->addValue(
  260. 'category',
  261. $row['category_title']
  262. );
  263. }
  264. }
  265. $di = new ChamiloIndexer();
  266. isset($_POST['language']) ? $lang = Database:: escape_string(
  267. $_POST['language']
  268. ) : $lang = 'english';
  269. $di->connectDb(null, null, $lang);
  270. $di->addChunk($ic_slide);
  271. // Index and return search engine document id.
  272. $did = $di->index();
  273. if ($did) {
  274. // Save it to db.
  275. $tbl_se_ref = Database::get_main_table(
  276. TABLE_MAIN_SEARCH_ENGINE_REF
  277. );
  278. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  279. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  280. $sql = sprintf(
  281. $sql,
  282. $tbl_se_ref,
  283. $course_int_id,
  284. $courseCode,
  285. TOOL_LINK,
  286. $link_id,
  287. $did
  288. );
  289. Database:: query($sql);
  290. }
  291. }
  292. Display::addFlash(Display::return_message(get_lang('LinkAdded')));
  293. return $link_id;
  294. }
  295. } elseif ($type == 'category') {
  296. $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
  297. $category_title = trim($_POST['category_title']);
  298. $description = trim($_POST['description']);
  299. if (empty($category_title)) {
  300. echo Display::return_message(get_lang('GiveCategoryName'), 'error');
  301. $ok = false;
  302. } else {
  303. // Looking for the largest order number for this category.
  304. $result = Database:: query(
  305. "SELECT MAX(display_order) FROM $tbl_categories
  306. WHERE c_id = $course_id "
  307. );
  308. list($orderMax) = Database:: fetch_row($result);
  309. $order = $orderMax + 1;
  310. $order = intval($order);
  311. $session_id = api_get_session_id();
  312. $params = [
  313. 'c_id' => $course_id,
  314. 'category_title' => $category_title,
  315. 'description' => $description,
  316. 'display_order' => $order,
  317. 'session_id' => $session_id,
  318. ];
  319. $linkId = Database::insert($tbl_categories, $params);
  320. if ($linkId) {
  321. // iid
  322. $sql = "UPDATE $tbl_categories SET id = iid WHERE iid = $linkId";
  323. Database:: query($sql);
  324. // add link_category visibility
  325. // course ID is taken from context in api_set_default_visibility
  326. //api_set_default_visibility($linkId, TOOL_LINK_CATEGORY);
  327. api_item_property_update(
  328. $_course,
  329. TOOL_LINK_CATEGORY,
  330. $linkId,
  331. 'LinkCategoryAdded',
  332. api_get_user_id()
  333. );
  334. api_set_default_visibility($linkId, TOOL_LINK_CATEGORY);
  335. }
  336. Display::addFlash(Display::return_message(get_lang('CategoryAdded')));
  337. return $linkId;
  338. }
  339. }
  340. return $ok;
  341. }
  342. /**
  343. * Used to delete a link or a category.
  344. *
  345. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  346. *
  347. * @param int $id
  348. * @param string $type The type of item to delete
  349. *
  350. * @return bool
  351. */
  352. public static function deletelinkcategory($id, $type)
  353. {
  354. $courseInfo = api_get_course_info();
  355. $tbl_link = Database::get_course_table(TABLE_LINK);
  356. $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
  357. $course_id = $courseInfo['real_id'];
  358. $id = intval($id);
  359. if (empty($id)) {
  360. return false;
  361. }
  362. $result = false;
  363. switch ($type) {
  364. case 'link':
  365. // -> Items are no longer physically deleted,
  366. // but the visibility is set to 2 (in item_property).
  367. // This will make a restore function possible for the platform administrator.
  368. $sql = "UPDATE $tbl_link SET on_homepage='0'
  369. WHERE c_id = $course_id AND id='".$id."'";
  370. Database:: query($sql);
  371. api_item_property_update(
  372. $courseInfo,
  373. TOOL_LINK,
  374. $id,
  375. 'delete',
  376. api_get_user_id()
  377. );
  378. self::delete_link_from_search_engine(api_get_course_id(), $id);
  379. Skill::deleteSkillsFromItem($id, ITEM_TYPE_LINK);
  380. Display::addFlash(Display::return_message(get_lang('LinkDeleted')));
  381. $result = true;
  382. break;
  383. case 'category':
  384. // First we delete the category itself and afterwards all the links of this category.
  385. $sql = "DELETE FROM ".$tbl_categories."
  386. WHERE c_id = $course_id AND id='".$id."'";
  387. Database:: query($sql);
  388. $sql = "DELETE FROM ".$tbl_link."
  389. WHERE c_id = $course_id AND category_id='".$id."'";
  390. Database:: query($sql);
  391. api_item_property_update(
  392. $courseInfo,
  393. TOOL_LINK_CATEGORY,
  394. $id,
  395. 'delete',
  396. api_get_user_id()
  397. );
  398. Display::addFlash(Display::return_message(get_lang('CategoryDeleted')));
  399. $result = true;
  400. break;
  401. }
  402. return $result;
  403. }
  404. /**
  405. * Removes a link from search engine database.
  406. *
  407. * @param string $course_id Course code
  408. * @param int $link_id Document id to delete
  409. */
  410. public static function delete_link_from_search_engine($course_id, $link_id)
  411. {
  412. // Remove from search engine if enabled.
  413. if (api_get_setting('search_enabled') === 'true') {
  414. $tbl_se_ref = Database::get_main_table(
  415. TABLE_MAIN_SEARCH_ENGINE_REF
  416. );
  417. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  418. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
  419. $res = Database:: query($sql);
  420. if (Database:: num_rows($res) > 0) {
  421. $row = Database::fetch_array($res);
  422. $di = new ChamiloIndexer();
  423. $di->remove_document($row['search_did']);
  424. }
  425. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  426. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
  427. Database:: query($sql);
  428. // Remove terms from db.
  429. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  430. delete_all_values_for_item($course_id, TOOL_DOCUMENT, $link_id);
  431. }
  432. }
  433. /**
  434. * Get link info.
  435. *
  436. * @param int $id
  437. *
  438. * @return array link info
  439. */
  440. public static function getLinkInfo($id)
  441. {
  442. $tbl_link = Database::get_course_table(TABLE_LINK);
  443. $course_id = api_get_course_int_id();
  444. if (empty($id) || empty($course_id)) {
  445. return [];
  446. }
  447. $sql = "SELECT * FROM $tbl_link
  448. WHERE c_id = $course_id AND id='".intval($id)."' ";
  449. $result = Database::query($sql);
  450. $data = [];
  451. if (Database::num_rows($result)) {
  452. $data = Database::fetch_array($result);
  453. }
  454. return $data;
  455. }
  456. /**
  457. * @param int $id
  458. * @param array $values
  459. */
  460. public static function editLink($id, $values = [])
  461. {
  462. $tbl_link = Database::get_course_table(TABLE_LINK);
  463. $_course = api_get_course_info();
  464. $course_id = $_course['real_id'];
  465. $id = intval($id);
  466. $values['url'] = trim($values['url']);
  467. $values['title'] = trim($values['title']);
  468. $values['description'] = trim($values['description']);
  469. $values['target'] = empty($values['target']) ? '_self' : $values['target'];
  470. $values['on_homepage'] = isset($values['on_homepage']) ? $values['on_homepage'] : '';
  471. $categoryId = intval($values['category_id']);
  472. // We ensure URL to be absolute.
  473. if (strpos($values['url'], '://') === false) {
  474. $values['url'] = 'http://'.$_POST['url'];
  475. }
  476. // If the title is empty, we use the URL as title.
  477. if ($values['title'] == '') {
  478. $values['title'] = $values['url'];
  479. }
  480. // If the URL is invalid, an error occurs.
  481. if (!api_valid_url($values['url'], true)) {
  482. Display::addFlash(
  483. Display::return_message(get_lang('GiveURL'), 'error')
  484. );
  485. return false;
  486. }
  487. if (empty($id) || empty($course_id)) {
  488. return false;
  489. }
  490. // Finding the old category_id.
  491. $sql = "SELECT * FROM $tbl_link
  492. WHERE c_id = $course_id AND id='".$id."'";
  493. $result = Database:: query($sql);
  494. $row = Database:: fetch_array($result);
  495. $category_id = $row['category_id'];
  496. if ($category_id != $values['category_id']) {
  497. $sql = "SELECT MAX(display_order)
  498. FROM $tbl_link
  499. WHERE
  500. c_id = $course_id AND
  501. category_id='".intval($values['category_id'])."'";
  502. $result = Database:: query($sql);
  503. list($max_display_order) = Database:: fetch_row($result);
  504. $max_display_order++;
  505. } else {
  506. $max_display_order = $row['display_order'];
  507. }
  508. $params = [
  509. 'url' => $values['url'],
  510. 'title' => $values['title'],
  511. 'description' => $values['description'],
  512. 'category_id' => $values['category_id'],
  513. 'display_order' => $max_display_order,
  514. 'on_homepage' => $values['on_homepage'],
  515. 'target' => $values['target'],
  516. ];
  517. Database::update(
  518. $tbl_link,
  519. $params,
  520. ['c_id = ? AND id = ?' => [$course_id, $id]]
  521. );
  522. // Update search enchine and its values table if enabled.
  523. if (api_get_setting('search_enabled') == 'true') {
  524. $course_int_id = api_get_course_int_id();
  525. $course_id = api_get_course_id();
  526. $link_title = Database:: escape_string($values['title']);
  527. $link_description = Database:: escape_string($values['description']);
  528. // Actually, it consists on delete terms from db,
  529. // insert new ones, create a new search engine document, and remove the old one.
  530. // Get search_did.
  531. $tbl_se_ref = Database::get_main_table(
  532. TABLE_MAIN_SEARCH_ENGINE_REF
  533. );
  534. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  535. $sql = sprintf(
  536. $sql,
  537. $tbl_se_ref,
  538. $course_id,
  539. TOOL_LINK,
  540. $id
  541. );
  542. $res = Database:: query($sql);
  543. if (Database:: num_rows($res) > 0) {
  544. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  545. $se_ref = Database:: fetch_array($res);
  546. $specific_fields = get_specific_field_list();
  547. $ic_slide = new IndexableChunk();
  548. $all_specific_terms = '';
  549. foreach ($specific_fields as $specific_field) {
  550. delete_all_specific_field_value(
  551. $course_id,
  552. $specific_field['id'],
  553. TOOL_LINK,
  554. $id
  555. );
  556. if (isset($_REQUEST[$specific_field['code']])) {
  557. $sterms = trim(
  558. $_REQUEST[$specific_field['code']]
  559. );
  560. if (!empty($sterms)) {
  561. $all_specific_terms .= ' '.$sterms;
  562. $sterms = explode(',', $sterms);
  563. foreach ($sterms as $sterm) {
  564. $ic_slide->addTerm(
  565. trim($sterm),
  566. $specific_field['code']
  567. );
  568. add_specific_field_value(
  569. $specific_field['id'],
  570. $course_id,
  571. TOOL_LINK,
  572. $id,
  573. $sterm
  574. );
  575. }
  576. }
  577. }
  578. }
  579. // Build the chunk to index.
  580. $ic_slide->addValue("title", $link_title);
  581. $ic_slide->addCourseId($course_id);
  582. $ic_slide->addToolId(TOOL_LINK);
  583. $xapian_data = [
  584. SE_COURSE_ID => $course_id,
  585. SE_TOOL_ID => TOOL_LINK,
  586. SE_DATA => [
  587. 'link_id' => (int) $id,
  588. ],
  589. SE_USER => (int) api_get_user_id(),
  590. ];
  591. $ic_slide->xapian_data = serialize($xapian_data);
  592. $link_description = $all_specific_terms.' '.$link_description;
  593. $ic_slide->addValue('content', $link_description);
  594. // Add category name if set.
  595. if (isset($categoryId) && $categoryId > 0) {
  596. $table_link_category = Database::get_course_table(
  597. TABLE_LINK_CATEGORY
  598. );
  599. $sql_cat = 'SELECT * FROM %s WHERE id=%d and c_id = %d LIMIT 1';
  600. $sql_cat = sprintf(
  601. $sql_cat,
  602. $table_link_category,
  603. $categoryId,
  604. $course_int_id
  605. );
  606. $result = Database:: query($sql_cat);
  607. if (Database:: num_rows($result) == 1) {
  608. $row = Database:: fetch_array($result);
  609. $ic_slide->addValue(
  610. 'category',
  611. $row['category_title']
  612. );
  613. }
  614. }
  615. $di = new ChamiloIndexer();
  616. isset($_POST['language']) ? $lang = Database:: escape_string($_POST['language']) : $lang = 'english';
  617. $di->connectDb(null, null, $lang);
  618. $di->remove_document($se_ref['search_did']);
  619. $di->addChunk($ic_slide);
  620. // Index and return search engine document id.
  621. $did = $di->index();
  622. if ($did) {
  623. // Save it to db.
  624. $sql = 'DELETE FROM %s
  625. WHERE course_code=\'%s\'
  626. AND tool_id=\'%s\'
  627. AND ref_id_high_level=\'%s\'';
  628. $sql = sprintf(
  629. $sql,
  630. $tbl_se_ref,
  631. $course_id,
  632. TOOL_LINK,
  633. $id
  634. );
  635. Database:: query($sql);
  636. $sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did)
  637. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  638. $sql = sprintf(
  639. $sql,
  640. $tbl_se_ref,
  641. $course_int_id,
  642. $course_id,
  643. TOOL_LINK,
  644. $id,
  645. $did
  646. );
  647. Database:: query($sql);
  648. }
  649. }
  650. }
  651. // "WHAT'S NEW" notification: update table last_toolEdit.
  652. api_item_property_update(
  653. $_course,
  654. TOOL_LINK,
  655. $id,
  656. 'LinkUpdated',
  657. api_get_user_id()
  658. );
  659. Display::addFlash(Display::return_message(get_lang('LinkModded')));
  660. }
  661. /**
  662. * @param int $id
  663. * @param array $values
  664. *
  665. * @return bool
  666. */
  667. public static function editCategory($id, $values)
  668. {
  669. $table = Database::get_course_table(TABLE_LINK_CATEGORY);
  670. $course_id = api_get_course_int_id();
  671. $id = intval($id);
  672. // This is used to put the modified info of the category-form into the database.
  673. $params = [
  674. 'category_title' => $values['category_title'],
  675. 'description' => $values['description'],
  676. ];
  677. Database::update(
  678. $table,
  679. $params,
  680. ['c_id = ? AND id = ?' => [$course_id, $id]]
  681. );
  682. Display::addFlash(Display::return_message(get_lang('CategoryModded')));
  683. return true;
  684. }
  685. /**
  686. * Changes the visibility of a link.
  687. *
  688. * @todo add the changing of the visibility of a course
  689. *
  690. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  691. */
  692. public static function change_visibility_link($id, $scope)
  693. {
  694. $_course = api_get_course_info();
  695. $_user = api_get_user_info();
  696. if ($scope == TOOL_LINK) {
  697. api_item_property_update(
  698. $_course,
  699. TOOL_LINK,
  700. $id,
  701. $_GET['action'],
  702. $_user['user_id']
  703. );
  704. Display::addFlash(Display::return_message(get_lang('VisibilityChanged')));
  705. } elseif ($scope == TOOL_LINK_CATEGORY) {
  706. api_item_property_update(
  707. $_course,
  708. TOOL_LINK_CATEGORY,
  709. $id,
  710. $_GET['action'],
  711. $_user['user_id']
  712. );
  713. Display::addFlash(Display::return_message(get_lang('VisibilityChanged')));
  714. }
  715. }
  716. /**
  717. * Generate SQL to select all the links categories in the current course and
  718. * session.
  719. *
  720. * @param int $courseId
  721. * @param int $sessionId
  722. * @param bool $withBaseContent
  723. *
  724. * @return array
  725. */
  726. public static function getLinkCategories($courseId, $sessionId, $withBaseContent = true)
  727. {
  728. $tblLinkCategory = Database::get_course_table(TABLE_LINK_CATEGORY);
  729. $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  730. $courseId = intval($courseId);
  731. $courseInfo = api_get_course_info_by_id($courseId);
  732. // Condition for the session.
  733. $sessionCondition = api_get_session_condition(
  734. $sessionId,
  735. true,
  736. $withBaseContent,
  737. 'linkcat.session_id'
  738. );
  739. // Getting links
  740. $sql = "SELECT *, linkcat.id
  741. FROM $tblLinkCategory linkcat
  742. WHERE
  743. linkcat.c_id = $courseId
  744. $sessionCondition
  745. ORDER BY linkcat.display_order DESC";
  746. $result = Database::query($sql);
  747. $categories = Database::store_result($result);
  748. $sql = "SELECT *, linkcat.id
  749. FROM $tblLinkCategory linkcat
  750. INNER JOIN $tblItemProperty ip
  751. ON (linkcat.id = ip.ref AND linkcat.c_id = ip.c_id)
  752. WHERE
  753. ip.tool = '".TOOL_LINK_CATEGORY."' AND
  754. (ip.visibility = '0' OR ip.visibility = '1')
  755. $sessionCondition AND
  756. linkcat.c_id = ".$courseId."
  757. ORDER BY linkcat.display_order DESC";
  758. $result = Database::query($sql);
  759. $categoryInItemProperty = [];
  760. if (Database::num_rows($result)) {
  761. while ($row = Database::fetch_array($result, 'ASSOC')) {
  762. $categoryInItemProperty[$row['id']] = $row;
  763. }
  764. }
  765. foreach ($categories as &$category) {
  766. if (!isset($categoryInItemProperty[$category['id']])) {
  767. api_item_property_update(
  768. $courseInfo,
  769. TOOL_LINK_CATEGORY,
  770. $category['id'],
  771. 'LinkCategoryAdded',
  772. api_get_user_id()
  773. );
  774. }
  775. }
  776. $sql = "SELECT DISTINCT linkcat.*, visibility
  777. FROM $tblLinkCategory linkcat
  778. INNER JOIN $tblItemProperty ip
  779. ON (linkcat.id = ip.ref AND linkcat.c_id = ip.c_id)
  780. WHERE
  781. ip.tool = '".TOOL_LINK_CATEGORY."' AND
  782. (ip.visibility = '0' OR ip.visibility = '1')
  783. $sessionCondition AND
  784. linkcat.c_id = ".$courseId."
  785. ORDER BY linkcat.display_order DESC
  786. ";
  787. $result = Database::query($sql);
  788. return Database::store_result($result, 'ASSOC');
  789. }
  790. /**
  791. * @param int $categoryId
  792. * @param $courseId
  793. * @param $sessionId
  794. * @param bool $withBaseContent
  795. *
  796. * @return array
  797. */
  798. public static function getLinksPerCategory(
  799. $categoryId,
  800. $courseId,
  801. $sessionId,
  802. $withBaseContent = true
  803. ) {
  804. $tbl_link = Database::get_course_table(TABLE_LINK);
  805. $TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  806. $courseId = (int) $courseId;
  807. $sessionId = (int) $sessionId;
  808. $categoryId = (int) $categoryId;
  809. // Condition for the session.
  810. $condition_session = api_get_session_condition(
  811. $sessionId,
  812. true,
  813. false,
  814. 'ip.session_id'
  815. );
  816. if (!empty($sessionId)) {
  817. $conditionBaseSession = api_get_session_condition(
  818. 0,
  819. true,
  820. $withBaseContent,
  821. 'ip.session_id'
  822. );
  823. $condition = " AND
  824. (
  825. (ip.visibility = '1' $conditionBaseSession) OR
  826. (
  827. (ip.visibility = '0' OR ip.visibility = '1')
  828. $condition_session
  829. )
  830. )
  831. ";
  832. } else {
  833. $condition = api_get_session_condition(
  834. 0,
  835. true,
  836. false,
  837. 'ip.session_id'
  838. );
  839. $condition .= " AND (ip.visibility = '0' OR ip.visibility = '1') $condition ";
  840. }
  841. $sql = "SELECT
  842. link.id,
  843. ip.session_id,
  844. link.session_id link_session_id,
  845. url,
  846. category_id,
  847. visibility,
  848. description,
  849. title,
  850. target,
  851. on_homepage
  852. FROM $tbl_link link
  853. INNER JOIN $TABLE_ITEM_PROPERTY ip
  854. ON (link.id = ip.ref AND link.c_id = ip.c_id)
  855. WHERE
  856. ip.tool = '".TOOL_LINK."' AND
  857. link.category_id = '".$categoryId."' AND
  858. link.c_id = $courseId AND
  859. ip.c_id = $courseId
  860. $condition
  861. ORDER BY link.display_order ASC, ip.session_id DESC";
  862. $result = Database:: query($sql);
  863. return Database::store_result($result);
  864. }
  865. /**
  866. * Displays all the links of a given category.
  867. *
  868. * @param int $catid
  869. * @param int $courseId
  870. * @param int $session_id
  871. * @param bool $showActionLinks
  872. *
  873. * @return string
  874. *
  875. * @author Julio Montoya
  876. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  877. */
  878. public static function showLinksPerCategory($catid, $courseId, $session_id, $showActionLinks = true)
  879. {
  880. global $token;
  881. $_user = api_get_user_info();
  882. $catid = (int) $catid;
  883. $links = self::getLinksPerCategory($catid, $courseId, $session_id);
  884. $content = '';
  885. $numberOfLinks = count($links);
  886. if (!empty($links)) {
  887. $content .= '<div class="link list-group">';
  888. $i = 1;
  889. $linksAdded = [];
  890. foreach ($links as $myrow) {
  891. $linkId = $myrow['id'];
  892. if (in_array($linkId, $linksAdded)) {
  893. continue;
  894. }
  895. $linksAdded[] = $linkId;
  896. $categoryId = $myrow['category_id'];
  897. // Validation when belongs to a session.
  898. $session_img = api_get_session_image(
  899. $myrow['link_session_id'],
  900. $_user['status']
  901. );
  902. $toolbar = '';
  903. $link_validator = '';
  904. if (api_is_allowed_to_edit(null, true)) {
  905. $toolbar .= Display::toolbarButton(
  906. '',
  907. 'javascript:void(0);',
  908. 'check-circle-o',
  909. 'default btn-sm',
  910. [
  911. 'onclick' => "check_url('".$linkId."', '".addslashes($myrow['url'])."');",
  912. 'title' => get_lang('CheckURL'),
  913. ]
  914. );
  915. $link_validator .= Display::span(
  916. '',
  917. [
  918. 'id' => 'url_id_'.$linkId,
  919. 'class' => 'check-link',
  920. ]
  921. );
  922. if ($session_id == $myrow['link_session_id']) {
  923. $url = api_get_self().'?'.api_get_cidreq().'&action=editlink&id='.$linkId;
  924. $title = get_lang('Edit');
  925. $toolbar .= Display::toolbarButton(
  926. '',
  927. $url,
  928. 'pencil',
  929. 'default btn-sm',
  930. [
  931. 'title' => $title,
  932. ]
  933. );
  934. }
  935. $urlVisibility = api_get_self().'?'.api_get_cidreq().
  936. '&sec_token='.$token.
  937. '&id='.$linkId.
  938. '&scope=link&category_id='.$categoryId;
  939. switch ($myrow['visibility']) {
  940. case '1':
  941. $urlVisibility .= '&action=invisible';
  942. $title = get_lang('MakeInvisible');
  943. $toolbar .= Display::toolbarButton(
  944. '',
  945. $urlVisibility,
  946. 'eye',
  947. 'default btn-sm',
  948. [
  949. 'title' => $title,
  950. ]
  951. );
  952. break;
  953. case '0':
  954. $urlVisibility .= '&action=visible';
  955. $title = get_lang('MakeVisible');
  956. $toolbar .= Display::toolbarButton(
  957. '',
  958. $urlVisibility,
  959. 'eye-slash',
  960. 'primary btn-sm',
  961. [
  962. 'title' => $title,
  963. ]
  964. );
  965. break;
  966. }
  967. if ($session_id == $myrow['link_session_id']) {
  968. $moveLinkParams = [
  969. 'id' => $linkId,
  970. 'scope' => 'category',
  971. 'category_id' => $categoryId,
  972. 'action' => 'move_link_up',
  973. ];
  974. $toolbar .= Display::toolbarButton(
  975. get_lang('MoveUp'),
  976. api_get_self().'?'.api_get_cidreq().'&'.http_build_query($moveLinkParams),
  977. 'level-up',
  978. 'default',
  979. ['class' => 'btn-sm '.($i === 1 ? 'disabled' : '')],
  980. false
  981. );
  982. $moveLinkParams['action'] = 'move_link_down';
  983. $toolbar .= Display::toolbarButton(
  984. get_lang('MoveDown'),
  985. api_get_self().'?'.api_get_cidreq().'&'.http_build_query($moveLinkParams),
  986. 'level-down',
  987. 'default',
  988. ['class' => 'btn-sm '.($i === $numberOfLinks ? 'disabled' : '')],
  989. false
  990. );
  991. $url = api_get_self().'?'.api_get_cidreq().'&sec_token='.$token.'&action=deletelink&id='.$linkId.'&category_id='.$categoryId;
  992. $event = "javascript: if(!confirm('".get_lang('LinkDelconfirm')."'))return false;";
  993. $title = get_lang('Delete');
  994. $toolbar .= Display::toolbarButton(
  995. '',
  996. $url,
  997. 'trash',
  998. 'default btn-sm',
  999. [
  1000. 'onclick' => $event,
  1001. 'title' => $title,
  1002. ]
  1003. );
  1004. }
  1005. }
  1006. $showLink = false;
  1007. $titleClass = '';
  1008. if ($myrow['visibility'] == '1') {
  1009. $showLink = true;
  1010. } else {
  1011. if (api_is_allowed_to_edit(null, true)) {
  1012. $showLink = true;
  1013. $titleClass = 'text-muted';
  1014. }
  1015. }
  1016. if ($showLink) {
  1017. $iconLink = Display::return_icon(
  1018. 'url.png',
  1019. get_lang('Link'),
  1020. null,
  1021. ICON_SIZE_SMALL
  1022. );
  1023. $url = api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$linkId.'&link_url='.urlencode($myrow['url']);
  1024. $content .= '<div class="list-group-item">';
  1025. if ($showActionLinks) {
  1026. $content .= '<div class="pull-right"><div class="btn-group">'.$toolbar.'</div></div>';
  1027. }
  1028. $content .= '<h4 class="list-group-item-heading">';
  1029. $content .= $iconLink;
  1030. $content .= Display::tag(
  1031. 'a',
  1032. Security::remove_XSS($myrow['title']),
  1033. [
  1034. 'href' => $url,
  1035. 'target' => $myrow['target'],
  1036. 'class' => $titleClass,
  1037. ]
  1038. );
  1039. $content .= $link_validator;
  1040. $content .= $session_img;
  1041. $content .= '</h4>';
  1042. $content .= '<p class="list-group-item-text">'.$myrow['description'].'</p>';
  1043. $content .= '</div>';
  1044. }
  1045. $i++;
  1046. }
  1047. $content .= '</div>';
  1048. }
  1049. return $content;
  1050. }
  1051. /**
  1052. * Displays the edit, delete and move icons.
  1053. *
  1054. * @param int Category ID
  1055. * @param int $currentCategory
  1056. * @param int $countCategories
  1057. *
  1058. * @return string
  1059. *
  1060. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1061. */
  1062. public static function showCategoryAdminTools($category, $currentCategory, $countCategories)
  1063. {
  1064. $categoryId = $category['id'];
  1065. $token = null;
  1066. $tools = '<a href="'.api_get_self().'?'.api_get_cidreq().'&sec_token='.$token.'&action=editcategory&id='.$categoryId.'&category_id='.$categoryId.'" title='.get_lang('Modify').'">'.
  1067. Display:: return_icon(
  1068. 'edit.png',
  1069. get_lang('Modify'),
  1070. [],
  1071. ICON_SIZE_SMALL
  1072. ).'</a>';
  1073. // DISPLAY MOVE UP COMMAND only if it is not the top link.
  1074. if ($currentCategory != 0) {
  1075. $tools .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&sec_token='.$token.'&action=up&up='.$categoryId.'&category_id='.$categoryId.'" title="'.get_lang('Up').'">'.
  1076. Display:: return_icon(
  1077. 'up.png',
  1078. get_lang('Up'),
  1079. [],
  1080. ICON_SIZE_SMALL
  1081. ).'</a>';
  1082. } else {
  1083. $tools .= Display:: return_icon(
  1084. 'up_na.png',
  1085. get_lang('Up'),
  1086. [],
  1087. ICON_SIZE_SMALL
  1088. ).'</a>';
  1089. }
  1090. // DISPLAY MOVE DOWN COMMAND only if it is not the bottom link.
  1091. if ($currentCategory < $countCategories - 1) {
  1092. $tools .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&sec_token='.$token.'&action=down&down='.$categoryId.'&category_id='.$categoryId.'">'.
  1093. Display:: return_icon(
  1094. 'down.png',
  1095. get_lang('Down'),
  1096. [],
  1097. ICON_SIZE_SMALL
  1098. ).'</a>';
  1099. } else {
  1100. $tools .= Display:: return_icon(
  1101. 'down_na.png',
  1102. get_lang('Down'),
  1103. [],
  1104. ICON_SIZE_SMALL
  1105. ).'</a>';
  1106. }
  1107. $tools .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&sec_token='.$token.'&action=deletecategory&id='.$categoryId."&category_id=$categoryId\"
  1108. onclick=\"javascript: if(!confirm('".get_lang('CategoryDelconfirm')."')) return false;\">".
  1109. Display:: return_icon(
  1110. 'delete.png',
  1111. get_lang('Delete'),
  1112. [],
  1113. ICON_SIZE_SMALL
  1114. ).'</a>';
  1115. return $tools;
  1116. }
  1117. /**
  1118. * move a link or a linkcategory up or down.
  1119. *
  1120. * @param int Category ID
  1121. * @param int Course ID
  1122. * @param int Session ID
  1123. *
  1124. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1125. *
  1126. * @todo support sessions
  1127. */
  1128. public static function movecatlink($action, $catlinkid, $courseId = null, $sessionId = null)
  1129. {
  1130. $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
  1131. if (is_null($courseId)) {
  1132. $courseId = api_get_course_int_id();
  1133. }
  1134. $courseId = intval($courseId);
  1135. if (is_null($sessionId)) {
  1136. $sessionId = api_get_session_id();
  1137. }
  1138. $sessionId = intval($sessionId);
  1139. $thiscatlinkId = intval($catlinkid);
  1140. if ($action == 'down') {
  1141. $sortDirection = 'DESC';
  1142. }
  1143. if ($action == 'up') {
  1144. $sortDirection = 'ASC';
  1145. }
  1146. $movetable = $tbl_categories;
  1147. if (!empty($sortDirection)) {
  1148. if (!in_array(trim(strtoupper($sortDirection)), ['ASC', 'DESC'])) {
  1149. $sortDirection = 'ASC';
  1150. }
  1151. $sql = "SELECT id, display_order FROM $movetable
  1152. WHERE c_id = $courseId
  1153. ORDER BY display_order $sortDirection";
  1154. $linkresult = Database:: query($sql);
  1155. $thislinkOrder = 1;
  1156. while ($sortrow = Database:: fetch_array($linkresult)) {
  1157. // STEP 2 : FOUND THE NEXT LINK ID AND ORDER, COMMIT SWAP
  1158. // This part seems unlogic, but it isn't . We first look for the current link with the querystring ID
  1159. // and we know the next iteration of the while loop is the next one. These should be swapped.
  1160. if (isset($thislinkFound) && $thislinkFound) {
  1161. $nextlinkId = $sortrow['id'];
  1162. $nextlinkOrder = $sortrow['display_order'];
  1163. Database:: query(
  1164. "UPDATE ".$movetable."
  1165. SET display_order = '$nextlinkOrder'
  1166. WHERE c_id = $courseId AND id = '$thiscatlinkId'"
  1167. );
  1168. Database:: query(
  1169. "UPDATE ".$movetable."
  1170. SET display_order = '$thislinkOrder'
  1171. WHERE c_id = $courseId AND id = '$nextlinkId'"
  1172. );
  1173. break;
  1174. }
  1175. if ($sortrow['id'] == $thiscatlinkId) {
  1176. $thislinkOrder = $sortrow['display_order'];
  1177. $thislinkFound = true;
  1178. }
  1179. }
  1180. }
  1181. Display::addFlash(Display::return_message(get_lang('LinkMoved')));
  1182. }
  1183. /**
  1184. * This function checks if the url is a vimeo link.
  1185. *
  1186. * @author Julio Montoya
  1187. *
  1188. * @version 1.0
  1189. */
  1190. public static function isVimeoLink($url)
  1191. {
  1192. $isLink = strrpos($url, 'vimeo.com');
  1193. return $isLink;
  1194. }
  1195. /**
  1196. * Get vimeo id from URL.
  1197. *
  1198. * @param string $url
  1199. *
  1200. * @return bool|mixed
  1201. */
  1202. public static function getVimeoLinkId($url)
  1203. {
  1204. $possibleUrls = [
  1205. 'http://www.vimeo.com/',
  1206. 'http://vimeo.com/',
  1207. 'https://www.vimeo.com/',
  1208. 'https://vimeo.com/',
  1209. ];
  1210. $url = str_replace($possibleUrls, '', $url);
  1211. if (is_numeric($url)) {
  1212. return $url;
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * This function checks if the url is a youtube link.
  1218. *
  1219. * @author Jorge Frisancho
  1220. * @author Julio Montoya - Fixing code
  1221. *
  1222. * @version 1.0
  1223. */
  1224. public static function is_youtube_link($url)
  1225. {
  1226. $is_youtube_link = strrpos($url, 'youtube') || strrpos(
  1227. $url,
  1228. 'youtu.be'
  1229. );
  1230. return $is_youtube_link;
  1231. }
  1232. /**
  1233. * This function checks if the url is a PDF File link.
  1234. *
  1235. * @author Jorge Frisancho
  1236. * @author Alex Aragón - Fixing code
  1237. *
  1238. * @version 1.0
  1239. */
  1240. public static function isPdfLink($url)
  1241. {
  1242. $isPdfLink = strrpos(strtolower($url), '.pdf');
  1243. return $isPdfLink;
  1244. }
  1245. /**
  1246. * Get youtube id from an URL.
  1247. *
  1248. * @param string $url
  1249. *
  1250. * @return string
  1251. */
  1252. public static function get_youtube_video_id($url)
  1253. {
  1254. // This is the length of YouTube's video IDs
  1255. $len = 11;
  1256. // The ID string starts after "v=", which is usually right after
  1257. // "youtube.com/watch?" in the URL
  1258. $pos = strpos($url, "v=");
  1259. $id = '';
  1260. //If false try other options
  1261. if ($pos === false) {
  1262. $url_parsed = parse_url($url);
  1263. //Youtube shortener
  1264. //http://youtu.be/ID
  1265. $pos = strpos($url, "youtu.be");
  1266. if ($pos == false) {
  1267. $id = '';
  1268. } else {
  1269. return substr($url_parsed['path'], 1);
  1270. }
  1271. //if empty try the youtube.com/embed/ID
  1272. if (empty($id)) {
  1273. $pos = strpos($url, "embed");
  1274. if ($pos === false) {
  1275. return '';
  1276. } else {
  1277. return substr($url_parsed['path'], 7);
  1278. }
  1279. }
  1280. } else {
  1281. // Offset the start location to match the beginning of the ID string
  1282. $pos += 2;
  1283. // Get the ID string and return it
  1284. $id = substr($url, $pos, $len);
  1285. return $id;
  1286. }
  1287. }
  1288. /**
  1289. * @param int $course_id
  1290. * @param int $session_id
  1291. * @param int $categoryId
  1292. * @param string $show
  1293. * @param null $token
  1294. * @param bool $showActionLinks
  1295. * @param bool $forceOpenCategories
  1296. *
  1297. * @return string
  1298. */
  1299. public static function listLinksAndCategories(
  1300. $course_id,
  1301. $session_id,
  1302. $categoryId,
  1303. $show = 'none',
  1304. $token = null,
  1305. $showActionLinks = true,
  1306. $forceOpenCategories = false
  1307. ) {
  1308. $categoryId = (int) $categoryId;
  1309. $content = '';
  1310. $categories = self::getLinkCategories($course_id, $session_id);
  1311. $countCategories = count($categories);
  1312. $linksPerCategory = self::showLinksPerCategory(0, $course_id, $session_id, $showActionLinks);
  1313. if ($showActionLinks) {
  1314. /* Action Links */
  1315. $content = '<div class="actions">';
  1316. if (api_is_allowed_to_edit(null, true)) {
  1317. $content .= '<a href="'.api_get_self().'?'.api_get_cidreq(
  1318. ).'&action=addlink&category_id='.$categoryId.'">'.
  1319. Display::return_icon('new_link.png', get_lang('LinkAdd'), '', ICON_SIZE_MEDIUM).'</a>';
  1320. $content .= '<a href="'.api_get_self().'?'.api_get_cidreq(
  1321. ).'&action=addcategory&category_id='.$categoryId.'">'.
  1322. Display::return_icon('new_folder.png', get_lang('CategoryAdd'), '', ICON_SIZE_MEDIUM).'</a>';
  1323. }
  1324. if (!empty($countCategories)) {
  1325. $content .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=list&show=none">';
  1326. $content .= Display::return_icon(
  1327. 'forum_listview.png',
  1328. get_lang('FlatView'),
  1329. '',
  1330. ICON_SIZE_MEDIUM
  1331. ).' </a>';
  1332. $content .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=list&show=all">';
  1333. $content .= Display::return_icon(
  1334. 'forum_nestedview.png',
  1335. get_lang('NestedView'),
  1336. '',
  1337. ICON_SIZE_MEDIUM
  1338. ).'</a>';
  1339. }
  1340. $content .= Display::url(
  1341. Display::return_icon('pdf.png', get_lang('ExportToPdf'), '', ICON_SIZE_MEDIUM),
  1342. api_get_self().'?'.api_get_cidreq().'&action=export'
  1343. );
  1344. $content .= '</div>';
  1345. }
  1346. if (empty($countCategories)) {
  1347. $content .= $linksPerCategory;
  1348. } else {
  1349. if (!empty($linksPerCategory)) {
  1350. $content .= Display::panel($linksPerCategory, get_lang('NoCategory'));
  1351. }
  1352. }
  1353. $counter = 0;
  1354. foreach ($categories as $myrow) {
  1355. // Student don't see invisible categories.
  1356. if (!api_is_allowed_to_edit(null, true)) {
  1357. if ($myrow['visibility'] == 0) {
  1358. continue;
  1359. }
  1360. }
  1361. // Validation when belongs to a session
  1362. $showChildren = $categoryId == $myrow['id'] || $show === 'all';
  1363. if ($forceOpenCategories) {
  1364. $showChildren = true;
  1365. }
  1366. $strVisibility = '';
  1367. $visibilityClass = null;
  1368. if ($myrow['visibility'] == '1') {
  1369. $strVisibility = '<a href="link.php?'.api_get_cidreq().'&sec_token='.$token.'&action=invisible&id='.$myrow['id'].'&scope='.TOOL_LINK_CATEGORY.'" title="'.get_lang('Hide').'">'.
  1370. Display::return_icon('visible.png', get_lang('Hide'), [], ICON_SIZE_SMALL).'</a>';
  1371. } elseif ($myrow['visibility'] == '0') {
  1372. $visibilityClass = 'text-muted';
  1373. $strVisibility = ' <a href="link.php?'.api_get_cidreq().'&sec_token='.$token.'&action=visible&id='.$myrow['id'].'&scope='.TOOL_LINK_CATEGORY.'" title="'.get_lang('Show').'">'.
  1374. Display::return_icon('invisible.png', get_lang('Show'), [], ICON_SIZE_SMALL).'</a>';
  1375. }
  1376. $header = '';
  1377. if ($showChildren) {
  1378. $header .= '<a class="'.$visibilityClass.'" href="'.api_get_self().'?'.api_get_cidreq().'&category_id=">';
  1379. $header .= Display::return_icon('forum_nestedview.png');
  1380. } else {
  1381. $header .= '<a class="'.$visibilityClass.'" href="'.api_get_self().'?'.api_get_cidreq().'&category_id='.$myrow['id'].'">';
  1382. $header .= Display::return_icon('forum_listview.png');
  1383. }
  1384. $header .= Security::remove_XSS($myrow['category_title']).'</a>';
  1385. if ($showActionLinks) {
  1386. if (api_is_allowed_to_edit(null, true)) {
  1387. if ($session_id == $myrow['session_id']) {
  1388. $header .= $strVisibility;
  1389. $header .= self::showCategoryAdminTools($myrow, $counter, count($categories));
  1390. } else {
  1391. $header .= get_lang('EditionNotAvailableFromSession');
  1392. }
  1393. }
  1394. }
  1395. $childrenContent = '';
  1396. if ($showChildren) {
  1397. $childrenContent = self::showLinksPerCategory(
  1398. $myrow['id'],
  1399. api_get_course_int_id(),
  1400. api_get_session_id()
  1401. );
  1402. }
  1403. $content .= Display::panel($myrow['description'].$childrenContent, $header);
  1404. $counter++;
  1405. }
  1406. return $content;
  1407. }
  1408. /**
  1409. * @param int $linkId
  1410. * @param string $action
  1411. * @param null $token
  1412. *
  1413. * @return FormValidator
  1414. */
  1415. public static function getLinkForm($linkId, $action, $token = null)
  1416. {
  1417. $course_id = api_get_course_int_id();
  1418. $session_id = api_get_session_id();
  1419. $linkInfo = self::getLinkInfo($linkId);
  1420. $categoryId = isset($linkInfo['category_id']) ? $linkInfo['category_id'] : '';
  1421. $lpId = isset($_GET['lp_id']) ? Security::remove_XSS($_GET['lp_id']) : null;
  1422. $form = new FormValidator(
  1423. 'link',
  1424. 'post',
  1425. api_get_self().'?action='.$action.
  1426. '&category_id='.$categoryId.
  1427. '&'.api_get_cidreq().
  1428. '&id='.$linkId.
  1429. '&sec_token='.$token
  1430. );
  1431. if ($action == 'addlink') {
  1432. $form->addHeader(get_lang('LinkAdd'));
  1433. } else {
  1434. $form->addHeader(get_lang('LinkMod'));
  1435. }
  1436. $target_link = '_blank';
  1437. $title = '';
  1438. $category = '';
  1439. $onhomepage = '';
  1440. $description = '';
  1441. if (!empty($linkInfo)) {
  1442. $urllink = $linkInfo['url'];
  1443. $title = $linkInfo['title'];
  1444. $description = $linkInfo['description'];
  1445. $category = $linkInfo['category_id'];
  1446. if ($linkInfo['on_homepage'] != 0) {
  1447. $onhomepage = 1;
  1448. }
  1449. $target_link = $linkInfo['target'];
  1450. }
  1451. $form->addHidden('id', $linkId);
  1452. $form->addText('url', 'URL');
  1453. $form->addRule('url', get_lang('GiveURL'), 'url');
  1454. $form->addText('title', get_lang('LinkName'));
  1455. $form->addTextarea('description', get_lang('Description'));
  1456. $resultcategories = self::getLinkCategories($course_id, $session_id);
  1457. $options = ['0' => '--'];
  1458. if (!empty($resultcategories)) {
  1459. foreach ($resultcategories as $myrow) {
  1460. $options[$myrow['id']] = $myrow['category_title'];
  1461. }
  1462. }
  1463. $form->addSelect('category_id', get_lang('Category'), $options);
  1464. $form->addCheckBox('on_homepage', null, get_lang('OnHomepage'));
  1465. $targets = [
  1466. '_self' => get_lang('LinkOpenSelf'),
  1467. '_blank' => get_lang('LinkOpenBlank'),
  1468. '_parent' => get_lang('LinkOpenParent'),
  1469. '_top' => get_lang('LinkOpenTop'),
  1470. ];
  1471. $form->addSelect(
  1472. 'target',
  1473. [
  1474. get_lang('LinkTarget'),
  1475. get_lang('AddTargetOfLinkOnHomepage'),
  1476. ],
  1477. $targets
  1478. );
  1479. $defaults = [
  1480. 'url' => empty($urllink) ? 'http://' : Security::remove_XSS($urllink),
  1481. 'title' => Security::remove_XSS($title),
  1482. 'category_id' => $category,
  1483. 'on_homepage' => $onhomepage,
  1484. 'description' => $description,
  1485. 'target' => $target_link,
  1486. ];
  1487. if (api_get_setting('search_enabled') == 'true') {
  1488. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1489. $specific_fields = get_specific_field_list();
  1490. $form->addCheckBox('index_document', get_lang('SearchFeatureDoIndexLink'), get_lang('Yes'));
  1491. foreach ($specific_fields as $specific_field) {
  1492. $default_values = '';
  1493. if ($action == 'editlink') {
  1494. $filter = [
  1495. 'field_id' => $specific_field['id'],
  1496. 'ref_id' => intval($_GET['id']),
  1497. 'tool_id' => '\''.TOOL_LINK.'\'',
  1498. ];
  1499. $values = get_specific_field_values_list($filter, ['value']);
  1500. if (!empty($values)) {
  1501. $arr_str_values = [];
  1502. foreach ($values as $value) {
  1503. $arr_str_values[] = $value['value'];
  1504. }
  1505. $default_values = implode(', ', $arr_str_values);
  1506. }
  1507. }
  1508. $form->addText($specific_field['name'], $specific_field['code']);
  1509. $defaults[$specific_field['name']] = $default_values;
  1510. }
  1511. }
  1512. $skillList = Skill::addSkillsToForm($form, ITEM_TYPE_LINK, $linkId);
  1513. $form->addHidden('lp_id', $lpId);
  1514. $form->addButtonSave(get_lang('SaveLink'), 'submitLink');
  1515. $defaults['skills'] = array_keys($skillList);
  1516. $form->setDefaults($defaults);
  1517. return $form;
  1518. }
  1519. /**
  1520. * @param int $id
  1521. * @param string $action
  1522. *
  1523. * @return FormValidator
  1524. */
  1525. public static function getCategoryForm($id, $action)
  1526. {
  1527. $id = (int) $id;
  1528. $action = Security::remove_XSS($action);
  1529. $form = new FormValidator(
  1530. 'category',
  1531. 'post',
  1532. api_get_self().'?action='.$action.'&'.api_get_cidreq()
  1533. );
  1534. $defaults = [];
  1535. if ($action == 'addcategory') {
  1536. $form->addHeader(get_lang('CategoryAdd'));
  1537. $my_cat_title = get_lang('CategoryAdd');
  1538. } else {
  1539. $form->addHeader(get_lang('CategoryMod'));
  1540. $my_cat_title = get_lang('CategoryMod');
  1541. $defaults = self::getCategory($id);
  1542. }
  1543. $form->addHidden('id', $id);
  1544. $form->addText('category_title', get_lang('CategoryName'));
  1545. $form->addTextarea('description', get_lang('Description'));
  1546. $form->addButtonSave($my_cat_title, 'submitCategory');
  1547. $form->setDefaults($defaults);
  1548. return $form;
  1549. }
  1550. /**
  1551. * @param int $id
  1552. *
  1553. * @return array
  1554. */
  1555. public static function getCategory($id)
  1556. {
  1557. $table = Database::get_course_table(TABLE_LINK_CATEGORY);
  1558. $id = (int) $id;
  1559. $courseId = api_get_course_int_id();
  1560. if (empty($id) || empty($courseId)) {
  1561. return [];
  1562. }
  1563. $sql = "SELECT * FROM $table
  1564. WHERE id = $id AND c_id = $courseId";
  1565. $result = Database::query($sql);
  1566. $category = Database::fetch_array($result, 'ASSOC');
  1567. return $category;
  1568. }
  1569. /**
  1570. * Move a link up in its category.
  1571. *
  1572. * @param int $id
  1573. *
  1574. * @return bool
  1575. */
  1576. public static function moveLinkUp($id)
  1577. {
  1578. return self::moveLinkDisplayOrder($id, 'ASC');
  1579. }
  1580. /**
  1581. * Move a link down in its category.
  1582. *
  1583. * @param int $id
  1584. *
  1585. * @return bool
  1586. */
  1587. public static function moveLinkDown($id)
  1588. {
  1589. return self::moveLinkDisplayOrder($id, 'DESC');
  1590. }
  1591. /**
  1592. * @param string $url
  1593. *
  1594. * @return bool
  1595. */
  1596. public static function checkUrl($url)
  1597. {
  1598. // Check if curl is available.
  1599. if (!in_array('curl', get_loaded_extensions())) {
  1600. return false;
  1601. }
  1602. // set URL and other appropriate options
  1603. $defaults = [
  1604. CURLOPT_URL => $url,
  1605. CURLOPT_FOLLOWLOCATION => true, // follow redirects accept youtube.com
  1606. CURLOPT_HEADER => 0,
  1607. CURLOPT_RETURNTRANSFER => true,
  1608. CURLOPT_TIMEOUT => 4,
  1609. ];
  1610. $proxySettings = api_get_configuration_value('proxy_settings');
  1611. if (!empty($proxySettings) &&
  1612. isset($proxySettings['curl_setopt_array'])
  1613. ) {
  1614. $defaults[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  1615. $defaults[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  1616. }
  1617. // Create a new cURL resource
  1618. $ch = curl_init();
  1619. curl_setopt_array($ch, $defaults);
  1620. // grab URL and pass it to the browser
  1621. ob_start();
  1622. $result = curl_exec($ch);
  1623. ob_get_clean();
  1624. // close cURL resource, and free up system resources
  1625. curl_close($ch);
  1626. return $result;
  1627. }
  1628. /**
  1629. * Move a link inside its category (display_order field).
  1630. *
  1631. * @param int $id The link ID
  1632. * @param string $direction The direction to sort the links
  1633. *
  1634. * @return bool
  1635. */
  1636. private static function moveLinkDisplayOrder($id, $direction)
  1637. {
  1638. $em = Database::getManager();
  1639. /** @var CLink $link */
  1640. $link = $em->find('ChamiloCourseBundle:CLink', $id);
  1641. if (!$link) {
  1642. return false;
  1643. }
  1644. $compareLinks = $em
  1645. ->getRepository('ChamiloCourseBundle:CLink')
  1646. ->findBy(
  1647. [
  1648. 'cId' => $link->getCId(),
  1649. 'categoryId' => $link->getCategoryId(),
  1650. ],
  1651. ['displayOrder' => $direction]
  1652. );
  1653. /** @var CLink $prevLink */
  1654. $prevLink = null;
  1655. /** @var CLink $compareLink */
  1656. foreach ($compareLinks as $compareLink) {
  1657. if ($compareLink->getId() !== $link->getId()) {
  1658. $prevLink = $compareLink;
  1659. continue;
  1660. }
  1661. if (!$prevLink) {
  1662. return false;
  1663. }
  1664. $newPrevLinkDisplayOrder = $link->getDisplayOrder();
  1665. $newLinkDisplayOrder = $prevLink->getDisplayOrder();
  1666. $link->setDisplayOrder($newLinkDisplayOrder);
  1667. $prevLink->setDisplayOrder($newPrevLinkDisplayOrder);
  1668. $em->merge($prevLink);
  1669. $em->merge($link);
  1670. break;
  1671. }
  1672. $em->flush();
  1673. return true;
  1674. }
  1675. }