....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 41.207.40.59  /  Your IP : 216.73.216.58
Web Server : Apache/2.4.52 (Ubuntu)
System : Linux srv-prod 5.15.0-157-generic #167-Ubuntu SMP Wed Sep 17 21:35:53 UTC 2025 x86_64
User : www-data ( 33)
PHP Version : 8.3.26
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/formation/h5p/tests/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/formation/h5p/tests/api_test.php
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Testing the H5P API.
 *
 * @package    core_h5p
 * @category   test
 * @copyright  2020 Sara Arjona <sara@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

declare(strict_types = 1);

namespace core_h5p;

use stdClass;

defined('MOODLE_INTERNAL') || die();

/**
 * Test class covering the H5P API.
 *
 * @package    core_h5p
 * @copyright  2020 Sara Arjona <sara@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @coversDefaultClass \core_h5p\api
 */
final class api_test extends \advanced_testcase {

    /**
     * Test the behaviour of delete_library().
     *
     * @dataProvider  delete_library_provider
     * @param  string $libraryname          Machine name of the library to delete.
     * @param  int    $expectedh5p          Total of H5P contents expected after deleting the library.
     * @param  int    $expectedlibraries    Total of H5P libraries expected after deleting the library.
     * @param  int    $expectedcontents     Total of H5P content_libraries expected after deleting the library.
     * @param  int    $expecteddependencies Total of H5P library dependencies expected after deleting the library.
     */
    public function test_delete_library(string $libraryname, int $expectedh5p, int $expectedlibraries,
            int $expectedcontents, int $expecteddependencies): void {
        global $DB;

        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();

        // Generate h5p related data.
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
        $generator->generate_h5p_data();
        $generator->create_library_record('H5P.TestingLibrary', 'TestingLibrary', 1, 0);

        // Check the current content in H5P tables is the expected.
        $counth5p = $DB->count_records('h5p');
        $counth5plibraries = $DB->count_records('h5p_libraries');
        $counth5pcontents = $DB->count_records('h5p_contents_libraries');
        $counth5pdependencies = $DB->count_records('h5p_library_dependencies');

        $this->assertSame(1, $counth5p);
        $this->assertSame(7, $counth5plibraries);
        $this->assertSame(5, $counth5pcontents);
        $this->assertSame(7, $counth5pdependencies);

        // Delete this library.
        $factory = new factory();
        $library = $DB->get_record('h5p_libraries', ['machinename' => $libraryname]);
        if ($library) {
            api::delete_library($factory, $library);
        }

        // Check the expected libraries and content have been removed.
        $counth5p = $DB->count_records('h5p');
        $counth5plibraries = $DB->count_records('h5p_libraries');
        $counth5pcontents = $DB->count_records('h5p_contents_libraries');
        $counth5pdependencies = $DB->count_records('h5p_library_dependencies');

        $this->assertSame($expectedh5p, $counth5p);
        $this->assertSame($expectedlibraries, $counth5plibraries);
        $this->assertSame($expectedcontents, $counth5pcontents);
        $this->assertSame($expecteddependencies, $counth5pdependencies);
    }

    /**
     * Data provider for test_delete_library().
     *
     * @return array
     */
    public static function delete_library_provider(): array {
        return [
            'Delete MainLibrary' => [
                'MainLibrary',
                0,
                6,
                0,
                4,
            ],
            'Delete Library1' => [
                'Library1',
                0,
                5,
                0,
                1,
            ],
            'Delete Library2' => [
                'Library2',
                0,
                4,
                0,
                1,
            ],
            'Delete Library3' => [
                'Library3',
                0,
                4,
                0,
                0,
            ],
            'Delete Library4' => [
                'Library4',
                0,
                4,
                0,
                1,
            ],
            'Delete Library5' => [
                'Library5',
                0,
                3,
                0,
                0,
            ],
            'Delete a library without dependencies' => [
                'H5P.TestingLibrary',
                1,
                6,
                5,
                7,
            ],
            'Delete unexisting library' => [
                'LibraryX',
                1,
                7,
                5,
                7,
            ],
        ];
    }

    /**
     * Test the behaviour of get_dependent_libraries().
     *
     * @dataProvider  get_dependent_libraries_provider
     * @param  string $libraryname     Machine name of the library to delete.
     * @param  int    $expectedvalue   Total of H5P required libraries expected.
     */
    public function test_get_dependent_libraries(string $libraryname, int $expectedvalue): void {
        global $DB;

        $this->resetAfterTest();

        // Generate h5p related data.
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
        $generator->generate_h5p_data();
        $generator->create_library_record('H5P.TestingLibrary', 'TestingLibrary', 1, 0);

        // Get required libraries.
        $library = $DB->get_record('h5p_libraries', ['machinename' => $libraryname], 'id');
        if ($library) {
            $libraries = api::get_dependent_libraries((int)$library->id);
        } else {
            $libraries = [];
        }

        $this->assertCount($expectedvalue, $libraries);
    }

    /**
     * Data provider for test_get_dependent_libraries().
     *
     * @return array
     */
    public static function get_dependent_libraries_provider(): array {
        return [
            'Main library of a content' => [
                'MainLibrary',
                0,
            ],
            'Library1' => [
                'Library1',
                1,
            ],
            'Library2' => [
                'Library2',
                2,
            ],
            'Library without dependencies' => [
                'H5P.TestingLibrary',
                0,
            ],
            'Unexisting library' => [
                'LibraryX',
                0,
            ],
        ];
    }

    /**
     * Test the behaviour of get_library().
     *
     * @dataProvider  get_library_provider
     * @param  string $libraryname     Machine name of the library to delete.
     * @param  bool   $emptyexpected   Wether the expected result is empty or not.
     */
    public function test_get_library(string $libraryname, bool $emptyexpected): void {
        global $DB;

        $this->resetAfterTest();

        // Generate h5p related data.
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
        $generator->generate_h5p_data();
        $generator->create_library_record('H5P.TestingLibrary', 'TestingLibrary', 1, 0);

        // Get the library identifier.
        $library = $DB->get_record('h5p_libraries', ['machinename' => $libraryname], 'id');
        if ($library) {
            $result = api::get_library((int)$library->id);
        } else {
            $result = null;
        }

        if ($emptyexpected) {
            $this->assertEmpty($result);
        } else {
            $this->assertEquals($library->id, $result->id);
            $this->assertEquals($libraryname, $result->machinename);
        }

    }

    /**
     * Data provider for test_get_library().
     *
     * @return array
     */
    public static function get_library_provider(): array {
        return [
            'Main library of a content' => [
                'MainLibrary',
                false,
            ],
            'Library1' => [
                'Library1',
                false,
            ],
            'Library without dependencies' => [
                'H5P.TestingLibrary',
                false,
            ],
            'Unexisting library' => [
                'LibraryX',
                true,
            ],
        ];
    }

    /**
     * Test the behaviour of get_content_from_pluginfile_url().
     */
    public function test_get_content_from_pluginfile_url(): void {
        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();
        $factory = new factory();

        // Create the H5P data.
        $filename = 'find-the-words.h5p';
        $path = self::get_fixture_path(__NAMESPACE__, $filename);
        $fakefile = helper::create_fake_stored_file_from_path($path);
        $config = (object)[
            'frame' => 1,
            'export' => 1,
            'embed' => 0,
            'copyright' => 0,
        ];

        // Get URL for this H5P content file.
        $syscontext = \context_system::instance();
        $url = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            'unittest',
            $fakefile->get_itemid(),
            '/',
            $filename
        );

        // Scenario 1: Get the H5P for this URL and check there isn't any existing H5P (because it hasn't been saved).
        list($newfile, $h5p) = api::get_content_from_pluginfile_url($url->out());
        $this->assertEquals($fakefile->get_pathnamehash(), $newfile->get_pathnamehash());
        $this->assertEquals($fakefile->get_contenthash(), $newfile->get_contenthash());
        $this->assertFalse($h5p);

        // Scenario 2: Save the H5P and check now the H5P is exactly the same as the original one.
        $h5pid = helper::save_h5p($factory, $fakefile, $config);
        list($newfile, $h5p) = api::get_content_from_pluginfile_url($url->out());

        $this->assertEquals($h5pid, $h5p->id);
        $this->assertEquals($fakefile->get_pathnamehash(), $h5p->pathnamehash);
        $this->assertEquals($fakefile->get_contenthash(), $h5p->contenthash);

        // Scenario 3: Get the H5P for an unexisting H5P file.
        $url = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            'unittest',
            $fakefile->get_itemid(),
            '/',
            'unexisting.h5p'
        );
        list($newfile, $h5p) = api::get_content_from_pluginfile_url($url->out());
        $this->assertFalse($newfile);
        $this->assertFalse($h5p);
    }

    /**
     * Test the behaviour of get_original_content_from_pluginfile_url().
     *
     * @covers ::get_original_content_from_pluginfile_url
     */
    public function test_get_original_content_from_pluginfile_url(): void {
        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();
        $this->setAdminUser();

        $factory = new factory();
        $syscontext = \context_system::instance();

        // Create the original file.
        $filename = 'greeting-card.h5p';
        $path = self::get_fixture_path(__NAMESPACE__, $filename);
        $originalfile = helper::create_fake_stored_file_from_path($path);
        $originalfilerecord = [
            'contextid' => $originalfile->get_contextid(),
            'component' => $originalfile->get_component(),
            'filearea'  => $originalfile->get_filearea(),
            'itemid'    => $originalfile->get_itemid(),
            'filepath'  => $originalfile->get_filepath(),
            'filename'  => $originalfile->get_filename(),
        ];

        $config = (object)[
            'frame' => 1,
            'export' => 1,
            'embed' => 0,
            'copyright' => 0,
        ];

        $originalurl = \moodle_url::make_pluginfile_url(
            $originalfile->get_contextid(),
            $originalfile->get_component(),
            $originalfile->get_filearea(),
            $originalfile->get_itemid(),
            $originalfile->get_filepath(),
            $originalfile->get_filename()
        );

        // Create a reference to the original file.
        $reffilerecord = [
            'contextid' => $syscontext->id,
            'component' => 'core',
            'filearea'  => 'phpunit',
            'itemid'    => 0,
            'filepath'  => '/',
            'filename'  => $filename
        ];

        $fs = get_file_storage();
        $ref = $fs->pack_reference($originalfilerecord);
        $repos = \repository::get_instances(['type' => 'user']);
        $userrepository = reset($repos);
        $referencedfile = $fs->create_file_from_reference($reffilerecord, $userrepository->id, $ref);
        $this->assertEquals($referencedfile->get_contenthash(), $originalfile->get_contenthash());

        $referencedurl = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            'core',
            'phpunit',
            0,
            '/',
            $filename
        );

        // Scenario 1: Original file (without any reference).
        $originalh5pid = helper::save_h5p($factory, $originalfile, $config);
        list($source, $h5p, $file) = api::get_original_content_from_pluginfile_url($originalurl->out());
        $this->assertEquals($originalfile->get_pathnamehash(), $source->get_pathnamehash());
        $this->assertEquals($originalfile->get_contenthash(), $source->get_contenthash());
        $this->assertEquals($originalh5pid, $h5p->id);
        $this->assertFalse($file);

        // Scenario 2: Referenced file (alias to originalfile).
        list($source, $h5p, $file) = api::get_original_content_from_pluginfile_url($referencedurl->out());
        $this->assertEquals($originalfile->get_pathnamehash(), $source->get_pathnamehash());
        $this->assertEquals($originalfile->get_contenthash(), $source->get_contenthash());
        $this->assertEquals($originalfile->get_contenthash(), $source->get_contenthash());
        $this->assertEquals($originalh5pid, $h5p->id);
        $this->assertEquals($referencedfile->get_pathnamehash(), $file->get_pathnamehash());
        $this->assertEquals($referencedfile->get_contenthash(), $file->get_contenthash());
        $this->assertEquals($referencedfile->get_contenthash(), $file->get_contenthash());

        // Scenario 3: Unexisting file.
        $unexistingurl = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            'core',
            'phpunit',
            0,
            '/',
            'unexisting.h5p'
        );
        list($source, $h5p, $file) = api::get_original_content_from_pluginfile_url($unexistingurl->out());
        $this->assertFalse($source);
        $this->assertFalse($h5p);
        $this->assertFalse($file);
    }

    /**
     * Test the behaviour of can_edit_content().
     *
     * @covers ::can_edit_content
     * @dataProvider can_edit_content_provider
     *
     * @param string $currentuser User who will call the method.
     * @param string $fileauthor Author of the file to check.
     * @param string $filecomponent Component of the file to check.
     * @param bool $expected Expected result after calling the can_edit_content method.
     * @param string $filearea Area of the file to check.
     *
     * @return void
     */
    public function test_can_edit_content(string $currentuser, string $fileauthor, string $filecomponent, bool $expected,
            $filearea = 'unittest'): void {
        global $USER, $DB;

        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();

        // Create course.
        $course = $this->getDataGenerator()->create_course();
        $context = \context_course::instance($course->id);

        // Create some users.
        $this->setAdminUser();
        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher');
        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
        $users = [
            'admin' => $USER,
            'teacher' => $teacher,
            'student' => $student,
        ];

        // Set current user.
        if ($currentuser !== 'admin') {
            $this->setUser($users[$currentuser]);
        }

        $itemid = rand();
        if ($filearea === 'post') {
            // Create a forum and add a discussion.
            $forum = $this->getDataGenerator()->create_module('forum', ['course' => $course->id]);

            $record = new stdClass();
            $record->course = $course->id;
            $record->userid = $users[$fileauthor]->id;
            $record->forum = $forum->id;
            $discussion = $this->getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
            $post = $DB->get_record('forum_posts', ['discussion' => $discussion->id]);
            $itemid = $post->id;
        }

        // Create the file.
        $filename = 'greeting-card.h5p';
        $path = self::get_fixture_path(__NAMESPACE__, $filename);
        if ($filecomponent === 'contentbank') {
            $generator = $this->getDataGenerator()->get_plugin_generator('core_contentbank');
            $contents = $generator->generate_contentbank_data(
                'contenttype_h5p',
                1,
                (int)$users[$fileauthor]->id,
                $context,
                true,
                $path
            );
            $content = array_shift($contents);
            $file = $content->get_file();
        } else {
            $filerecord = [
                'contextid' => $context->id,
                'component' => $filecomponent,
                'filearea'  => $filearea,
                'itemid'    => $itemid,
                'filepath'  => '/',
                'filename'  => basename($path),
                'userid'    => $users[$fileauthor]->id,
            ];
            $fs = get_file_storage();
            $file = $fs->create_file_from_pathname($filerecord, $path);
        }

        // Check if the currentuser can edit the file.
        $result = api::can_edit_content($file);
        $this->assertEquals($expected, $result);
    }

    /**
     * Data provider for test_can_edit_content().
     *
     * @return array
     */
    public static function can_edit_content_provider(): array {
        return [
            // Component = user.
            'user: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'user',
                'expected' => true,
            ],
            'user: Admin user, teacher is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'teacher',
                'filecomponent' => 'user',
                'expected' => false,
            ],
            'user: Teacher user, teacher is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'teacher',
                'filecomponent' => 'user',
                'expected' => true,
            ],
            'user: Teacher user, admin is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'admin',
                'filecomponent' => 'user',
                'expected' => false,
            ],
            'user: Student user, student is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'student',
                'filecomponent' => 'user',
                'expected' => true,
            ],
            'user: Student user, teacher is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'teacher',
                'filecomponent' => 'user',
                'expected' => false,
            ],

            // Component = mod_h5pactivity.
            'mod_h5pactivity: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_h5pactivity',
                'expected' => true,
            ],
            'mod_h5pactivity: Admin user, teacher is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_h5pactivity',
                'expected' => true,
            ],
            'mod_h5pactivity: Teacher user, teacher is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_h5pactivity',
                'expected' => true,
            ],
            'mod_h5pactivity: Teacher user, admin is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_h5pactivity',
                'expected' => true,
            ],
            'mod_h5pactivity: Student user, student is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'student',
                'filecomponent' => 'mod_h5pactivity',
                'expected' => false,
            ],
            'mod_h5pactivity: Student user, teacher is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_h5pactivity',
                'expected' => false,
            ],

            // Component = mod_book.
            'mod_book: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_book',
                'expected' => true,
            ],
            'mod_book: Admin user, teacher is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_book',
                'expected' => true,
            ],

            // Component = mod_forum.
            'mod_forum: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_forum',
                'expected' => true,
            ],
            'mod_forum: Admin user, teacher is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_forum',
                'expected' => true,
            ],
            'mod_forum: Teacher user, admin is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_forum',
                'expected' => true,
            ],
            'mod_forum: Student user, teacher is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_forum',
                'expected' => false,
            ],
            'mod_forum/post: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_forum',
                'expected' => true,
                'filearea' => 'post',
            ],
            'mod_forum/post: Teacher user, admin is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_forum',
                'expected' => true,
                'filearea' => 'post',
            ],
            'mod_forum/post: Student user, teacher is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'teacher',
                'filecomponent' => 'mod_forum',
                'expected' => false,
                'filearea' => 'post',
            ],

            // Component = block_html.
            'block_html: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'block_html',
                'expected' => true,
            ],
            'block_html: Admin user, teacher is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'teacher',
                'filecomponent' => 'block_html',
                'expected' => true,
            ],

            // Component = contentbank.
            'contentbank: Admin user is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'contentbank',
                'expected' => true,
            ],
            'contentbank: Admin user, teacher is author' => [
                'currentuser' => 'admin',
                'fileauthor' => 'teacher',
                'filecomponent' => 'contentbank',
                'expected' => true,
            ],
            'contentbank: Teacher user, teacher is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'teacher',
                'filecomponent' => 'contentbank',
                'expected' => true,
            ],
            'contentbank: Teacher user, admin is author' => [
                'currentuser' => 'teacher',
                'fileauthor' => 'admin',
                'filecomponent' => 'contentbank',
                'expected' => false,
            ],
            'contentbank: Student user, student is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'student',
                'filecomponent' => 'contentbank',
                'expected' => false,
            ],
            'contentbank: Student user, teacher is author' => [
                'currentuser' => 'student',
                'fileauthor' => 'teacher',
                'filecomponent' => 'contentbank',
                'expected' => false,
            ],

            // Unexisting components.
            'Unexisting component' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'unexisting_component',
                'expected' => false,
            ],
            'Unexisting module activity' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'mod_unexisting',
                'expected' => false,
            ],
            'Unexisting block' => [
                'currentuser' => 'admin',
                'fileauthor' => 'admin',
                'filecomponent' => 'block_unexisting',
                'expected' => false,
            ],
        ];
    }

    /**
     * Test the behaviour of create_content_from_pluginfile_url().
     */
    public function test_create_content_from_pluginfile_url(): void {
        global $DB;

        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();
        $factory = new factory();

        // Create the H5P data.
        $filename = 'find-the-words.h5p';
        $path = self::get_fixture_path(__NAMESPACE__, $filename);
        $fakefile = helper::create_fake_stored_file_from_path($path);
        $config = (object)[
            'frame' => 1,
            'export' => 1,
            'embed' => 0,
            'copyright' => 0,
        ];

        // Get URL for this H5P content file.
        $syscontext = \context_system::instance();
        $url = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            'unittest',
            $fakefile->get_itemid(),
            '/',
            $filename
        );

        // Scenario 1: Create the H5P from this URL and check the content is exactly the same as the fake file.
        $messages = new \stdClass();
        list($newfile, $h5pid) = api::create_content_from_pluginfile_url($url->out(), $config, $factory, $messages);
        $this->assertNotFalse($h5pid);
        $h5p = $DB->get_record('h5p', ['id' => $h5pid]);
        $this->assertEquals($fakefile->get_pathnamehash(), $h5p->pathnamehash);
        $this->assertEquals($fakefile->get_contenthash(), $h5p->contenthash);
        $this->assertTrue(empty($messages->error));
        $this->assertTrue(empty($messages->info));

        // Scenario 2: Create the H5P for an unexisting H5P file.
        $url = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            'unittest',
            $fakefile->get_itemid(),
            '/',
            'unexisting.h5p'
        );
        list($newfile, $h5p) = api::create_content_from_pluginfile_url($url->out(), $config, $factory, $messages);
        $this->assertFalse($newfile);
        $this->assertFalse($h5p);
        $this->assertTrue(empty($messages->error));
        $this->assertTrue(empty($messages->info));
    }

    /**
     * Test the behaviour of delete_content_from_pluginfile_url().
     */
    public function test_delete_content_from_pluginfile_url(): void {
        global $DB;

        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();
        $factory = new factory();

        // Create the H5P data.
        $filename = 'find-the-words.h5p';
        $path = self::get_fixture_path(__NAMESPACE__, $filename);
        $fakefile = helper::create_fake_stored_file_from_path($path);
        $config = (object)[
            'frame' => 1,
            'export' => 1,
            'embed' => 0,
            'copyright' => 0,
        ];

        // Get URL for this H5P content file.
        $syscontext = \context_system::instance();
        $url = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            'unittest',
            $fakefile->get_itemid(),
            '/',
            $filename
        );

        // Scenario 1: Try to remove the H5P content for an undeployed file.
        list($newfile, $h5p) = api::get_content_from_pluginfile_url($url->out());
        $this->assertEquals(0, $DB->count_records('h5p'));
        api::delete_content_from_pluginfile_url($url->out(), $factory);
        $this->assertEquals(0, $DB->count_records('h5p'));

        // Scenario 2: Deploy an H5P from this URL, check it's created, remove it and check it has been removed as expected.
        $this->assertEquals(0, $DB->count_records('h5p'));

        $messages = new \stdClass();
        list($newfile, $h5pid) = api::create_content_from_pluginfile_url($url->out(), $config, $factory, $messages);
        $this->assertEquals(1, $DB->count_records('h5p'));

        api::delete_content_from_pluginfile_url($url->out(), $factory);
        $this->assertEquals(0, $DB->count_records('h5p'));

        // Scenario 3: Try to remove the H5P for an unexisting H5P URL.
        $url = \moodle_url::make_pluginfile_url(
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            'unittest',
            $fakefile->get_itemid(),
            '/',
            'unexisting.h5p'
        );
        $this->assertEquals(0, $DB->count_records('h5p'));
        api::delete_content_from_pluginfile_url($url->out(), $factory);
        $this->assertEquals(0, $DB->count_records('h5p'));
    }

    /**
     * Test the behaviour of get_export_info_from_context_id().
     */
    public function test_get_export_info_from_context_id(): void {
        global $DB;

        $this->setRunTestInSeparateProcess(true);
        $this->resetAfterTest();
        $factory = new factory();

        // Create the H5P data.
        $filename = 'find-the-words.h5p';
        $syscontext = \context_system::instance();

        // Test scenario 1: H5P exists and deployed.
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
        $fakeexportfile = $generator->create_export_file($filename,
            $syscontext->id,
            \core_h5p\file_storage::COMPONENT,
            \core_h5p\file_storage::EXPORT_FILEAREA);

        $exportfile = api::get_export_info_from_context_id($syscontext->id,
            $factory,
            \core_h5p\file_storage::COMPONENT,
            \core_h5p\file_storage::EXPORT_FILEAREA);
        $this->assertEquals($fakeexportfile['filename'], $exportfile['filename']);
        $this->assertEquals($fakeexportfile['filepath'], $exportfile['filepath']);
        $this->assertEquals($fakeexportfile['filesize'], $exportfile['filesize']);
        $this->assertEquals($fakeexportfile['timemodified'], $exportfile['timemodified']);
        $this->assertEquals($fakeexportfile['fileurl'], $exportfile['fileurl']);

        // Test scenario 2: H5P exist, deployed but the content has changed.
        // We need to change the contenthash to simulate the H5P file was changed.
        $h5pfile = $DB->get_record('h5p', []);
        $h5pfile->contenthash = sha1('testedit');
        $DB->update_record('h5p', $h5pfile);
        $exportfile = api::get_export_info_from_context_id($syscontext->id,
            $factory,
            \core_h5p\file_storage::COMPONENT,
            \core_h5p\file_storage::EXPORT_FILEAREA);
        $this->assertNull($exportfile);

        // Tests scenario 3: H5P is not deployed.
        // We need to delete the H5P record to simulate the H5P was not deployed.
        $DB->delete_records('h5p', ['id' => $h5pfile->id]);
        $exportfile = api::get_export_info_from_context_id($syscontext->id,
            $factory,
            \core_h5p\file_storage::COMPONENT,
            \core_h5p\file_storage::EXPORT_FILEAREA);
        $this->assertNull($exportfile);
    }

    /**
     * Test the behaviour of set_library_enabled().
     *
     * @covers ::set_library_enabled
     * @dataProvider set_library_enabled_provider
     *
     * @param string $libraryname Library name to enable/disable.
     * @param string $action Action to be done with the library. Supported values: enable, disable.
     * @param int $expected Expected value for the enabled library field. -1 will be passed if the library doesn't exist.
     */
    public function test_set_library_enabled(string $libraryname, string $action, int $expected): void {
        global $DB;

        $this->resetAfterTest();

        // Create libraries.
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
        $generator->generate_h5p_data();

        // Check by default the library is enabled.
        $library = $DB->get_record('h5p_libraries', ['machinename' => $libraryname]);
        if ($expected >= 0) {
            $this->assertEquals(1, $library->enabled);
            $libraryid = (int) $library->id;
        } else {
            // Unexisting library. Set libraryid to some unexisting id.
            $libraryid = -1;
            $this->expectException('dml_missing_record_exception');
        }

        \core_h5p\api::set_library_enabled($libraryid, ($action == 'enable'));

        // Check the value of the "enabled" field after calling enable/disable method.
        $libraries = $DB->get_records('h5p_libraries');
        foreach ($libraries as $libraryid => $library) {
            if ($library->machinename == $libraryname) {
                $this->assertEquals($expected, $library->enabled);
            } else {
                // Check that only $libraryname has been enabled/disabled.
                $this->assertEquals(1, $library->enabled);
            }
        }
    }

    /**
     * Data provider for test_set_library_enabled().
     *
     * @return array
     */
    public static function set_library_enabled_provider(): array {
        return [
            'Disable existing library' => [
                'libraryname' => 'MainLibrary',
                'action' => 'disable',
                'expected' => 0,
            ],
            'Enable existing library' => [
                'libraryname' => 'MainLibrary',
                'action' => 'enable',
                'expected' => 1,
            ],
            'Disable existing library (not main)' => [
                'libraryname' => 'Library1',
                'action' => 'disable',
                'expected' => 0,
            ],
            'Enable existing library (not main)' => [
                'libraryname' => 'Library1',
                'action' => 'enable',
                'expected' => 1,
            ],
            'Disable existing library (not runnable)' => [
                'libraryname' => 'Library3',
                'action' => 'disable',
                'expected' => 1, // Not runnable libraries can't be disabled.
            ],
            'Enable existing library (not runnable)' => [
                'libraryname' => 'Library3',
                'action' => 'enable',
                'expected' => 1,
            ],
            'Enable unexisting library' => [
                'libraryname' => 'Unexisting library',
                'action' => 'enable',
                'expected' => -1,
            ],
            'Disable unexisting library' => [
                'libraryname' => 'Unexisting library',
                'action' => 'disable',
                'expected' => -1,
            ],
        ];
    }

    /**
     * Test the behaviour of is_library_enabled().
     *
     * @covers ::is_library_enabled
     * @dataProvider is_library_enabled_provider
     *
     * @param string $libraryname Library name to check.
     * @param bool $expected Expected result after calling the method.
     * @param bool $exception Exception expected or not.
     * @param bool $useid Whether to use id for calling is_library_enabled method.
     * @param bool $uselibraryname Whether to use libraryname for calling is_library_enabled method.
     */
    public function test_is_library_enabled(string $libraryname, bool $expected, bool $exception = false,
        bool $useid = false, bool $uselibraryname = true): void {
        global $DB;

        $this->resetAfterTest();

        // Create the following libraries:
        // - H5P.Lib1: 1 version enabled, 1 version disabled.
        // - H5P.Lib2: 2 versions enabled.
        // - H5P.Lib3: 2 versions disabled.
        // - H5P.Lib4: 1 version disabled.
        // - H5P.Lib5: 1 version enabled.
        $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
        $libraries = [
            'H5P.Lib1.1' => $generator->create_library_record('H5P.Lib1', 'Lib1', 1, 1, 0, '', null, null, null, false),
            'H5P.Lib1.2' => $generator->create_library_record('H5P.Lib1', 'Lib1', 1, 2),
            'H5P.Lib2.1' => $generator->create_library_record('H5P.Lib2', 'Lib2', 2, 1),
            'H5P.Lib2.2' => $generator->create_library_record('H5P.Lib2', 'Lib2', 2, 2),
            'H5P.Lib3.1' => $generator->create_library_record('H5P.Lib3', 'Lib3', 3, 1, 0, '', null, null, null, false),
            'H5P.Lib3.2' => $generator->create_library_record('H5P.Lib3', 'Lib3', 3, 2, 0, '', null, null, null, false),
            'H5P.Lib4.1' => $generator->create_library_record('H5P.Lib4', 'Lib4', 4, 1, 0, '', null, null, null, false),
            'H5P.Lib5.1' => $generator->create_library_record('H5P.Lib5', 'Lib5', 5, 1),
        ];

        $countenabledlibraries = $DB->count_records('h5p_libraries', ['enabled' => 1]);
        $this->assertEquals(4, $countenabledlibraries);

        if ($useid) {
            $librarydata = ['id' => $libraries[$libraryname]->id];
        } else if ($uselibraryname) {
            $librarydata = ['machinename' => $libraryname];
        } else {
            $librarydata = ['invalid' => true];
        }

        if ($exception) {
            $this->expectException(\moodle_exception::class);
        }

        $result = api::is_library_enabled((object) $librarydata);
        $this->assertEquals($expected, $result);
    }

    /**
     * Data provider for test_is_library_enabled().
     *
     * @return array
     */
    public static function is_library_enabled_provider(): array {
        return [
            'Library with 2 versions, one of them disabled' => [
                'libraryname' => 'H5P.Lib1',
                'expected' => false,
            ],
            'Library with 2 versions, all enabled' => [
                'libraryname' => 'H5P.Lib2',
                'expected' => true,
            ],
            'Library with 2 versions, all disabled' => [
                'libraryname' => 'H5P.Lib3',
                'expected' => false,
            ],
            'Library with only one version, disabled' => [
                'libraryname' => 'H5P.Lib4',
                'expected' => false,
            ],
            'Library with only one version, enabled' => [
                'libraryname' => 'H5P.Lib5',
                'expected' => true,
            ],
            'Library with 2 versions, one of them disabled (using id) - 1.1 (disabled)' => [
                'libraryname' => 'H5P.Lib1.1',
                'expected' => false,
                'exception' => false,
                'useid' => true,
            ],
            'Library with 2 versions, one of them disabled (using id) - 1.2 (enabled)' => [
                'libraryname' => 'H5P.Lib1.2',
                'expected' => true,
                'exception' => false,
                'useid' => true,
            ],
            'Library with 2 versions, all enabled (using id) - 2.1' => [
                'libraryname' => 'H5P.Lib2.1',
                'expected' => true,
                'exception' => false,
                'useid' => true,
            ],
            'Library with 2 versions, all enabled (using id) - 2.2' => [
                'libraryname' => 'H5P.Lib2.2',
                'expected' => true,
                'exception' => false,
                'useid' => true,
            ],
            'Library with 2 versions, all disabled (using id) - 3.1' => [
                'libraryname' => 'H5P.Lib3.1',
                'expected' => false,
                'exception' => false,
                'useid' => true,
            ],
            'Library with 2 versions, all disabled (using id) - 3.2' => [
                'libraryname' => 'H5P.Lib3.2',
                'expected' => false,
                'exception' => false,
                'useid' => true,
            ],
            'Library with only one version, disabled (using id)' => [
                'libraryname' => 'H5P.Lib4.1',
                'expected' => false,
                'exception' => false,
                'useid' => true,
            ],
            'Library with only one version, enabled (using id)' => [
                'libraryname' => 'H5P.Lib5.1',
                'expected' => true,
                'exception' => false,
                'useid' => true,
            ],
            'Unexisting library' => [
                'libraryname' => 'H5P.Unexisting',
                'expected' => true,
            ],
            'Missing required parameters' => [
                'libraryname' => 'H5P.Unexisting',
                'expected' => false,
                'exception' => true,
                'useid' => false,
                'uselibraryname' => false,
            ],
        ];
    }

    /**
     * Test the behaviour of is_valid_package().
     * @runInSeparateProcess
     *
     * @covers ::is_valid_package
     * @dataProvider is_valid_package_provider
     *
     * @param string $filename The H5P content to validate.
     * @param bool $expected Expected result after calling the method.
     * @param bool $isadmin Whether the user calling the method will be admin or not.
     * @param bool $onlyupdatelibs Whether new libraries can be installed or only the existing ones can be updated.
     * @param bool $skipcontent Should the content be skipped (so only the libraries will be saved)?
     */
    public function test_is_valid_package(string $filename, bool $expected, bool $isadmin = false, bool $onlyupdatelibs = false,
            bool $skipcontent = false): void {
        global $USER;

        $this->resetAfterTest();

        if ($isadmin) {
            $this->setAdminUser();
            $user = $USER;
        } else {
            // Create a user.
            $user = $this->getDataGenerator()->create_user();
            $this->setUser($user);
        }

        // Prepare the file.
        $path = __DIR__ . $filename;
        $file = helper::create_fake_stored_file_from_path($path, (int)$user->id);

        // Check if the H5P content is valid or not.
        $result = api::is_valid_package($file, $onlyupdatelibs, $skipcontent);
        $this->assertEquals($expected, $result);
    }

    /**
     * Data provider for test_is_valid_package().
     *
     * @return array
     */
    public static function is_valid_package_provider(): array {
        return [
            'Valid H5P file (as admin)' => [
                'filename' => '/fixtures/greeting-card.h5p',
                'expected' => true,
                'isadmin' => true,
            ],
            'Valid H5P file (as user) without library update and checking content' => [
                'filename' => '/fixtures/greeting-card.h5p',
                'expected' => false, // Libraries are missing and user hasn't the right permissions to upload them.
                'isadmin' => false,
                'onlyupdatelibs' => false,
                'skipcontent' => false,
            ],
            'Valid H5P file (as user) with library update and checking content' => [
                'filename' => '/fixtures/greeting-card.h5p',
                'expected' => false, // Libraries are missing and user hasn't the right permissions to upload them.
                'isadmin' => false,
                'onlyupdatelibs' => true,
                'skipcontent' => false,
            ],
            'Valid H5P file (as user) without library update and skipping content' => [
                'filename' => '/fixtures/greeting-card.h5p',
                'expected' => true, // Content check is skipped so the package will be considered valid.
                'isadmin' => false,
                'onlyupdatelibs' => false,
                'skipcontent' => true,
            ],
            'Valid H5P file (as user) with library update and skipping content' => [
                'filename' => '/fixtures/greeting-card.h5p',
                'expected' => true, // Content check is skipped so the package will be considered valid.
                'isadmin' => false,
                'onlyupdatelibs' => true,
                'skipcontent' => true,
            ],
            'Invalid H5P file (as admin)' => [
                'filename' => '/fixtures/h5ptest.zip',
                'expected' => false,
                'isadmin' => true,
            ],
            'Invalid H5P file (as user)' => [
                'filename' => '/fixtures/h5ptest.zip',
                'expected' => false,
                'isadmin' => false,
            ],
            'Invalid H5P file (as user) skipping content' => [
                'filename' => '/fixtures/h5ptest.zip',
                'expected' => true, // Content check is skipped so the package will be considered valid.
                'isadmin' => false,
                'onlyupdatelibs' => false,
                'skipcontent' => true,
            ],
        ];
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit