learnpathItem.class.php 186 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class learnpathItem
  5. * lp_item defines items belonging to a learnpath. Each item has a name,
  6. * a score, a use time and additional information that enables tracking a user's
  7. * progress in a learning path.
  8. *
  9. * @package chamilo.learnpath
  10. *
  11. * @author Yannick Warnier <ywarnier@beeznest.org>
  12. */
  13. class learnpathItem
  14. {
  15. const DEBUG = 0; // Logging parameter.
  16. public $iId;
  17. public $attempt_id; // Also called "objectives" SCORM-wise.
  18. public $audio; // The path to an audio file (stored in document/audio/).
  19. public $children = []; // Contains the ids of children items.
  20. public $condition; // If this item has a special condition embedded.
  21. public $current_score;
  22. public $current_start_time;
  23. public $current_stop_time;
  24. public $current_data = '';
  25. public $db_id;
  26. public $db_item_view_id = '';
  27. public $description = '';
  28. public $file;
  29. /**
  30. * At the moment, interactions are just an array of arrays with a structure
  31. * of 8 text fields: id(0), type(1), time(2), weighting(3),
  32. * correct_responses(4), student_response(5), result(6), latency(7).
  33. */
  34. public $interactions = [];
  35. public $interactions_count = 0;
  36. public $objectives = [];
  37. public $objectives_count = 0;
  38. public $launch_data = '';
  39. public $lesson_location = '';
  40. public $level = 0;
  41. public $core_exit = '';
  42. //var $location; // Only set this for SCORM?
  43. public $lp_id;
  44. public $max_score;
  45. public $mastery_score;
  46. public $min_score;
  47. public $max_time_allowed = '';
  48. public $name;
  49. public $next;
  50. public $parent;
  51. public $path; // In some cases the exo_id = exercise_id in courseDb exercices table.
  52. public $possible_status = [
  53. 'not attempted',
  54. 'incomplete',
  55. 'completed',
  56. 'passed',
  57. 'failed',
  58. 'browsed',
  59. ];
  60. public $prereq_string = '';
  61. public $prereq_alert = '';
  62. public $prereqs = [];
  63. public $previous;
  64. public $prevent_reinit = 1; // 0 = multiple attempts 1 = one attempt
  65. public $seriousgame_mode;
  66. public $ref;
  67. public $save_on_close = true;
  68. public $search_did = null;
  69. public $status;
  70. public $title;
  71. /**
  72. * Type attribute can contain one of
  73. * link|student_publication|dir|quiz|document|forum|thread.
  74. */
  75. public $type;
  76. public $view_id;
  77. public $oldTotalTime;
  78. //var used if absolute session time mode is used
  79. private $last_scorm_session_time = 0;
  80. private $prerequisiteMaxScore;
  81. private $prerequisiteMinScore;
  82. /**
  83. * Prepares the learning path item for later launch.
  84. * Don't forget to use set_lp_view() if applicable after creating the item.
  85. * Setting an lp_view will finalise the item_view data collection.
  86. *
  87. * @param int $id Learning path item ID
  88. * @param int $user_id User ID
  89. * @param int $course_id Course int id
  90. * @param array|null $item_content An array with the contents of the item
  91. */
  92. public function __construct(
  93. $id,
  94. $user_id = 0,
  95. $course_id = 0,
  96. $item_content = null
  97. ) {
  98. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  99. // Get items table.
  100. if (!isset($user_id)) {
  101. $user_id = api_get_user_id();
  102. }
  103. if (self::DEBUG > 0) {
  104. error_log("learnpathItem constructor: id: $id user_id: $user_id course_id: $course_id");
  105. error_log("item_content: ".print_r($item_content, 1));
  106. }
  107. $id = (int) $id;
  108. if (empty($item_content)) {
  109. if (empty($course_id)) {
  110. $course_id = api_get_course_int_id();
  111. } else {
  112. $course_id = (int) $course_id;
  113. }
  114. $sql = "SELECT * FROM $items_table
  115. WHERE iid = $id";
  116. $res = Database::query($sql);
  117. if (Database::num_rows($res) < 1) {
  118. $this->error = 'Could not find given learnpath item in learnpath_item table';
  119. }
  120. $row = Database::fetch_array($res);
  121. } else {
  122. $row = $item_content;
  123. }
  124. $this->lp_id = $row['lp_id'];
  125. $this->iId = $row['iid'];
  126. $this->max_score = $row['max_score'];
  127. $this->min_score = $row['min_score'];
  128. $this->name = $row['title'];
  129. $this->type = $row['item_type'];
  130. $this->ref = $row['ref'];
  131. $this->title = $row['title'];
  132. $this->description = $row['description'];
  133. $this->path = $row['path'];
  134. $this->mastery_score = $row['mastery_score'];
  135. $this->parent = $row['parent_item_id'];
  136. $this->next = $row['next_item_id'];
  137. $this->previous = $row['previous_item_id'];
  138. $this->display_order = $row['display_order'];
  139. $this->prereq_string = $row['prerequisite'];
  140. $this->max_time_allowed = $row['max_time_allowed'];
  141. $this->setPrerequisiteMaxScore($row['prerequisite_max_score']);
  142. $this->setPrerequisiteMinScore($row['prerequisite_min_score']);
  143. $this->oldTotalTime = 0;
  144. if (isset($row['launch_data'])) {
  145. $this->launch_data = $row['launch_data'];
  146. }
  147. $this->save_on_close = true;
  148. $this->db_id = $id;
  149. // Load children list
  150. if (!empty($this->lp_id)) {
  151. $sql = "SELECT iid FROM $items_table
  152. WHERE
  153. c_id = $course_id AND
  154. lp_id = ".$this->lp_id." AND
  155. parent_item_id = $id";
  156. $res = Database::query($sql);
  157. if (Database::num_rows($res) > 0) {
  158. while ($row = Database::fetch_assoc($res)) {
  159. $this->children[] = $row['iid'];
  160. }
  161. }
  162. // Get search_did.
  163. if (api_get_setting('search_enabled') == 'true') {
  164. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  165. $sql = 'SELECT *
  166. FROM %s
  167. WHERE
  168. course_code=\'%s\' AND
  169. tool_id=\'%s\' AND
  170. ref_id_high_level=%s AND
  171. ref_id_second_level=%d
  172. LIMIT 1';
  173. // TODO: Verify if it's possible to assume the actual course instead
  174. // of getting it from db.
  175. $sql = sprintf(
  176. $sql,
  177. $tbl_se_ref,
  178. api_get_course_id(),
  179. TOOL_LEARNPATH,
  180. $this->lp_id,
  181. $id
  182. );
  183. $res = Database::query($sql);
  184. if (Database::num_rows($res) > 0) {
  185. $se_ref = Database::fetch_array($res);
  186. $this->search_did = (int) $se_ref['search_did'];
  187. }
  188. }
  189. }
  190. $this->seriousgame_mode = 0;
  191. $this->audio = $row['audio'];
  192. if (self::DEBUG > 0) {
  193. error_log(
  194. 'New LP - End of learnpathItem constructor for item '.$id,
  195. 0
  196. );
  197. }
  198. }
  199. /**
  200. * Adds a child to the current item.
  201. *
  202. * @param int $item The child item ID
  203. */
  204. public function add_child($item)
  205. {
  206. if (!empty($item)) {
  207. // Do not check in DB as we expect the call to come from the
  208. // learnpath class which should be aware of any fake.
  209. $this->children[] = $item;
  210. }
  211. }
  212. /**
  213. * Adds an interaction to the current item.
  214. *
  215. * @param int $index Index (order ID) of the interaction inside this item
  216. * @param array $params Array of parameters:
  217. * id(0), type(1), time(2), weighting(3), correct_responses(4),
  218. * student_response(5), result(6), latency(7)
  219. */
  220. public function add_interaction($index, $params)
  221. {
  222. $this->interactions[$index] = $params;
  223. // Take the current maximum index to generate the interactions_count.
  224. if (($index + 1) > $this->interactions_count) {
  225. $this->interactions_count = $index + 1;
  226. }
  227. }
  228. /**
  229. * Adds an objective to the current item.
  230. *
  231. * @param array Array of parameters:
  232. * id(0), status(1), score_raw(2), score_max(3), score_min(4)
  233. */
  234. public function add_objective($index, $params)
  235. {
  236. if (empty($params[0])) {
  237. return null;
  238. }
  239. $this->objectives[$index] = $params;
  240. // Take the current maximum index to generate the objectives_count.
  241. if ((count($this->objectives) + 1) > $this->objectives_count) {
  242. $this->objectives_count = (count($this->objectives) + 1);
  243. }
  244. }
  245. /**
  246. * Closes/stops the item viewing. Finalises runtime values.
  247. * If required, save to DB.
  248. *
  249. * @return bool True on success, false otherwise
  250. */
  251. public function close()
  252. {
  253. if (self::DEBUG > 0) {
  254. error_log('learnpathItem::close()', 0);
  255. }
  256. $this->current_stop_time = time();
  257. $type = $this->get_type();
  258. if ($type != 'sco') {
  259. if ($type == TOOL_QUIZ || $type == TOOL_HOTPOTATOES) {
  260. $this->get_status(
  261. true,
  262. true
  263. ); // Update status (second option forces the update).
  264. } else {
  265. $this->status = $this->possible_status[2];
  266. }
  267. }
  268. if ($this->save_on_close) {
  269. $this->save();
  270. }
  271. return true;
  272. }
  273. /**
  274. * Deletes all traces of this item in the database.
  275. *
  276. * @return bool true. Doesn't check for errors yet.
  277. */
  278. public function delete()
  279. {
  280. if (self::DEBUG > 0) {
  281. error_log('learnpath_item::delete() for item '.$this->db_id, 0);
  282. }
  283. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  284. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  285. $course_id = api_get_course_int_id();
  286. $sql = "DELETE FROM $lp_item_view
  287. WHERE c_id = $course_id AND lp_item_id = ".$this->db_id;
  288. Database::query($sql);
  289. $sql = "SELECT * FROM $lp_item
  290. WHERE iid = ".$this->db_id;
  291. $res_sel = Database::query($sql);
  292. if (Database::num_rows($res_sel) < 1) {
  293. return false;
  294. }
  295. $sql = "DELETE FROM $lp_item
  296. WHERE iid = ".$this->db_id;
  297. Database::query($sql);
  298. if (api_get_setting('search_enabled') == 'true') {
  299. if (!is_null($this->search_did)) {
  300. $di = new ChamiloIndexer();
  301. $di->remove_document($this->search_did);
  302. }
  303. }
  304. return true;
  305. }
  306. /**
  307. * Drops a child from the children array.
  308. *
  309. * @param string $item index of child item to drop
  310. */
  311. public function drop_child($item)
  312. {
  313. if (!empty($item)) {
  314. foreach ($this->children as $index => $child) {
  315. if ($child == $item) {
  316. $this->children[$index] = null;
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * Gets the current attempt_id for this user on this item.
  323. *
  324. * @return int attempt_id for this item view by this user or 1 if none defined
  325. */
  326. public function get_attempt_id()
  327. {
  328. $res = 1;
  329. if (!empty($this->attempt_id)) {
  330. $res = (int) $this->attempt_id;
  331. }
  332. return $res;
  333. }
  334. /**
  335. * Gets a list of the item's children.
  336. *
  337. * @return array Array of children items IDs
  338. */
  339. public function get_children()
  340. {
  341. $list = [];
  342. foreach ($this->children as $child) {
  343. if (!empty($child)) {
  344. $list[] = $child;
  345. }
  346. }
  347. return $list;
  348. }
  349. /**
  350. * Gets the core_exit value from the database.
  351. */
  352. public function get_core_exit()
  353. {
  354. return $this->core_exit;
  355. }
  356. /**
  357. * Gets the credit information (rather scorm-stuff) based on current status
  358. * and reinit autorization. Credit tells the sco(content) if Chamilo will
  359. * record the data it is sent (credit) or not (no-credit).
  360. *
  361. * @return string 'credit' or 'no-credit'. Defaults to 'credit'
  362. * Because if we don't know enough about this item, it's probably because
  363. * it was never used before.
  364. */
  365. public function get_credit()
  366. {
  367. if (self::DEBUG > 1) {
  368. error_log('learnpathItem::get_credit()', 0);
  369. }
  370. $credit = 'credit';
  371. // Now check the value of prevent_reinit (if it's 0, return credit as
  372. // the default was).
  373. // If prevent_reinit == 1 (or more).
  374. if ($this->get_prevent_reinit() != 0) {
  375. // If status is not attempted or incomplete, credit anyway.
  376. // Otherwise:
  377. // Check the status in the database rather than in the object, as
  378. // checking in the object would always return "no-credit" when we
  379. // want to set it to completed.
  380. $status = $this->get_status(true);
  381. if (self::DEBUG > 2) {
  382. error_log(
  383. 'learnpathItem::get_credit() - get_prevent_reinit!=0 and '.
  384. 'status is '.$status,
  385. 0
  386. );
  387. }
  388. //0=not attempted - 1 = incomplete
  389. if ($status != $this->possible_status[0] &&
  390. $status != $this->possible_status[1]
  391. ) {
  392. $credit = 'no-credit';
  393. }
  394. }
  395. if (self::DEBUG > 1) {
  396. error_log("learnpathItem::get_credit() returns: $credit");
  397. }
  398. return $credit;
  399. }
  400. /**
  401. * Gets the current start time property.
  402. *
  403. * @return int Current start time, or current time if none
  404. */
  405. public function get_current_start_time()
  406. {
  407. if (empty($this->current_start_time)) {
  408. return time();
  409. }
  410. return $this->current_start_time;
  411. }
  412. /**
  413. * Gets the item's description.
  414. *
  415. * @return string Description
  416. */
  417. public function get_description()
  418. {
  419. if (empty($this->description)) {
  420. return '';
  421. }
  422. return $this->description;
  423. }
  424. /**
  425. * Gets the file path from the course's root directory, no matter what
  426. * tool it is from.
  427. *
  428. * @param string $path_to_scorm_dir
  429. *
  430. * @return string The file path, or an empty string if there is no file
  431. * attached, or '-1' if the file must be replaced by an error page
  432. */
  433. public function get_file_path($path_to_scorm_dir = '')
  434. {
  435. $course_id = api_get_course_int_id();
  436. if (self::DEBUG > 0) {
  437. error_log('learnpathItem::get_file_path()', 0);
  438. }
  439. $path = $this->get_path();
  440. $type = $this->get_type();
  441. if (empty($path)) {
  442. if ($type == 'dir') {
  443. return '';
  444. } else {
  445. return '-1';
  446. }
  447. } elseif ($path == strval(intval($path))) {
  448. // The path is numeric, so it is a reference to a Chamilo object.
  449. switch ($type) {
  450. case 'dir':
  451. return '';
  452. case TOOL_DOCUMENT:
  453. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  454. $sql = 'SELECT path
  455. FROM '.$table_doc.'
  456. WHERE
  457. c_id = '.$course_id.' AND
  458. iid = '.$path;
  459. $res = Database::query($sql);
  460. $row = Database::fetch_array($res);
  461. $real_path = 'document'.$row['path'];
  462. return $real_path;
  463. case TOOL_STUDENTPUBLICATION:
  464. case TOOL_QUIZ:
  465. case TOOL_FORUM:
  466. case TOOL_THREAD:
  467. case TOOL_LINK:
  468. default:
  469. return '-1';
  470. }
  471. } else {
  472. if (!empty($path_to_scorm_dir)) {
  473. $path = $path_to_scorm_dir.$path;
  474. }
  475. return $path;
  476. }
  477. }
  478. /**
  479. * Gets the DB ID.
  480. *
  481. * @return int Database ID for the current item
  482. */
  483. public function get_id()
  484. {
  485. if (!empty($this->db_id)) {
  486. return $this->db_id;
  487. }
  488. // TODO: Check this return value is valid for children classes (SCORM?).
  489. return 0;
  490. }
  491. /**
  492. * Loads the interactions into the item object, from the database.
  493. * If object interactions exist, they will be overwritten by this function,
  494. * using the database elements only.
  495. */
  496. public function load_interactions()
  497. {
  498. $this->interactions = [];
  499. $course_id = api_get_course_int_id();
  500. $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  501. $sql = "SELECT id FROM $tbl
  502. WHERE
  503. c_id = $course_id AND
  504. lp_item_id = ".$this->db_id." AND
  505. lp_view_id = ".$this->view_id." AND
  506. view_count = ".$this->get_view_count();
  507. $res = Database::query($sql);
  508. if (Database::num_rows($res) > 0) {
  509. $row = Database::fetch_array($res);
  510. $lp_iv_id = $row[0];
  511. $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  512. $sql = "SELECT * FROM $iva_table
  513. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
  514. $res_sql = Database::query($sql);
  515. while ($row = Database::fetch_array($res_sql)) {
  516. $this->interactions[$row['interaction_id']] = [
  517. $row['interaction_id'],
  518. $row['interaction_type'],
  519. $row['weighting'],
  520. $row['completion_time'],
  521. $row['correct_responses'],
  522. $row['student_responses'],
  523. $row['result'],
  524. $row['latency'],
  525. ];
  526. }
  527. }
  528. }
  529. /**
  530. * Gets the current count of interactions recorded in the database.
  531. *
  532. * @param bool $checkdb Whether to count from database or not (defaults to no)
  533. *
  534. * @return int The current number of interactions recorder
  535. */
  536. public function get_interactions_count($checkdb = false)
  537. {
  538. $return = 0;
  539. if (api_is_invitee()) {
  540. // If the user is an invitee, we consider there's no interaction
  541. return 0;
  542. }
  543. $course_id = api_get_course_int_id();
  544. if ($checkdb) {
  545. $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  546. $sql = "SELECT iid FROM $tbl
  547. WHERE
  548. c_id = $course_id AND
  549. lp_item_id = ".$this->db_id." AND
  550. lp_view_id = ".$this->view_id." AND
  551. view_count = ".$this->get_attempt_id();
  552. $res = Database::query($sql);
  553. if (Database::num_rows($res) > 0) {
  554. $row = Database::fetch_array($res);
  555. $lp_iv_id = $row[0];
  556. $iva_table = Database::get_course_table(
  557. TABLE_LP_IV_INTERACTION
  558. );
  559. $sql = "SELECT count(id) as mycount
  560. FROM $iva_table
  561. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id ";
  562. $res_sql = Database::query($sql);
  563. if (Database::num_rows($res_sql) > 0) {
  564. $row = Database::fetch_array($res_sql);
  565. $return = $row['mycount'];
  566. }
  567. }
  568. } else {
  569. if (!empty($this->interactions_count)) {
  570. $return = $this->interactions_count;
  571. }
  572. }
  573. return $return;
  574. }
  575. /**
  576. * Gets the JavaScript array content to fill the interactions array.
  577. *
  578. * @param bool $checkdb Whether to check directly into the database (default no)
  579. *
  580. * @return string An empty string if no interaction, a JS array definition otherwise
  581. */
  582. public function get_interactions_js_array($checkdb = false)
  583. {
  584. $return = '';
  585. if ($checkdb) {
  586. $this->load_interactions(true);
  587. }
  588. foreach ($this->interactions as $id => $in) {
  589. $return .= "[
  590. '$id',
  591. '".$in[1]."',
  592. '".$in[2]."',
  593. '".$in[3]."',
  594. '".$in[4]."',
  595. '".$in[5]."',
  596. '".$in[6]."',
  597. '".$in[7]."'],";
  598. }
  599. if (!empty($return)) {
  600. $return = substr($return, 0, -1);
  601. }
  602. return $return;
  603. }
  604. /**
  605. * Gets the current count of objectives recorded in the database.
  606. *
  607. * @return int The current number of objectives recorder
  608. */
  609. public function get_objectives_count()
  610. {
  611. $res = 0;
  612. if (!empty($this->objectives_count)) {
  613. $res = $this->objectives_count;
  614. }
  615. return $res;
  616. }
  617. /**
  618. * Gets the launch_data field found in imsmanifests (this is SCORM- or
  619. * AICC-related, really).
  620. *
  621. * @return string Launch data as found in imsmanifest and stored in
  622. * Chamilo (read only). Defaults to ''.
  623. */
  624. public function get_launch_data()
  625. {
  626. if (!empty($this->launch_data)) {
  627. return str_replace(
  628. ["\r", "\n", "'"],
  629. ['\r', '\n', "\\'"],
  630. $this->launch_data
  631. );
  632. }
  633. return '';
  634. }
  635. /**
  636. * Gets the lesson location.
  637. *
  638. * @return string lesson location as recorded by the SCORM and AICC
  639. * elements. Defaults to ''
  640. */
  641. public function get_lesson_location()
  642. {
  643. if (!empty($this->lesson_location)) {
  644. return str_replace(
  645. ["\r", "\n", "'"],
  646. ['\r', '\n', "\\'"],
  647. $this->lesson_location
  648. );
  649. }
  650. return '';
  651. }
  652. /**
  653. * Gets the lesson_mode (scorm feature, but might be used by aicc as well
  654. * as chamilo paths).
  655. *
  656. * The "browse" mode is not supported yet (because there is no such way of
  657. * seeing a sco in Chamilo)
  658. *
  659. * @return string 'browse','normal' or 'review'. Defaults to 'normal'
  660. */
  661. public function get_lesson_mode()
  662. {
  663. $mode = 'normal';
  664. if ($this->get_prevent_reinit() != 0) {
  665. // If prevent_reinit == 0
  666. $my_status = $this->get_status();
  667. if ($my_status != $this->possible_status[0] && $my_status != $this->possible_status[1]) {
  668. $mode = 'review';
  669. }
  670. }
  671. return $mode;
  672. }
  673. /**
  674. * Gets the depth level.
  675. *
  676. * @return int Level. Defaults to 0
  677. */
  678. public function get_level()
  679. {
  680. if (empty($this->level)) {
  681. return 0;
  682. }
  683. return $this->level;
  684. }
  685. /**
  686. * Gets the mastery score.
  687. */
  688. public function get_mastery_score()
  689. {
  690. if (isset($this->mastery_score)) {
  691. return $this->mastery_score;
  692. }
  693. return -1;
  694. }
  695. /**
  696. * Gets the maximum (score).
  697. *
  698. * @return int Maximum score. Defaults to 100 if nothing else is defined
  699. */
  700. public function get_max()
  701. {
  702. if ($this->type == 'sco') {
  703. if (isset($this->view_max_score) &&
  704. !empty($this->view_max_score) &&
  705. $this->view_max_score > 0
  706. ) {
  707. return $this->view_max_score;
  708. } elseif (isset($this->view_max_score) &&
  709. $this->view_max_score === ''
  710. ) {
  711. return $this->view_max_score;
  712. } else {
  713. if (!empty($this->max_score)) {
  714. return $this->max_score;
  715. } else {
  716. return 100;
  717. }
  718. }
  719. } else {
  720. if (!empty($this->max_score)) {
  721. return $this->max_score;
  722. } else {
  723. return 100;
  724. }
  725. }
  726. }
  727. /**
  728. * Gets the maximum time allowed for this user in this attempt on this item.
  729. *
  730. * @return string Time string in SCORM format
  731. * (HH:MM:SS or HH:MM:SS.SS or HHHH:MM:SS.SS)
  732. */
  733. public function get_max_time_allowed()
  734. {
  735. if (!empty($this->max_time_allowed)) {
  736. return $this->max_time_allowed;
  737. }
  738. return '';
  739. }
  740. /**
  741. * Gets the minimum (score).
  742. *
  743. * @return int Minimum score. Defaults to 0
  744. */
  745. public function get_min()
  746. {
  747. if (!empty($this->min_score)) {
  748. return $this->min_score;
  749. }
  750. return 0;
  751. }
  752. /**
  753. * Gets the parent ID.
  754. *
  755. * @return int Parent ID. Defaults to null
  756. */
  757. public function get_parent()
  758. {
  759. if (!empty($this->parent)) {
  760. return $this->parent;
  761. }
  762. // TODO: Check this return value is valid for children classes (SCORM?).
  763. return null;
  764. }
  765. /**
  766. * Gets the path attribute.
  767. *
  768. * @return string Path. Defaults to ''
  769. */
  770. public function get_path()
  771. {
  772. if (empty($this->path)) {
  773. return '';
  774. }
  775. return $this->path;
  776. }
  777. /**
  778. * Gets the prerequisites string.
  779. *
  780. * @return string empty string or prerequisites string if defined
  781. */
  782. public function get_prereq_string()
  783. {
  784. if (!empty($this->prereq_string)) {
  785. return $this->prereq_string;
  786. }
  787. return '';
  788. }
  789. /**
  790. * Gets the prevent_reinit attribute value (and sets it if not set already).
  791. *
  792. * @return int 1 or 0 (defaults to 1)
  793. */
  794. public function get_prevent_reinit()
  795. {
  796. if (self::DEBUG > 2) {
  797. error_log('learnpathItem::get_prevent_reinit()', 0);
  798. }
  799. if (!isset($this->prevent_reinit)) {
  800. if (!empty($this->lp_id)) {
  801. $table = Database::get_course_table(TABLE_LP_MAIN);
  802. $sql = "SELECT prevent_reinit
  803. FROM $table
  804. WHERE iid = ".$this->lp_id;
  805. $res = Database::query($sql);
  806. if (Database::num_rows($res) < 1) {
  807. $this->error = "Could not find parent learnpath in lp table";
  808. if (self::DEBUG > 2) {
  809. error_log(
  810. 'New LP - End of learnpathItem::get_prevent_reinit() - Returning false',
  811. 0
  812. );
  813. }
  814. return false;
  815. } else {
  816. $row = Database::fetch_array($res);
  817. $this->prevent_reinit = $row['prevent_reinit'];
  818. }
  819. } else {
  820. // Prevent reinit is always 1 by default - see learnpath.class.php
  821. $this->prevent_reinit = 1;
  822. }
  823. }
  824. if (self::DEBUG > 2) {
  825. error_log(
  826. 'New LP - End of learnpathItem::get_prevent_reinit() - Returned '.$this->prevent_reinit,
  827. 0
  828. );
  829. }
  830. return $this->prevent_reinit;
  831. }
  832. /**
  833. * Returns 1 if seriousgame_mode is activated, 0 otherwise.
  834. *
  835. * @return int (0 or 1)
  836. *
  837. * @deprecated seriousgame_mode seems not to be used
  838. *
  839. * @author ndiechburg <noel@cblue.be>
  840. */
  841. public function get_seriousgame_mode()
  842. {
  843. if (!isset($this->seriousgame_mode)) {
  844. if (!empty($this->lp_id)) {
  845. $table = Database::get_course_table(TABLE_LP_MAIN);
  846. $sql = "SELECT seriousgame_mode
  847. FROM $table
  848. WHERE iid = ".$this->lp_id;
  849. $res = Database::query($sql);
  850. if (Database::num_rows($res) < 1) {
  851. $this->error = 'Could not find parent learnpath in learnpath table';
  852. return false;
  853. } else {
  854. $row = Database::fetch_array($res);
  855. $this->seriousgame_mode = isset($row['seriousgame_mode']) ? $row['seriousgame_mode'] : 0;
  856. }
  857. } else {
  858. $this->seriousgame_mode = 0; //SeriousGame mode is always off by default
  859. }
  860. }
  861. return $this->seriousgame_mode;
  862. }
  863. /**
  864. * Gets the item's reference column.
  865. *
  866. * @return string The item's reference field (generally used for SCORM identifiers)
  867. */
  868. public function get_ref()
  869. {
  870. return $this->ref;
  871. }
  872. /**
  873. * Gets the list of included resources as a list of absolute or relative
  874. * paths of resources included in the current item. This allows for a
  875. * better SCORM export. The list will generally include pictures, flash
  876. * objects, java applets, or any other stuff included in the source of the
  877. * current item. The current item is expected to be an HTML file. If it
  878. * is not, then the function will return and empty list.
  879. *
  880. * @param string $type (one of the Chamilo tools) - optional (otherwise takes the current item's type)
  881. * @param string $abs_path absolute file path - optional (otherwise takes the current item's path)
  882. * @param int $recursivity level of recursivity we're in
  883. *
  884. * @return array List of file paths.
  885. * An additional field containing 'local' or 'remote' helps determine if
  886. * the file should be copied into the zip or just linked
  887. */
  888. public function get_resources_from_source(
  889. $type = null,
  890. $abs_path = null,
  891. $recursivity = 1
  892. ) {
  893. $max = 5;
  894. if ($recursivity > $max) {
  895. return [];
  896. }
  897. $type = empty($type) ? $this->get_type() : $type;
  898. if (!isset($abs_path)) {
  899. $path = $this->get_file_path();
  900. $abs_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$path;
  901. }
  902. $files_list = [];
  903. switch ($type) {
  904. case TOOL_DOCUMENT:
  905. case TOOL_QUIZ:
  906. case 'sco':
  907. // Get the document and, if HTML, open it.
  908. if (!is_file($abs_path)) {
  909. // The file could not be found.
  910. return false;
  911. }
  912. // for now, read the whole file in one go (that's gonna be
  913. // a problem when the file is too big).
  914. $info = pathinfo($abs_path);
  915. $ext = $info['extension'];
  916. switch (strtolower($ext)) {
  917. case 'html':
  918. case 'htm':
  919. case 'shtml':
  920. case 'css':
  921. $wantedAttributes = [
  922. 'src',
  923. 'url',
  924. '@import',
  925. 'href',
  926. 'value',
  927. ];
  928. // Parse it for included resources.
  929. $fileContent = file_get_contents($abs_path);
  930. // Get an array of attributes from the HTML source.
  931. $attributes = DocumentManager::parse_HTML_attributes(
  932. $fileContent,
  933. $wantedAttributes
  934. );
  935. // Look at 'src' attributes in this file
  936. foreach ($wantedAttributes as $attr) {
  937. if (isset($attributes[$attr])) {
  938. // Find which kind of path these are (local or remote).
  939. $sources = $attributes[$attr];
  940. foreach ($sources as $source) {
  941. // Skip what is obviously not a resource.
  942. if (strpos($source, "+this.")) {
  943. continue;
  944. } // javascript code - will still work unaltered.
  945. if (strpos($source, '.') === false) {
  946. continue;
  947. } // No dot, should not be an external file anyway.
  948. if (strpos($source, 'mailto:')) {
  949. continue;
  950. } // mailto link.
  951. if (strpos($source, ';') &&
  952. !strpos($source, '&amp;')
  953. ) {
  954. continue;
  955. } // Avoid code - that should help.
  956. if ($attr == 'value') {
  957. if (strpos($source, 'mp3file')) {
  958. $files_list[] = [
  959. substr(
  960. $source,
  961. 0,
  962. strpos(
  963. $source,
  964. '.swf'
  965. ) + 4
  966. ),
  967. 'local',
  968. 'abs',
  969. ];
  970. $mp3file = substr(
  971. $source,
  972. strpos(
  973. $source,
  974. 'mp3file='
  975. ) + 8
  976. );
  977. if (substr($mp3file, 0, 1) == '/') {
  978. $files_list[] = [
  979. $mp3file,
  980. 'local',
  981. 'abs',
  982. ];
  983. } else {
  984. $files_list[] = [
  985. $mp3file,
  986. 'local',
  987. 'rel',
  988. ];
  989. }
  990. } elseif (strpos($source, 'flv=') === 0) {
  991. $source = substr($source, 4);
  992. if (strpos($source, '&') > 0) {
  993. $source = substr(
  994. $source,
  995. 0,
  996. strpos($source, '&')
  997. );
  998. }
  999. if (strpos($source, '://') > 0) {
  1000. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1001. // We found the current portal url.
  1002. $files_list[] = [
  1003. $source,
  1004. 'local',
  1005. 'url',
  1006. ];
  1007. } else {
  1008. // We didn't find any trace of current portal.
  1009. $files_list[] = [
  1010. $source,
  1011. 'remote',
  1012. 'url',
  1013. ];
  1014. }
  1015. } else {
  1016. $files_list[] = [
  1017. $source,
  1018. 'local',
  1019. 'abs',
  1020. ];
  1021. }
  1022. continue; // Skipping anything else to avoid two entries
  1023. //(while the others can have sub-files in their url, flv's can't).
  1024. }
  1025. }
  1026. if (strpos($source, '://') > 0) {
  1027. // Cut at '?' in a URL with params.
  1028. if (strpos($source, '?') > 0) {
  1029. $second_part = substr(
  1030. $source,
  1031. strpos($source, '?')
  1032. );
  1033. if (strpos($second_part, '://') > 0) {
  1034. // If the second part of the url contains a url too,
  1035. // treat the second one before cutting.
  1036. $pos1 = strpos(
  1037. $second_part,
  1038. '='
  1039. );
  1040. $pos2 = strpos(
  1041. $second_part,
  1042. '&'
  1043. );
  1044. $second_part = substr(
  1045. $second_part,
  1046. $pos1 + 1,
  1047. $pos2 - ($pos1 + 1)
  1048. );
  1049. if (strpos($second_part, api_get_path(WEB_PATH)) !== false) {
  1050. // We found the current portal url.
  1051. $files_list[] = [
  1052. $second_part,
  1053. 'local',
  1054. 'url',
  1055. ];
  1056. $in_files_list[] = self::get_resources_from_source(
  1057. TOOL_DOCUMENT,
  1058. $second_part,
  1059. $recursivity + 1
  1060. );
  1061. if (count($in_files_list) > 0) {
  1062. $files_list = array_merge(
  1063. $files_list,
  1064. $in_files_list
  1065. );
  1066. }
  1067. } else {
  1068. // We didn't find any trace of current portal.
  1069. $files_list[] = [
  1070. $second_part,
  1071. 'remote',
  1072. 'url',
  1073. ];
  1074. }
  1075. } elseif (strpos($second_part, '=') > 0) {
  1076. if (substr($second_part, 0, 1) === '/') {
  1077. // Link starts with a /,
  1078. // making it absolute (relative to DocumentRoot).
  1079. $files_list[] = [
  1080. $second_part,
  1081. 'local',
  1082. 'abs',
  1083. ];
  1084. $in_files_list[] = self::get_resources_from_source(
  1085. TOOL_DOCUMENT,
  1086. $second_part,
  1087. $recursivity + 1
  1088. );
  1089. if (count($in_files_list) > 0) {
  1090. $files_list = array_merge(
  1091. $files_list,
  1092. $in_files_list
  1093. );
  1094. }
  1095. } elseif (strstr($second_part, '..') === 0) {
  1096. // Link is relative but going back in the hierarchy.
  1097. $files_list[] = [
  1098. $second_part,
  1099. 'local',
  1100. 'rel',
  1101. ];
  1102. $dir = dirname(
  1103. $abs_path
  1104. );
  1105. $new_abs_path = realpath(
  1106. $dir.'/'.$second_part
  1107. );
  1108. $in_files_list[] = self::get_resources_from_source(
  1109. TOOL_DOCUMENT,
  1110. $new_abs_path,
  1111. $recursivity + 1
  1112. );
  1113. if (count($in_files_list) > 0) {
  1114. $files_list = array_merge(
  1115. $files_list,
  1116. $in_files_list
  1117. );
  1118. }
  1119. } else {
  1120. // No starting '/', making it relative to current document's path.
  1121. if (substr($second_part, 0, 2) == './') {
  1122. $second_part = substr(
  1123. $second_part,
  1124. 2
  1125. );
  1126. }
  1127. $files_list[] = [
  1128. $second_part,
  1129. 'local',
  1130. 'rel',
  1131. ];
  1132. $dir = dirname(
  1133. $abs_path
  1134. );
  1135. $new_abs_path = realpath(
  1136. $dir.'/'.$second_part
  1137. );
  1138. $in_files_list[] = self::get_resources_from_source(
  1139. TOOL_DOCUMENT,
  1140. $new_abs_path,
  1141. $recursivity + 1
  1142. );
  1143. if (count($in_files_list) > 0) {
  1144. $files_list = array_merge(
  1145. $files_list,
  1146. $in_files_list
  1147. );
  1148. }
  1149. }
  1150. }
  1151. // Leave that second part behind now.
  1152. $source = substr(
  1153. $source,
  1154. 0,
  1155. strpos($source, '?')
  1156. );
  1157. if (strpos($source, '://') > 0) {
  1158. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1159. // We found the current portal url.
  1160. $files_list[] = [
  1161. $source,
  1162. 'local',
  1163. 'url',
  1164. ];
  1165. $in_files_list[] = self::get_resources_from_source(
  1166. TOOL_DOCUMENT,
  1167. $source,
  1168. $recursivity + 1
  1169. );
  1170. if (count($in_files_list) > 0) {
  1171. $files_list = array_merge(
  1172. $files_list,
  1173. $in_files_list
  1174. );
  1175. }
  1176. } else {
  1177. // We didn't find any trace of current portal.
  1178. $files_list[] = [
  1179. $source,
  1180. 'remote',
  1181. 'url',
  1182. ];
  1183. }
  1184. } else {
  1185. // No protocol found, make link local.
  1186. if (substr($source, 0, 1) === '/') {
  1187. // Link starts with a /, making it absolute (relative to DocumentRoot).
  1188. $files_list[] = [
  1189. $source,
  1190. 'local',
  1191. 'abs',
  1192. ];
  1193. $in_files_list[] = self::get_resources_from_source(
  1194. TOOL_DOCUMENT,
  1195. $source,
  1196. $recursivity + 1
  1197. );
  1198. if (count($in_files_list) > 0) {
  1199. $files_list = array_merge(
  1200. $files_list,
  1201. $in_files_list
  1202. );
  1203. }
  1204. } elseif (strstr($source, '..') === 0) {
  1205. // Link is relative but going back in the hierarchy.
  1206. $files_list[] = [
  1207. $source,
  1208. 'local',
  1209. 'rel',
  1210. ];
  1211. $dir = dirname(
  1212. $abs_path
  1213. );
  1214. $new_abs_path = realpath(
  1215. $dir.'/'.$source
  1216. );
  1217. $in_files_list[] = self::get_resources_from_source(
  1218. TOOL_DOCUMENT,
  1219. $new_abs_path,
  1220. $recursivity + 1
  1221. );
  1222. if (count($in_files_list) > 0) {
  1223. $files_list = array_merge(
  1224. $files_list,
  1225. $in_files_list
  1226. );
  1227. }
  1228. } else {
  1229. // No starting '/', making it relative to current document's path.
  1230. if (substr($source, 0, 2) == './') {
  1231. $source = substr(
  1232. $source,
  1233. 2
  1234. );
  1235. }
  1236. $files_list[] = [
  1237. $source,
  1238. 'local',
  1239. 'rel',
  1240. ];
  1241. $dir = dirname(
  1242. $abs_path
  1243. );
  1244. $new_abs_path = realpath(
  1245. $dir.'/'.$source
  1246. );
  1247. $in_files_list[] = self::get_resources_from_source(
  1248. TOOL_DOCUMENT,
  1249. $new_abs_path,
  1250. $recursivity + 1
  1251. );
  1252. if (count($in_files_list) > 0) {
  1253. $files_list = array_merge(
  1254. $files_list,
  1255. $in_files_list
  1256. );
  1257. }
  1258. }
  1259. }
  1260. }
  1261. // Found some protocol there.
  1262. if (strpos($source, api_get_path(WEB_PATH)) !== false) {
  1263. // We found the current portal url.
  1264. $files_list[] = [
  1265. $source,
  1266. 'local',
  1267. 'url',
  1268. ];
  1269. $in_files_list[] = self::get_resources_from_source(
  1270. TOOL_DOCUMENT,
  1271. $source,
  1272. $recursivity + 1
  1273. );
  1274. if (count($in_files_list) > 0) {
  1275. $files_list = array_merge(
  1276. $files_list,
  1277. $in_files_list
  1278. );
  1279. }
  1280. } else {
  1281. // We didn't find any trace of current portal.
  1282. $files_list[] = [
  1283. $source,
  1284. 'remote',
  1285. 'url',
  1286. ];
  1287. }
  1288. } else {
  1289. // No protocol found, make link local.
  1290. if (substr($source, 0, 1) === '/') {
  1291. // Link starts with a /, making it absolute (relative to DocumentRoot).
  1292. $files_list[] = [
  1293. $source,
  1294. 'local',
  1295. 'abs',
  1296. ];
  1297. $in_files_list[] = self::get_resources_from_source(
  1298. TOOL_DOCUMENT,
  1299. $source,
  1300. $recursivity + 1
  1301. );
  1302. if (count($in_files_list) > 0) {
  1303. $files_list = array_merge(
  1304. $files_list,
  1305. $in_files_list
  1306. );
  1307. }
  1308. } elseif (strstr($source, '..') === 0) {
  1309. // Link is relative but going back in the hierarchy.
  1310. $files_list[] = [
  1311. $source,
  1312. 'local',
  1313. 'rel',
  1314. ];
  1315. $dir = dirname($abs_path);
  1316. $new_abs_path = realpath(
  1317. $dir.'/'.$source
  1318. );
  1319. $in_files_list[] = self::get_resources_from_source(
  1320. TOOL_DOCUMENT,
  1321. $new_abs_path,
  1322. $recursivity + 1
  1323. );
  1324. if (count($in_files_list) > 0) {
  1325. $files_list = array_merge(
  1326. $files_list,
  1327. $in_files_list
  1328. );
  1329. }
  1330. } else {
  1331. // No starting '/', making it relative to current document's path.
  1332. if (strpos($source, 'width=') ||
  1333. strpos($source, 'autostart=')
  1334. ) {
  1335. continue;
  1336. }
  1337. if (substr($source, 0, 2) == './') {
  1338. $source = substr(
  1339. $source,
  1340. 2
  1341. );
  1342. }
  1343. $files_list[] = [
  1344. $source,
  1345. 'local',
  1346. 'rel',
  1347. ];
  1348. $dir = dirname($abs_path);
  1349. $new_abs_path = realpath(
  1350. $dir.'/'.$source
  1351. );
  1352. $in_files_list[] = self::get_resources_from_source(
  1353. TOOL_DOCUMENT,
  1354. $new_abs_path,
  1355. $recursivity + 1
  1356. );
  1357. if (count($in_files_list) > 0) {
  1358. $files_list = array_merge(
  1359. $files_list,
  1360. $in_files_list
  1361. );
  1362. }
  1363. }
  1364. }
  1365. }
  1366. }
  1367. }
  1368. break;
  1369. default:
  1370. break;
  1371. }
  1372. break;
  1373. default: // Ignore.
  1374. break;
  1375. }
  1376. $checked_files_list = [];
  1377. $checked_array_list = [];
  1378. foreach ($files_list as $idx => $file) {
  1379. if (!empty($file[0])) {
  1380. if (!in_array($file[0], $checked_files_list)) {
  1381. $checked_files_list[] = $files_list[$idx][0];
  1382. $checked_array_list[] = $files_list[$idx];
  1383. }
  1384. }
  1385. }
  1386. return $checked_array_list;
  1387. }
  1388. /**
  1389. * Gets the score.
  1390. *
  1391. * @return float The current score or 0 if no score set yet
  1392. */
  1393. public function get_score()
  1394. {
  1395. $res = 0;
  1396. if (!empty($this->current_score)) {
  1397. $res = $this->current_score;
  1398. }
  1399. return $res;
  1400. }
  1401. /**
  1402. * Gets the item status.
  1403. *
  1404. * @param bool $check_db Do or don't check into the database for the
  1405. * latest value. Optional. Default is true
  1406. * @param bool $update_local Do or don't update the local attribute
  1407. * value with what's been found in DB
  1408. *
  1409. * @return string Current status or 'Not attempted' if no status set yet
  1410. */
  1411. public function get_status($check_db = true, $update_local = false)
  1412. {
  1413. $course_id = api_get_course_int_id();
  1414. $debug = self::DEBUG;
  1415. if ($debug > 0) {
  1416. error_log('learnpathItem::get_status() on item '.$this->db_id, 0);
  1417. }
  1418. if ($check_db) {
  1419. if ($debug > 2) {
  1420. error_log('learnpathItem::get_status(): checking db', 0);
  1421. }
  1422. if (!empty($this->db_item_view_id) && !empty($course_id)) {
  1423. $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1424. $sql = "SELECT status FROM $table
  1425. WHERE
  1426. c_id = $course_id AND
  1427. iid = '".$this->db_item_view_id."' AND
  1428. view_count = '".$this->get_attempt_id()."'";
  1429. $res = Database::query($sql);
  1430. if (Database::num_rows($res) == 1) {
  1431. $row = Database::fetch_array($res);
  1432. if ($update_local) {
  1433. $this->set_status($row['status']);
  1434. }
  1435. return $row['status'];
  1436. }
  1437. }
  1438. } else {
  1439. if (!empty($this->status)) {
  1440. return $this->status;
  1441. }
  1442. }
  1443. return $this->possible_status[0];
  1444. }
  1445. /**
  1446. * Gets the suspend data.
  1447. */
  1448. public function get_suspend_data()
  1449. {
  1450. // TODO: Improve cleaning of breaklines ... it works but is it really
  1451. // a beautiful way to do it ?
  1452. if (!empty($this->current_data)) {
  1453. return str_replace(
  1454. ["\r", "\n", "'"],
  1455. ['\r', '\n', "\\'"],
  1456. $this->current_data
  1457. );
  1458. }
  1459. return '';
  1460. }
  1461. /**
  1462. * @param string $origin
  1463. * @param string $time
  1464. *
  1465. * @return string
  1466. */
  1467. public static function getScormTimeFromParameter(
  1468. $origin = 'php',
  1469. $time = null
  1470. ) {
  1471. $h = get_lang('h');
  1472. if (!isset($time)) {
  1473. if ($origin == 'js') {
  1474. return '00 : 00: 00';
  1475. }
  1476. return '00 '.$h.' 00 \' 00"';
  1477. }
  1478. return api_format_time($time, $origin);
  1479. }
  1480. /**
  1481. * Gets the total time spent on this item view so far.
  1482. *
  1483. * @param string $origin Origin of the request. If coming from PHP,
  1484. * send formatted as xxhxx'xx", otherwise use scorm format 00:00:00
  1485. * @param int|null $given_time Given time is a default time to return formatted
  1486. * @param bool $query_db Whether to get the value from db or from memory
  1487. *
  1488. * @return string A string with the time in SCORM format
  1489. */
  1490. public function get_scorm_time(
  1491. $origin = 'php',
  1492. $given_time = null,
  1493. $query_db = false
  1494. ) {
  1495. $time = null;
  1496. $course_id = api_get_course_int_id();
  1497. if (!isset($given_time)) {
  1498. if (self::DEBUG > 2) {
  1499. error_log(
  1500. 'learnpathItem::get_scorm_time(): given time empty, current_start_time = '.$this->current_start_time,
  1501. 0
  1502. );
  1503. }
  1504. if ($query_db === true) {
  1505. $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1506. $sql = "SELECT start_time, total_time
  1507. FROM $table
  1508. WHERE
  1509. c_id = $course_id AND
  1510. iid = '".$this->db_item_view_id."' AND
  1511. view_count = '".$this->get_attempt_id()."'";
  1512. $res = Database::query($sql);
  1513. $row = Database::fetch_array($res);
  1514. $start = $row['start_time'];
  1515. $stop = $start + $row['total_time'];
  1516. } else {
  1517. $start = $this->current_start_time;
  1518. $stop = $this->current_stop_time;
  1519. }
  1520. if (!empty($start)) {
  1521. if (!empty($stop)) {
  1522. $time = $stop - $start;
  1523. } else {
  1524. $time = time() - $start;
  1525. }
  1526. }
  1527. } else {
  1528. $time = $given_time;
  1529. }
  1530. if (self::DEBUG > 2) {
  1531. error_log(
  1532. 'learnpathItem::get_scorm_time(): intermediate = '.$time,
  1533. 0
  1534. );
  1535. }
  1536. $time = api_format_time($time, $origin);
  1537. return $time;
  1538. }
  1539. /**
  1540. * Get the extra terms (tags) that identify this item.
  1541. *
  1542. * @return mixed
  1543. */
  1544. public function get_terms()
  1545. {
  1546. $table = Database::get_course_table(TABLE_LP_ITEM);
  1547. $sql = "SELECT * FROM $table
  1548. WHERE iid = ".intval($this->db_id);
  1549. $res = Database::query($sql);
  1550. $row = Database::fetch_array($res);
  1551. return $row['terms'];
  1552. }
  1553. /**
  1554. * Returns the item's title.
  1555. *
  1556. * @return string Title
  1557. */
  1558. public function get_title()
  1559. {
  1560. if (empty($this->title)) {
  1561. return '';
  1562. }
  1563. return $this->title;
  1564. }
  1565. /**
  1566. * Returns the total time used to see that item.
  1567. *
  1568. * @return int Total time
  1569. */
  1570. public function get_total_time()
  1571. {
  1572. $debug = self::DEBUG;
  1573. if ($debug) {
  1574. error_log(
  1575. 'learnpathItem::get_total_time() for item '.$this->db_id.
  1576. ' - Initially, current_start_time = '.$this->current_start_time.
  1577. ' and current_stop_time = '.$this->current_stop_time,
  1578. 0
  1579. );
  1580. }
  1581. if ($this->current_start_time == 0) {
  1582. // Shouldn't be necessary thanks to the open() method.
  1583. if ($debug) {
  1584. error_log(
  1585. 'learnpathItem::get_total_time() - Current start time was empty',
  1586. 0
  1587. );
  1588. }
  1589. $this->current_start_time = time();
  1590. }
  1591. if (time() < $this->current_stop_time ||
  1592. $this->current_stop_time == 0
  1593. ) {
  1594. if ($debug) {
  1595. error_log(
  1596. 'learnpathItem::get_total_time() - Current stop time was '
  1597. .'greater than the current time or was empty',
  1598. 0
  1599. );
  1600. }
  1601. // If this case occurs, then we risk to write huge time data in db.
  1602. // In theory, stop time should be *always* updated here, but it
  1603. // might be used in some unknown goal.
  1604. $this->current_stop_time = time();
  1605. }
  1606. $time = $this->current_stop_time - $this->current_start_time;
  1607. if ($time < 0) {
  1608. if ($debug) {
  1609. error_log(
  1610. 'learnpathItem::get_total_time() - Time smaller than 0. Returning 0',
  1611. 0
  1612. );
  1613. }
  1614. return 0;
  1615. } else {
  1616. $time = $this->fixAbusiveTime($time);
  1617. if ($debug) {
  1618. error_log(
  1619. 'Current start time = '.$this->current_start_time.', current stop time = '.
  1620. $this->current_stop_time.' Returning '.$time."-----------\n"
  1621. );
  1622. }
  1623. return $time;
  1624. }
  1625. }
  1626. /**
  1627. * Sometimes time recorded for a learning path item is superior to the maximum allowed duration of the session.
  1628. * In this case, this session resets the time for that particular learning path item to 5 minutes
  1629. * (something more realistic, that is also used when leaving the portal without closing one's session).
  1630. *
  1631. * @param int $time
  1632. *
  1633. * @return int
  1634. */
  1635. public function fixAbusiveTime($time)
  1636. {
  1637. // Code based from Event::courseLogout
  1638. $sessionLifetime = api_get_configuration_value('session_lifetime');
  1639. // If session life time too big use 1 hour
  1640. if (empty($sessionLifetime) || $sessionLifetime > 86400) {
  1641. $sessionLifetime = 3600;
  1642. }
  1643. if (!Tracking::minimumTimeAvailable(api_get_session_id(), api_get_course_int_id())) {
  1644. $fixedAddedMinute = 5 * 60; // Add only 5 minutes
  1645. if ($time > $sessionLifetime) {
  1646. error_log("fixAbusiveTime: Total time is too big: $time replaced with: $fixedAddedMinute");
  1647. error_log("item_id : ".$this->db_id." lp_item_view.iid: ".$this->db_item_view_id);
  1648. $time = $fixedAddedMinute;
  1649. }
  1650. return $time;
  1651. } else {
  1652. // Calulate minimum and accumulated time
  1653. $user_id = api_get_user_id();
  1654. $myLP = learnpath::getLpFromSession(api_get_course_id(), $this->lp_id, $user_id);
  1655. $timeLp = $myLP->getAccumulateWorkTime();
  1656. $timeTotalCourse = $myLP->getAccumulateWorkTimeTotalCourse();
  1657. /*
  1658. $timeLp = $_SESSION['oLP']->getAccumulateWorkTime();
  1659. $timeTotalCourse = $_SESSION['oLP']->getAccumulateWorkTimeTotalCourse();
  1660. */
  1661. // Minimum connection percentage
  1662. $perc = 100;
  1663. // Time from the course
  1664. $tc = $timeTotalCourse;
  1665. /*if (!empty($sessionId) && $sessionId != 0) {
  1666. $sql = "SELECT hours, perc FROM plugin_licences_course_session WHERE session_id = $sessionId";
  1667. $res = Database::query($sql);
  1668. if (Database::num_rows($res) > 0) {
  1669. $aux = Database::fetch_assoc($res);
  1670. $perc = $aux['perc'];
  1671. $tc = $aux['hours'] * 60;
  1672. }
  1673. }*/
  1674. // Percentage of the learning paths
  1675. $pl = 0;
  1676. if (!empty($timeTotalCourse)) {
  1677. $pl = $timeLp / $timeTotalCourse;
  1678. }
  1679. // Minimum time for each learning path
  1680. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  1681. $time_seg = intval($accumulateWorkTime * 60);
  1682. if ($time_seg < $sessionLifetime) {
  1683. $sessionLifetime = $time_seg;
  1684. }
  1685. if ($time > $sessionLifetime) {
  1686. $fixedAddedMinute = $time_seg + mt_rand(0, 300);
  1687. if (self::DEBUG > 2) {
  1688. error_log("Total time is too big: $time replaced with: $fixedAddedMinute");
  1689. }
  1690. $time = $fixedAddedMinute;
  1691. }
  1692. return $time;
  1693. }
  1694. }
  1695. /**
  1696. * Gets the item type.
  1697. *
  1698. * @return string The item type (can be doc, dir, sco, asset)
  1699. */
  1700. public function get_type()
  1701. {
  1702. $res = 'asset';
  1703. if (!empty($this->type)) {
  1704. $res = $this->type;
  1705. }
  1706. return $res;
  1707. }
  1708. /**
  1709. * Gets the view count for this item.
  1710. *
  1711. * @return int Number of attempts or 0
  1712. */
  1713. public function get_view_count()
  1714. {
  1715. if (!empty($this->attempt_id)) {
  1716. return $this->attempt_id;
  1717. }
  1718. return 0;
  1719. }
  1720. /**
  1721. * Tells if an item is done ('completed','passed','succeeded') or not.
  1722. *
  1723. * @return bool True if the item is done ('completed','passed','succeeded'),
  1724. * false otherwise
  1725. */
  1726. public function is_done()
  1727. {
  1728. $completedStatusList = [
  1729. 'completed',
  1730. 'passed',
  1731. 'succeeded',
  1732. 'failed',
  1733. ];
  1734. if ($this->status_is($completedStatusList)) {
  1735. if (self::DEBUG > 2) {
  1736. error_log(
  1737. 'learnpath::is_done() - Item '.$this->get_id(
  1738. ).' is complete',
  1739. 0
  1740. );
  1741. }
  1742. return true;
  1743. } else {
  1744. if (self::DEBUG > 2) {
  1745. error_log(
  1746. 'learnpath::is_done() - Item '.$this->get_id(
  1747. ).' is not complete',
  1748. 0
  1749. );
  1750. }
  1751. return false;
  1752. }
  1753. }
  1754. /**
  1755. * Tells if a restart is allowed (take it from $this->prevent_reinit and $this->status).
  1756. *
  1757. * @return int -1 if retaking the sco another time for credit is not allowed,
  1758. * 0 if it is not allowed but the item has to be finished
  1759. * 1 if it is allowed. Defaults to 1
  1760. */
  1761. public function isRestartAllowed()
  1762. {
  1763. $restart = 1;
  1764. $mystatus = $this->get_status(true);
  1765. if ($this->get_prevent_reinit() > 0) {
  1766. // If prevent_reinit == 1 (or more)
  1767. // If status is not attempted or incomplete, authorize retaking (of the same) anyway. Otherwise:
  1768. if ($mystatus != $this->possible_status[0] && $mystatus != $this->possible_status[1]) {
  1769. $restart = -1;
  1770. } else { //status incompleted or not attempted
  1771. $restart = 0;
  1772. }
  1773. } else {
  1774. if ($mystatus == $this->possible_status[0] || $mystatus == $this->possible_status[1]) {
  1775. $restart = -1;
  1776. }
  1777. }
  1778. if (self::DEBUG > 2) {
  1779. error_log(
  1780. 'New LP - End of learnpathItem::isRestartAllowed() - Returning '.$restart,
  1781. 0
  1782. );
  1783. }
  1784. return $restart;
  1785. }
  1786. /**
  1787. * Opens/launches the item. Initialises runtime values.
  1788. *
  1789. * @param bool $allow_new_attempt
  1790. *
  1791. * @return bool true on success, false on failure
  1792. */
  1793. public function open($allow_new_attempt = false)
  1794. {
  1795. if (self::DEBUG > 0) {
  1796. error_log('learnpathItem::open()', 0);
  1797. }
  1798. if ($this->prevent_reinit == 0) {
  1799. $this->current_score = 0;
  1800. $this->current_start_time = time();
  1801. // In this case, as we are opening the item, what is important to us
  1802. // is the database status, in order to know if this item has already
  1803. // been used in the past (rather than just loaded and modified by
  1804. // some javascript but not written in the database).
  1805. // If the database status is different from 'not attempted', we can
  1806. // consider this item has already been used, and as such we can
  1807. // open a new attempt. Otherwise, we'll just reuse the current
  1808. // attempt, which is generally created the first time the item is
  1809. // loaded (for example as part of the table of contents).
  1810. $stat = $this->get_status(true);
  1811. if ($allow_new_attempt && isset($stat) && ($stat != $this->possible_status[0])) {
  1812. $this->attempt_id = $this->attempt_id + 1; // Open a new attempt.
  1813. }
  1814. $this->status = $this->possible_status[1];
  1815. } else {
  1816. /*if ($this->current_start_time == 0) {
  1817. // Small exception for start time, to avoid amazing values.
  1818. $this->current_start_time = time();
  1819. }*/
  1820. // If we don't init start time here, the time is sometimes calculated from the last start time.
  1821. $this->current_start_time = time();
  1822. }
  1823. }
  1824. /**
  1825. * Outputs the item contents.
  1826. *
  1827. * @return string HTML file (displayable in an <iframe>) or empty string if no path defined
  1828. */
  1829. public function output()
  1830. {
  1831. if (!empty($this->path) and is_file($this->path)) {
  1832. $output = '';
  1833. $output .= file_get_contents($this->path);
  1834. return $output;
  1835. }
  1836. return '';
  1837. }
  1838. /**
  1839. * Parses the prerequisites string with the AICC logic language.
  1840. *
  1841. * @param string $prereqs_string The prerequisites string as it figures in imsmanifest.xml
  1842. * @param array $items Array of items in the current learnpath object.
  1843. * Although we're in the learnpathItem object, it's necessary to have
  1844. * a list of all items to be able to check the current item's prerequisites
  1845. * @param array $refs_list list of references
  1846. * (the "ref" column in the lp_item table) that are strings used in the
  1847. * expression of prerequisites
  1848. * @param int $user_id The user ID. In some cases like Chamilo quizzes,
  1849. * it's necessary to have the user ID to query other tables (like the results of quizzes)
  1850. *
  1851. * @return bool True if the list of prerequisites given is entirely satisfied, false otherwise
  1852. */
  1853. public function parse_prereq($prereqs_string, $items, $refs_list, $user_id)
  1854. {
  1855. $debug = self::DEBUG;
  1856. if ($debug > 0) {
  1857. error_log(
  1858. 'learnpathItem::parse_prereq() for learnpath '.$this->lp_id.' with string '.$prereqs_string,
  1859. 0
  1860. );
  1861. }
  1862. $course_id = api_get_course_int_id();
  1863. $sessionId = api_get_session_id();
  1864. // Deal with &, |, ~, =, <>, {}, ,, X*, () in reverse order.
  1865. $this->prereq_alert = '';
  1866. // First parse all parenthesis by using a sequential loop
  1867. // (looking for less-inclusives first).
  1868. if ($prereqs_string == '_true_') {
  1869. return true;
  1870. }
  1871. if ($prereqs_string == '_false_') {
  1872. if (empty($this->prereq_alert)) {
  1873. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1874. }
  1875. return false;
  1876. }
  1877. while (strpos($prereqs_string, '(') !== false) {
  1878. // Remove any () set and replace with its value.
  1879. $matches = [];
  1880. $res = preg_match_all(
  1881. '/(\(([^\(\)]*)\))/',
  1882. $prereqs_string,
  1883. $matches
  1884. );
  1885. if ($res) {
  1886. foreach ($matches[2] as $id => $match) {
  1887. $str_res = $this->parse_prereq(
  1888. $match,
  1889. $items,
  1890. $refs_list,
  1891. $user_id
  1892. );
  1893. if ($str_res) {
  1894. $prereqs_string = str_replace(
  1895. $matches[1][$id],
  1896. '_true_',
  1897. $prereqs_string
  1898. );
  1899. } else {
  1900. $prereqs_string = str_replace(
  1901. $matches[1][$id],
  1902. '_false_',
  1903. $prereqs_string
  1904. );
  1905. }
  1906. }
  1907. }
  1908. }
  1909. // Parenthesis removed, now look for ORs as it is the lesser-priority
  1910. // binary operator (= always uses one text operand).
  1911. if (strpos($prereqs_string, '|') === false) {
  1912. if ($debug) {
  1913. error_log('New LP - Didnt find any OR, looking for AND', 0);
  1914. }
  1915. if (strpos($prereqs_string, '&') !== false) {
  1916. $list = explode('&', $prereqs_string);
  1917. if (count($list) > 1) {
  1918. $andstatus = true;
  1919. foreach ($list as $condition) {
  1920. $andstatus = $andstatus && $this->parse_prereq(
  1921. $condition,
  1922. $items,
  1923. $refs_list,
  1924. $user_id
  1925. );
  1926. if (!$andstatus) {
  1927. if ($debug) {
  1928. error_log(
  1929. 'New LP - One condition in AND was false, short-circuit',
  1930. 0
  1931. );
  1932. }
  1933. break;
  1934. }
  1935. }
  1936. if (empty($this->prereq_alert) && !$andstatus) {
  1937. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1938. }
  1939. return $andstatus;
  1940. } else {
  1941. if (isset($items[$refs_list[$list[0]]])) {
  1942. $status = $items[$refs_list[$list[0]]]->get_status(true);
  1943. $returnstatus = ($status == $this->possible_status[2]) || ($status == $this->possible_status[3]);
  1944. if (empty($this->prereq_alert) && !$returnstatus) {
  1945. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1946. }
  1947. return $returnstatus;
  1948. }
  1949. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1950. return false;
  1951. }
  1952. } else {
  1953. // No ORs found, now look for ANDs.
  1954. if ($debug) {
  1955. error_log('New LP - Didnt find any AND, looking for =', 0);
  1956. }
  1957. if (strpos($prereqs_string, '=') !== false) {
  1958. if ($debug) {
  1959. error_log('New LP - Found =, looking into it', 0);
  1960. }
  1961. // We assume '=' signs only appear when there's nothing else around.
  1962. $params = explode('=', $prereqs_string);
  1963. if (count($params) == 2) {
  1964. // Right number of operands.
  1965. if (isset($items[$refs_list[$params[0]]])) {
  1966. $status = $items[$refs_list[$params[0]]]->get_status(true);
  1967. $returnstatus = $status == $params[1];
  1968. if (empty($this->prereq_alert) && !$returnstatus) {
  1969. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1970. }
  1971. return $returnstatus;
  1972. }
  1973. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1974. return false;
  1975. }
  1976. } else {
  1977. // No ANDs found, look for <>
  1978. if ($debug) {
  1979. error_log(
  1980. 'New LP - Didnt find any =, looking for <>',
  1981. 0
  1982. );
  1983. }
  1984. if (strpos($prereqs_string, '<>') !== false) {
  1985. if ($debug) {
  1986. error_log('New LP - Found <>, looking into it', 0);
  1987. }
  1988. // We assume '<>' signs only appear when there's nothing else around.
  1989. $params = explode('<>', $prereqs_string);
  1990. if (count($params) == 2) {
  1991. // Right number of operands.
  1992. if (isset($items[$refs_list[$params[0]]])) {
  1993. $status = $items[$refs_list[$params[0]]]->get_status(true);
  1994. $returnstatus = $status != $params[1];
  1995. if (empty($this->prereq_alert) && !$returnstatus) {
  1996. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  1997. }
  1998. return $returnstatus;
  1999. }
  2000. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2001. return false;
  2002. }
  2003. } else {
  2004. // No <> found, look for ~ (unary)
  2005. if ($debug) {
  2006. error_log(
  2007. 'New LP - Didnt find any =, looking for ~',
  2008. 0
  2009. );
  2010. }
  2011. // Only remains: ~ and X*{}
  2012. if (strpos($prereqs_string, '~') !== false) {
  2013. // Found NOT.
  2014. if ($debug) {
  2015. error_log(
  2016. 'New LP - Found ~, looking into it',
  2017. 0
  2018. );
  2019. }
  2020. $list = [];
  2021. $myres = preg_match(
  2022. '/~([^(\d+\*)\{]*)/',
  2023. $prereqs_string,
  2024. $list
  2025. );
  2026. if ($myres) {
  2027. $returnstatus = !$this->parse_prereq(
  2028. $list[1],
  2029. $items,
  2030. $refs_list,
  2031. $user_id
  2032. );
  2033. if (empty($this->prereq_alert) && !$returnstatus) {
  2034. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2035. }
  2036. return $returnstatus;
  2037. } else {
  2038. // Strange...
  2039. if ($debug) {
  2040. error_log(
  2041. 'New LP - Found ~ but strange string: '.$prereqs_string,
  2042. 0
  2043. );
  2044. }
  2045. }
  2046. } else {
  2047. // Finally, look for sets/groups
  2048. if ($debug) {
  2049. error_log(
  2050. 'New LP - Didnt find any ~, looking for groups',
  2051. 0
  2052. );
  2053. }
  2054. // Only groups here.
  2055. $groups = [];
  2056. $groups_there = preg_match_all(
  2057. '/((\d+\*)?\{([^\}]+)\}+)/',
  2058. $prereqs_string,
  2059. $groups
  2060. );
  2061. if ($groups_there) {
  2062. foreach ($groups[1] as $gr) {
  2063. // Only take the results that correspond to
  2064. // the big brackets-enclosed condition.
  2065. if ($debug) {
  2066. error_log(
  2067. 'New LP - Dealing with group '.$gr,
  2068. 0
  2069. );
  2070. }
  2071. $multi = [];
  2072. $mycond = false;
  2073. if (preg_match(
  2074. '/(\d+)\*\{([^\}]+)\}/',
  2075. $gr,
  2076. $multi
  2077. )
  2078. ) {
  2079. if ($debug) {
  2080. error_log(
  2081. 'New LP - Found multiplier '.$multi[0],
  2082. 0
  2083. );
  2084. }
  2085. $count = $multi[1];
  2086. $list = explode(',', $multi[2]);
  2087. $mytrue = 0;
  2088. foreach ($list as $cond) {
  2089. if (isset($items[$refs_list[$cond]])) {
  2090. $status = $items[$refs_list[$cond]]->get_status(true);
  2091. if ($status == $this->possible_status[2] ||
  2092. $status == $this->possible_status[3]
  2093. ) {
  2094. $mytrue++;
  2095. if ($debug) {
  2096. error_log(
  2097. 'New LP - Found true item, counting.. ('.($mytrue).')',
  2098. 0
  2099. );
  2100. }
  2101. }
  2102. } else {
  2103. if ($debug) {
  2104. error_log(
  2105. 'New LP - item '.$cond.' does not exist in items list',
  2106. 0
  2107. );
  2108. }
  2109. }
  2110. }
  2111. if ($mytrue >= $count) {
  2112. if ($debug) {
  2113. error_log(
  2114. 'New LP - Got enough true results, return true',
  2115. 0
  2116. );
  2117. }
  2118. $mycond = true;
  2119. } else {
  2120. if ($debug) {
  2121. error_log(
  2122. 'New LP - Not enough true results',
  2123. 0
  2124. );
  2125. }
  2126. }
  2127. } else {
  2128. if ($debug) {
  2129. error_log(
  2130. 'New LP - No multiplier',
  2131. 0
  2132. );
  2133. }
  2134. $list = explode(',', $gr);
  2135. $mycond = true;
  2136. foreach ($list as $cond) {
  2137. if (isset($items[$refs_list[$cond]])) {
  2138. $status = $items[$refs_list[$cond]]->get_status(true);
  2139. if ($status == $this->possible_status[2] ||
  2140. $status == $this->possible_status[3]
  2141. ) {
  2142. $mycond = true;
  2143. if ($debug) {
  2144. error_log(
  2145. 'New LP - Found true item',
  2146. 0
  2147. );
  2148. }
  2149. } else {
  2150. if ($debug) {
  2151. error_log(
  2152. 'New LP - '.
  2153. ' Found false item, the set is not true, return false',
  2154. 0
  2155. );
  2156. }
  2157. $mycond = false;
  2158. break;
  2159. }
  2160. } else {
  2161. if ($debug) {
  2162. error_log(
  2163. 'New LP - item '.$cond.' does not exist in items list',
  2164. 0
  2165. );
  2166. }
  2167. if ($debug) {
  2168. error_log(
  2169. 'New LP - Found false item, the set is not true, return false',
  2170. 0
  2171. );
  2172. }
  2173. $mycond = false;
  2174. break;
  2175. }
  2176. }
  2177. }
  2178. if (!$mycond && empty($this->prereq_alert)) {
  2179. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2180. }
  2181. return $mycond;
  2182. }
  2183. } else {
  2184. // Nothing found there either. Now return the
  2185. // value of the corresponding resource completion status.
  2186. if (isset($refs_list[$prereqs_string]) &&
  2187. isset($items[$refs_list[$prereqs_string]])
  2188. ) {
  2189. /** @var learnpathItem $itemToCheck */
  2190. $itemToCheck = $items[$refs_list[$prereqs_string]];
  2191. if ($itemToCheck->type === 'quiz') {
  2192. // 1. Checking the status in current items.
  2193. $status = $itemToCheck->get_status(true);
  2194. $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
  2195. if (!$returnstatus) {
  2196. $explanation = sprintf(
  2197. get_lang('Item %s blocks this step'),
  2198. $itemToCheck->get_title()
  2199. );
  2200. $this->prereq_alert = $explanation;
  2201. }
  2202. // For one and first attempt.
  2203. if ($this->prevent_reinit == 1) {
  2204. // 2. If is completed we check the results in the DB of the quiz.
  2205. if ($returnstatus) {
  2206. $sql = 'SELECT score, max_score
  2207. FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
  2208. WHERE
  2209. exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
  2210. exe_user_id = '.$user_id.' AND
  2211. orig_lp_id = '.$this->lp_id.' AND
  2212. orig_lp_item_id = '.$prereqs_string.' AND
  2213. status <> "incomplete" AND
  2214. c_id = '.$course_id.'
  2215. ORDER BY exe_date DESC
  2216. LIMIT 0, 1';
  2217. $rs_quiz = Database::query($sql);
  2218. if ($quiz = Database::fetch_array($rs_quiz)) {
  2219. /** @var learnpathItem $myItemToCheck */
  2220. $myItemToCheck = $items[$refs_list[$this->get_id()]];
  2221. $minScore = $myItemToCheck->getPrerequisiteMinScore();
  2222. $maxScore = $myItemToCheck->getPrerequisiteMaxScore();
  2223. if (isset($minScore) && isset($minScore)) {
  2224. // Taking min/max prerequisites values see BT#5776
  2225. if ($quiz['score'] >= $minScore &&
  2226. $quiz['score'] <= $maxScore
  2227. ) {
  2228. $returnstatus = true;
  2229. } else {
  2230. $explanation = sprintf(
  2231. get_lang('Your result at %s blocks this step'),
  2232. $itemToCheck->get_title()
  2233. );
  2234. $this->prereq_alert = $explanation;
  2235. $returnstatus = false;
  2236. }
  2237. } else {
  2238. // Classic way
  2239. if ($quiz['score'] >=
  2240. $items[$refs_list[$prereqs_string]]->get_mastery_score()
  2241. ) {
  2242. $returnstatus = true;
  2243. } else {
  2244. $explanation = sprintf(
  2245. get_lang('Your result at %s blocks this step'),
  2246. $itemToCheck->get_title()
  2247. );
  2248. $this->prereq_alert = $explanation;
  2249. $returnstatus = false;
  2250. }
  2251. }
  2252. } else {
  2253. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2254. $returnstatus = false;
  2255. }
  2256. }
  2257. } else {
  2258. // 3. For multiple attempts we check that there are minimum 1 item completed
  2259. // Checking in the database.
  2260. $sql = 'SELECT score, max_score
  2261. FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES).'
  2262. WHERE
  2263. c_id = '.$course_id.' AND
  2264. exe_exo_id = '.$items[$refs_list[$prereqs_string]]->path.' AND
  2265. exe_user_id = '.$user_id.' AND
  2266. orig_lp_id = '.$this->lp_id.' AND
  2267. orig_lp_item_id = '.$prereqs_string;
  2268. $rs_quiz = Database::query($sql);
  2269. if (Database::num_rows($rs_quiz) > 0) {
  2270. while ($quiz = Database::fetch_array($rs_quiz)) {
  2271. /** @var learnpathItem $myItemToCheck */
  2272. $myItemToCheck = $items[$refs_list[$this->get_id()]];
  2273. $minScore = $myItemToCheck->getPrerequisiteMinScore();
  2274. $maxScore = $myItemToCheck->getPrerequisiteMaxScore();
  2275. if (empty($minScore)) {
  2276. // Try with mastery_score
  2277. $masteryScoreAsMin = $myItemToCheck->get_mastery_score();
  2278. if (!empty($masteryScoreAsMin)) {
  2279. $minScore = $masteryScoreAsMin;
  2280. }
  2281. }
  2282. if (isset($minScore) && isset($minScore)) {
  2283. // Taking min/max prerequisites values see BT#5776
  2284. if ($quiz['score'] >= $minScore && $quiz['score'] <= $maxScore) {
  2285. $returnstatus = true;
  2286. break;
  2287. } else {
  2288. $explanation = sprintf(
  2289. get_lang('Your result at %s blocks this step'),
  2290. $itemToCheck->get_title()
  2291. );
  2292. $this->prereq_alert = $explanation;
  2293. $returnstatus = false;
  2294. }
  2295. } else {
  2296. if ($quiz['score'] >=
  2297. $items[$refs_list[$prereqs_string]]->get_mastery_score()
  2298. ) {
  2299. $returnstatus = true;
  2300. break;
  2301. } else {
  2302. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2303. $returnstatus = false;
  2304. }
  2305. }
  2306. }
  2307. } else {
  2308. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2309. $returnstatus = false;
  2310. }
  2311. }
  2312. if ($returnstatus === false) {
  2313. // Check results from another sessions.
  2314. $checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
  2315. if ($checkOtherSessions) {
  2316. $returnstatus = $this->getStatusFromOtherSessions(
  2317. $user_id,
  2318. $prereqs_string,
  2319. $refs_list
  2320. );
  2321. }
  2322. }
  2323. return $returnstatus;
  2324. } elseif ($itemToCheck->type === 'student_publication') {
  2325. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  2326. $workId = $items[$refs_list[$prereqs_string]]->path;
  2327. $count = get_work_count_by_student($user_id, $workId);
  2328. if ($count >= 1) {
  2329. $returnstatus = true;
  2330. } else {
  2331. $returnstatus = false;
  2332. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2333. }
  2334. return $returnstatus;
  2335. } else {
  2336. $status = $itemToCheck->get_status(false);
  2337. $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
  2338. // Check results from another sessions.
  2339. $checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
  2340. if ($checkOtherSessions && !$returnstatus) {
  2341. $returnstatus = $this->getStatusFromOtherSessions(
  2342. $user_id,
  2343. $prereqs_string,
  2344. $refs_list
  2345. );
  2346. }
  2347. if (!$returnstatus) {
  2348. $explanation = sprintf(
  2349. get_lang('Item %s blocks this step'),
  2350. $itemToCheck->get_title()
  2351. );
  2352. $this->prereq_alert = $explanation;
  2353. }
  2354. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2355. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  2356. if ($returnstatus && $this->prevent_reinit == 1) {
  2357. $sql = "SELECT iid FROM $lp_view
  2358. WHERE
  2359. c_id = $course_id AND
  2360. user_id = $user_id AND
  2361. lp_id = $this->lp_id AND
  2362. session_id = $sessionId
  2363. LIMIT 0, 1";
  2364. $rs_lp = Database::query($sql);
  2365. if (Database::num_rows($rs_lp)) {
  2366. $lp_id = Database::fetch_row($rs_lp);
  2367. $my_lp_id = $lp_id[0];
  2368. $sql = "SELECT status FROM $lp_item_view
  2369. WHERE
  2370. c_id = $course_id AND
  2371. lp_view_id = $my_lp_id AND
  2372. lp_item_id = $refs_list[$prereqs_string]
  2373. LIMIT 0, 1";
  2374. $rs_lp = Database::query($sql);
  2375. $status_array = Database::fetch_row($rs_lp);
  2376. $status = $status_array[0];
  2377. $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3];
  2378. if (!$returnstatus && empty($this->prereq_alert)) {
  2379. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2380. }
  2381. }
  2382. if ($checkOtherSessions && $returnstatus === false) {
  2383. $returnstatus = $returnstatus = $this->getStatusFromOtherSessions(
  2384. $user_id,
  2385. $prereqs_string,
  2386. $refs_list
  2387. );
  2388. }
  2389. }
  2390. return $returnstatus;
  2391. }
  2392. }
  2393. }
  2394. }
  2395. }
  2396. }
  2397. }
  2398. } else {
  2399. $list = explode("\|", $prereqs_string);
  2400. if (count($list) > 1) {
  2401. if (self::DEBUG > 1) {
  2402. error_log('New LP - Found OR, looking into it', 0);
  2403. }
  2404. $orstatus = false;
  2405. foreach ($list as $condition) {
  2406. if (self::DEBUG > 1) {
  2407. error_log(
  2408. 'New LP - Found OR, adding it ('.$condition.')',
  2409. 0
  2410. );
  2411. }
  2412. $orstatus = $orstatus || $this->parse_prereq(
  2413. $condition,
  2414. $items,
  2415. $refs_list,
  2416. $user_id
  2417. );
  2418. if ($orstatus) {
  2419. // Shortcircuit OR.
  2420. if (self::DEBUG > 1) {
  2421. error_log(
  2422. 'New LP - One condition in OR was true, short-circuit',
  2423. 0
  2424. );
  2425. }
  2426. break;
  2427. }
  2428. }
  2429. if (!$orstatus && empty($this->prereq_alert)) {
  2430. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2431. }
  2432. return $orstatus;
  2433. } else {
  2434. if (self::DEBUG > 1) {
  2435. error_log(
  2436. 'New LP - OR was found but only one elem present !?',
  2437. 0
  2438. );
  2439. }
  2440. if (isset($items[$refs_list[$list[0]]])) {
  2441. $status = $items[$refs_list[$list[0]]]->get_status(true);
  2442. $returnstatus = $status == 'completed' || $status == 'passed';
  2443. if (!$returnstatus && empty($this->prereq_alert)) {
  2444. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2445. }
  2446. return $returnstatus;
  2447. }
  2448. }
  2449. }
  2450. if (empty($this->prereq_alert)) {
  2451. $this->prereq_alert = get_lang('This learning object cannot display because the course prerequisites are not completed. This happens when a course imposes that you follow it step by step or get a minimum score in tests before you reach the next steps.');
  2452. }
  2453. if (self::DEBUG > 1) {
  2454. error_log(
  2455. 'New LP - End of parse_prereq. Error code is now '.$this->prereq_alert,
  2456. 0
  2457. );
  2458. }
  2459. return false;
  2460. }
  2461. /**
  2462. * Reinits all local values as the learnpath is restarted.
  2463. *
  2464. * @return bool True on success, false otherwise
  2465. */
  2466. public function restart()
  2467. {
  2468. if (self::DEBUG > 0) {
  2469. error_log('learnpathItem::restart()', 0);
  2470. }
  2471. $seriousGame = $this->get_seriousgame_mode();
  2472. //For serious game : We reuse same attempt_id
  2473. if ($seriousGame == 1 && $this->type == 'sco') {
  2474. // If this is a sco, Chamilo can't update the time without an
  2475. // explicit scorm call
  2476. $this->current_start_time = 0;
  2477. $this->current_stop_time = 0; //Those 0 value have this effect
  2478. $this->last_scorm_session_time = 0;
  2479. $this->save();
  2480. return true;
  2481. }
  2482. $this->save();
  2483. $allowed = $this->isRestartAllowed();
  2484. if ($allowed === -1) {
  2485. // Nothing allowed, do nothing.
  2486. } elseif ($allowed === 1) {
  2487. // Restart as new attempt is allowed, record a new attempt.
  2488. $this->attempt_id = $this->attempt_id + 1; // Simply reuse the previous attempt_id.
  2489. $this->current_score = 0;
  2490. $this->current_start_time = 0;
  2491. $this->current_stop_time = 0;
  2492. $this->current_data = '';
  2493. $this->status = $this->possible_status[0];
  2494. $this->interactions_count = 0;
  2495. $this->interactions = [];
  2496. $this->objectives_count = 0;
  2497. $this->objectives = [];
  2498. $this->lesson_location = '';
  2499. if ($this->type != TOOL_QUIZ) {
  2500. $this->write_to_db();
  2501. }
  2502. } else {
  2503. // Restart current element is allowed (because it's not finished yet),
  2504. // reinit current.
  2505. //$this->current_score = 0;
  2506. $this->current_start_time = 0;
  2507. $this->current_stop_time = 0;
  2508. $this->interactions_count = $this->get_interactions_count(true);
  2509. }
  2510. return true;
  2511. }
  2512. /**
  2513. * Saves data in the database.
  2514. *
  2515. * @param bool $from_outside Save from URL params (1) or from object attributes (0)
  2516. * @param bool $prereqs_complete The results of a check on prerequisites for this item.
  2517. * True if prerequisites are completed, false otherwise. Defaults to false. Only used if not sco or au
  2518. *
  2519. * @return bool True on success, false on failure
  2520. */
  2521. public function save($from_outside = true, $prereqs_complete = false)
  2522. {
  2523. $debug = self::DEBUG;
  2524. if ($debug) {
  2525. error_log('learnpathItem::save()', 0);
  2526. }
  2527. // First check if parameters passed via GET can be saved here
  2528. // in case it's a SCORM, we should get:
  2529. if ($this->type == 'sco' || $this->type == 'au') {
  2530. $status = $this->get_status(true);
  2531. if ($this->prevent_reinit == 1 &&
  2532. $status != $this->possible_status[0] && // not attempted
  2533. $status != $this->possible_status[1] //incomplete
  2534. ) {
  2535. if ($debug) {
  2536. error_log(
  2537. 'learnpathItem::save() - save reinit blocked by setting',
  2538. 0
  2539. );
  2540. }
  2541. // Do nothing because the status has already been set. Don't allow it to change.
  2542. // TODO: Check there isn't a special circumstance where this should be saved.
  2543. } else {
  2544. if ($debug) {
  2545. error_log(
  2546. 'learnpathItem::save() - SCORM save request received',
  2547. 0
  2548. );
  2549. }
  2550. // Get all new settings from the URL
  2551. if ($from_outside) {
  2552. if ($debug) {
  2553. error_log(
  2554. 'learnpathItem::save() - Getting item data from outside',
  2555. 0
  2556. );
  2557. }
  2558. foreach ($_GET as $param => $value) {
  2559. switch ($param) {
  2560. case 'score':
  2561. $this->set_score($value);
  2562. if ($debug) {
  2563. error_log(
  2564. 'learnpathItem::save() - setting score to '.$value,
  2565. 0
  2566. );
  2567. }
  2568. break;
  2569. case 'max':
  2570. $this->set_max_score($value);
  2571. if ($debug) {
  2572. error_log(
  2573. 'learnpathItem::save() - setting view_max_score to '.$value,
  2574. 0
  2575. );
  2576. }
  2577. break;
  2578. case 'min':
  2579. $this->min_score = $value;
  2580. if ($debug) {
  2581. error_log(
  2582. 'learnpathItem::save() - setting min_score to '.$value,
  2583. 0
  2584. );
  2585. }
  2586. break;
  2587. case 'lesson_status':
  2588. if (!empty($value)) {
  2589. $this->set_status($value);
  2590. if ($debug) {
  2591. error_log(
  2592. 'learnpathItem::save() - setting status to '.$value,
  2593. 0
  2594. );
  2595. }
  2596. }
  2597. break;
  2598. case 'time':
  2599. $this->set_time($value);
  2600. if ($debug) {
  2601. error_log(
  2602. 'learnpathItem::save() - setting time to '.$value,
  2603. 0
  2604. );
  2605. }
  2606. break;
  2607. case 'suspend_data':
  2608. $this->current_data = $value;
  2609. if ($debug) {
  2610. error_log(
  2611. 'learnpathItem::save() - setting suspend_data to '.$value,
  2612. 0
  2613. );
  2614. }
  2615. break;
  2616. case 'lesson_location':
  2617. $this->set_lesson_location($value);
  2618. if ($debug) {
  2619. error_log(
  2620. 'learnpathItem::save() - setting lesson_location to '.$value,
  2621. 0
  2622. );
  2623. }
  2624. break;
  2625. case 'core_exit':
  2626. $this->set_core_exit($value);
  2627. if ($debug) {
  2628. error_log(
  2629. 'learnpathItem::save() - setting core_exit to '.$value,
  2630. 0
  2631. );
  2632. }
  2633. break;
  2634. case 'interactions':
  2635. break;
  2636. case 'objectives':
  2637. break;
  2638. default:
  2639. // Ignore.
  2640. break;
  2641. }
  2642. }
  2643. } else {
  2644. if ($debug) {
  2645. error_log(
  2646. 'learnpathItem::save() - Using inside item status',
  2647. 0
  2648. );
  2649. }
  2650. // Do nothing, just let the local attributes be used.
  2651. }
  2652. }
  2653. } else {
  2654. // If not SCO, such messages should not be expected.
  2655. $type = strtolower($this->type);
  2656. if ($debug) {
  2657. error_log("type: $type");
  2658. }
  2659. switch ($type) {
  2660. case 'asset':
  2661. if ($prereqs_complete) {
  2662. $this->set_status($this->possible_status[2]);
  2663. }
  2664. break;
  2665. case TOOL_HOTPOTATOES:
  2666. break;
  2667. case TOOL_QUIZ:
  2668. return false;
  2669. break;
  2670. default:
  2671. // For now, everything that is not sco and not asset is set to
  2672. // completed when saved.
  2673. if ($prereqs_complete) {
  2674. $this->set_status($this->possible_status[2]);
  2675. }
  2676. break;
  2677. }
  2678. }
  2679. if ($debug) {
  2680. error_log(
  2681. 'New LP - End of learnpathItem::save() - Calling write_to_db()',
  2682. 0
  2683. );
  2684. }
  2685. return $this->write_to_db();
  2686. }
  2687. /**
  2688. * Sets the number of attempt_id to a given value.
  2689. *
  2690. * @param int $num The given value to set attempt_id to
  2691. *
  2692. * @return bool TRUE on success, FALSE otherwise
  2693. */
  2694. public function set_attempt_id($num)
  2695. {
  2696. if ($num == strval(intval($num)) && $num >= 0) {
  2697. $this->attempt_id = $num;
  2698. return true;
  2699. }
  2700. return false;
  2701. }
  2702. /**
  2703. * Sets the core_exit value to the one given.
  2704. *
  2705. * @return bool $value True (always)
  2706. */
  2707. public function set_core_exit($value)
  2708. {
  2709. switch ($value) {
  2710. case '':
  2711. $this->core_exit = '';
  2712. break;
  2713. case 'suspend':
  2714. $this->core_exit = 'suspend';
  2715. break;
  2716. default:
  2717. $this->core_exit = 'none';
  2718. break;
  2719. }
  2720. return true;
  2721. }
  2722. /**
  2723. * Sets the item's description.
  2724. *
  2725. * @param string $string Description
  2726. */
  2727. public function set_description($string = '')
  2728. {
  2729. if (!empty($string)) {
  2730. $this->description = $string;
  2731. }
  2732. }
  2733. /**
  2734. * Sets the lesson_location value.
  2735. *
  2736. * @param string $location lesson_location as provided by the SCO
  2737. *
  2738. * @return bool True on success, false otherwise
  2739. */
  2740. public function set_lesson_location($location)
  2741. {
  2742. if (isset($location)) {
  2743. $this->lesson_location = $location;
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. /**
  2749. * Sets the item's depth level in the LP tree (0 is at root).
  2750. *
  2751. * @param int $int Level
  2752. */
  2753. public function set_level($int = 0)
  2754. {
  2755. $this->level = (int) $int;
  2756. }
  2757. /**
  2758. * Sets the lp_view id this item view is registered to.
  2759. *
  2760. * @param int $lp_view_id lp_view DB ID
  2761. * @param int $course_id
  2762. *
  2763. * @return bool
  2764. *
  2765. * @todo //todo insert into lp_item_view if lp_view not exists
  2766. */
  2767. public function set_lp_view($lp_view_id, $course_id = null)
  2768. {
  2769. $lp_view_id = (int) $lp_view_id;
  2770. $course_id = (int) $course_id;
  2771. if (empty($course_id)) {
  2772. $course_id = api_get_course_int_id();
  2773. }
  2774. $lpItemId = $this->get_id();
  2775. if (empty($lpItemId)) {
  2776. return false;
  2777. }
  2778. if (empty($lp_view_id)) {
  2779. return false;
  2780. }
  2781. if (self::DEBUG > 0) {
  2782. error_log('learnpathItem::set_lp_view('.$lp_view_id.')', 0);
  2783. }
  2784. $this->view_id = $lp_view_id;
  2785. $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2786. // Get the lp_item_view with the highest view_count.
  2787. $sql = "SELECT * FROM $item_view_table
  2788. WHERE
  2789. c_id = $course_id AND
  2790. lp_item_id = $lpItemId AND
  2791. lp_view_id = $lp_view_id
  2792. ORDER BY view_count DESC";
  2793. if (self::DEBUG > 2) {
  2794. error_log(
  2795. 'learnpathItem::set_lp_view() - Querying lp_item_view: '.$sql,
  2796. 0
  2797. );
  2798. }
  2799. $res = Database::query($sql);
  2800. if (Database::num_rows($res) > 0) {
  2801. $row = Database::fetch_array($res);
  2802. $this->db_item_view_id = $row['iid'];
  2803. $this->attempt_id = $row['view_count'];
  2804. $this->current_score = $row['score'];
  2805. $this->current_data = $row['suspend_data'];
  2806. $this->view_max_score = $row['max_score'];
  2807. $this->status = $row['status'];
  2808. $this->current_start_time = $row['start_time'];
  2809. $this->current_stop_time = $this->current_start_time + $row['total_time'];
  2810. $this->lesson_location = $row['lesson_location'];
  2811. $this->core_exit = $row['core_exit'];
  2812. if (self::DEBUG > 2) {
  2813. error_log(
  2814. 'learnpathItem::set_lp_view() - Updated item object with database values',
  2815. 0
  2816. );
  2817. }
  2818. // Now get the number of interactions for this little guy.
  2819. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2820. $sql = "SELECT * FROM $table
  2821. WHERE
  2822. c_id = $course_id AND
  2823. lp_iv_id = '".$this->db_item_view_id."'";
  2824. $res = Database::query($sql);
  2825. if ($res !== false) {
  2826. $this->interactions_count = Database::num_rows($res);
  2827. } else {
  2828. $this->interactions_count = 0;
  2829. }
  2830. // Now get the number of objectives for this little guy.
  2831. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2832. $sql = "SELECT * FROM $table
  2833. WHERE
  2834. c_id = $course_id AND
  2835. lp_iv_id = '".$this->db_item_view_id."'";
  2836. $this->objectives_count = 0;
  2837. $res = Database::query($sql);
  2838. if ($res !== false) {
  2839. $this->objectives_count = Database::num_rows($res);
  2840. }
  2841. }
  2842. return true;
  2843. }
  2844. /**
  2845. * Sets the path.
  2846. *
  2847. * @param string $string Path
  2848. */
  2849. public function set_path($string = '')
  2850. {
  2851. if (!empty($string)) {
  2852. $this->path = $string;
  2853. }
  2854. }
  2855. /**
  2856. * Sets the prevent_reinit attribute.
  2857. * This is based on the LP value and is set at creation time for
  2858. * each learnpathItem. It is a (bad?) way of avoiding
  2859. * a reference to the LP when saving an item.
  2860. *
  2861. * @param int 1 for "prevent", 0 for "don't prevent"
  2862. * saving freshened values (new "not attempted" status etc)
  2863. */
  2864. public function set_prevent_reinit($prevent)
  2865. {
  2866. $this->prevent_reinit = 0;
  2867. if ($prevent) {
  2868. $this->prevent_reinit = 1;
  2869. }
  2870. }
  2871. /**
  2872. * Sets the score value. If the mastery_score is set and the score reaches
  2873. * it, then set the status to 'passed'.
  2874. *
  2875. * @param float $score Score
  2876. *
  2877. * @return bool True on success, false otherwise
  2878. */
  2879. public function set_score($score)
  2880. {
  2881. $debug = self::DEBUG;
  2882. if ($debug > 0) {
  2883. error_log('learnpathItem::set_score('.$score.')', 0);
  2884. }
  2885. if (($this->max_score <= 0 || $score <= $this->max_score) && ($score >= $this->min_score)) {
  2886. $this->current_score = $score;
  2887. $masteryScore = $this->get_mastery_score();
  2888. $current_status = $this->get_status(false);
  2889. // Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
  2890. if ($masteryScore == -1) {
  2891. $masteryScore = $this->max_score;
  2892. }
  2893. if ($debug > 0) {
  2894. error_log('get_mastery_score: '.$masteryScore);
  2895. error_log('current_status: '.$current_status);
  2896. error_log('current score : '.$this->current_score);
  2897. }
  2898. // If mastery_score is set AND the current score reaches the mastery
  2899. // score AND the current status is different from 'completed', then
  2900. // set it to 'passed'.
  2901. /*
  2902. if ($master != -1 && $this->current_score >= $master && $current_status != $this->possible_status[2]) {
  2903. if ($debug > 0) error_log('Status changed to: '.$this->possible_status[3]);
  2904. $this->set_status($this->possible_status[3]); //passed
  2905. } elseif ($master != -1 && $this->current_score < $master) {
  2906. if ($debug > 0) error_log('Status changed to: '.$this->possible_status[4]);
  2907. $this->set_status($this->possible_status[4]); //failed
  2908. }*/
  2909. return true;
  2910. }
  2911. return false;
  2912. }
  2913. /**
  2914. * Sets the maximum score for this item.
  2915. *
  2916. * @param int $score Maximum score - must be a decimal or an empty string
  2917. *
  2918. * @return bool True on success, false on error
  2919. */
  2920. public function set_max_score($score)
  2921. {
  2922. if (is_int($score) || $score == '') {
  2923. $this->view_max_score = $score;
  2924. return true;
  2925. }
  2926. return false;
  2927. }
  2928. /**
  2929. * Sets the status for this item.
  2930. *
  2931. * @param string $status Status - must be one of the values defined in $this->possible_status
  2932. * (this affects the status setting)
  2933. *
  2934. * @return bool True on success, false on error
  2935. */
  2936. public function set_status($status)
  2937. {
  2938. if (self::DEBUG > 0) {
  2939. error_log('learnpathItem::set_status('.$status.')', 0);
  2940. }
  2941. $found = false;
  2942. foreach ($this->possible_status as $possible) {
  2943. if (preg_match('/^'.$possible.'$/i', $status)) {
  2944. $found = true;
  2945. }
  2946. }
  2947. if ($found) {
  2948. $this->status = $status;
  2949. if (self::DEBUG > 1) {
  2950. error_log(
  2951. 'learnpathItem::set_status() - '.
  2952. 'Updated object status of item '.$this->db_id.
  2953. ' to '.$this->status,
  2954. 0
  2955. );
  2956. }
  2957. return true;
  2958. }
  2959. $this->status = $this->possible_status[0];
  2960. return false;
  2961. }
  2962. /**
  2963. * Set the (indexing) terms for this learnpath item.
  2964. *
  2965. * @param string $terms Terms, as a comma-split list
  2966. *
  2967. * @return bool Always return true
  2968. */
  2969. public function set_terms($terms)
  2970. {
  2971. global $charset;
  2972. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2973. $a_terms = preg_split('/,/', $terms);
  2974. $i_terms = preg_split('/,/', $this->get_terms());
  2975. foreach ($i_terms as $term) {
  2976. if (!in_array($term, $a_terms)) {
  2977. array_push($a_terms, $term);
  2978. }
  2979. }
  2980. $new_terms = $a_terms;
  2981. $new_terms_string = implode(',', $new_terms);
  2982. // TODO: Validate csv string.
  2983. $terms = Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset));
  2984. $sql = "UPDATE $lp_item
  2985. SET terms = '$terms'
  2986. WHERE iid=".$this->get_id();
  2987. Database::query($sql);
  2988. // Save it to search engine.
  2989. if (api_get_setting('search_enabled') == 'true') {
  2990. $di = new ChamiloIndexer();
  2991. $di->update_terms($this->get_search_did(), $new_terms, 'T');
  2992. }
  2993. return true;
  2994. }
  2995. /**
  2996. * Get the document ID from inside the text index database.
  2997. *
  2998. * @return int Search index database document ID
  2999. */
  3000. public function get_search_did()
  3001. {
  3002. return $this->search_did;
  3003. }
  3004. /**
  3005. * Sets the item viewing time in a usable form, given that SCORM packages
  3006. * often give it as 00:00:00.0000.
  3007. *
  3008. * @param string Time as given by SCORM
  3009. * @param string $format
  3010. */
  3011. public function set_time($scorm_time, $format = 'scorm')
  3012. {
  3013. $debug = self::DEBUG;
  3014. if ($debug) {
  3015. error_log("learnpathItem::set_time($scorm_time, $format)");
  3016. error_log("this->type: ".$this->type);
  3017. error_log("this->current_start_time: ".$this->current_start_time);
  3018. }
  3019. if ($scorm_time == '0' &&
  3020. $this->type != 'sco' &&
  3021. $this->current_start_time != 0
  3022. ) {
  3023. $myTime = time() - $this->current_start_time;
  3024. if ($myTime > 0) {
  3025. $this->update_time($myTime);
  3026. if ($debug) {
  3027. error_log('found asset - set time to '.$myTime);
  3028. }
  3029. } else {
  3030. if ($debug) {
  3031. error_log('Time not set');
  3032. }
  3033. }
  3034. } else {
  3035. switch ($format) {
  3036. case 'scorm':
  3037. $res = [];
  3038. if (preg_match(
  3039. '/^(\d{1,4}):(\d{2}):(\d{2})(\.\d{1,4})?/',
  3040. $scorm_time,
  3041. $res
  3042. )
  3043. ) {
  3044. $hour = $res[1];
  3045. $min = $res[2];
  3046. $sec = $res[3];
  3047. // Getting total number of seconds spent.
  3048. $totalSec = $hour * 3600 + $min * 60 + $sec;
  3049. if ($debug) {
  3050. error_log("totalSec : $totalSec");
  3051. error_log("Now calling to scorm_update_time()");
  3052. }
  3053. $this->scorm_update_time($totalSec);
  3054. }
  3055. break;
  3056. case 'int':
  3057. if ($debug) {
  3058. error_log("scorm_time = $scorm_time");
  3059. error_log("Now calling to scorm_update_time()");
  3060. }
  3061. $this->scorm_update_time($scorm_time);
  3062. break;
  3063. }
  3064. }
  3065. }
  3066. /**
  3067. * Sets the item's title.
  3068. *
  3069. * @param string $string Title
  3070. */
  3071. public function set_title($string = '')
  3072. {
  3073. if (!empty($string)) {
  3074. $this->title = $string;
  3075. }
  3076. }
  3077. /**
  3078. * Sets the item's type.
  3079. *
  3080. * @param string $string Type
  3081. */
  3082. public function set_type($string = '')
  3083. {
  3084. if (!empty($string)) {
  3085. $this->type = $string;
  3086. }
  3087. }
  3088. /**
  3089. * Checks if the current status is part of the list of status given.
  3090. *
  3091. * @param array $list An array of status to check for.
  3092. * If the current status is one of the strings, return true
  3093. *
  3094. * @return bool True if the status was one of the given strings,
  3095. * false otherwise
  3096. */
  3097. public function status_is($list = [])
  3098. {
  3099. if (self::DEBUG > 1) {
  3100. error_log(
  3101. 'learnpathItem::status_is('.print_r(
  3102. $list,
  3103. true
  3104. ).') on item '.$this->db_id,
  3105. 0
  3106. );
  3107. }
  3108. $currentStatus = $this->get_status(true);
  3109. if (empty($currentStatus)) {
  3110. return false;
  3111. }
  3112. $found = false;
  3113. foreach ($list as $status) {
  3114. if (preg_match('/^'.$status.'$/i', $currentStatus)) {
  3115. if (self::DEBUG > 2) {
  3116. error_log(
  3117. 'New LP - learnpathItem::status_is() - Found status '.
  3118. $status.' corresponding to current status',
  3119. 0
  3120. );
  3121. }
  3122. $found = true;
  3123. return $found;
  3124. }
  3125. }
  3126. if (self::DEBUG > 2) {
  3127. error_log(
  3128. 'New LP - learnpathItem::status_is() - Status '.
  3129. $currentStatus.' did not match request',
  3130. 0
  3131. );
  3132. }
  3133. return $found;
  3134. }
  3135. /**
  3136. * Updates the time info according to the given session_time.
  3137. *
  3138. * @param int $totalSec Time in seconds
  3139. */
  3140. public function update_time($totalSec = 0)
  3141. {
  3142. if (self::DEBUG > 0) {
  3143. error_log('learnpathItem::update_time('.$totalSec.')');
  3144. }
  3145. if ($totalSec >= 0) {
  3146. // Getting start time from finish time. The only problem in the calculation is it might be
  3147. // modified by the scripts processing time.
  3148. $now = time();
  3149. $start = $now - $totalSec;
  3150. $this->current_start_time = $start;
  3151. $this->current_stop_time = $now;
  3152. }
  3153. }
  3154. /**
  3155. * Special scorm update time function. This function will update time
  3156. * directly into db for scorm objects.
  3157. *
  3158. * @param int $total_sec Total number of seconds
  3159. */
  3160. public function scorm_update_time($total_sec = 0)
  3161. {
  3162. $debug = self::DEBUG;
  3163. if ($debug) {
  3164. error_log('learnpathItem::scorm_update_time()');
  3165. error_log("total_sec: $total_sec");
  3166. }
  3167. // Step 1 : get actual total time stored in db
  3168. $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3169. $course_id = api_get_course_int_id();
  3170. $sql = 'SELECT total_time, status
  3171. FROM '.$item_view_table.'
  3172. WHERE
  3173. c_id = '.$course_id.' AND
  3174. lp_item_id = "'.$this->db_id.'" AND
  3175. lp_view_id = "'.$this->view_id.'" AND
  3176. view_count = "'.$this->get_attempt_id().'"';
  3177. $result = Database::query($sql);
  3178. $row = Database::fetch_array($result);
  3179. if (!isset($row['total_time'])) {
  3180. $total_time = 0;
  3181. } else {
  3182. $total_time = $row['total_time'];
  3183. }
  3184. if ($debug) {
  3185. error_log("Original total_time: $total_time");
  3186. }
  3187. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3188. $lp_id = (int) $this->lp_id;
  3189. $sql = "SELECT * FROM $lp_table WHERE iid = $lp_id";
  3190. $res = Database::query($sql);
  3191. $accumulateScormTime = 'false';
  3192. if (Database::num_rows($res) > 0) {
  3193. $row = Database::fetch_assoc($res);
  3194. $accumulateScormTime = $row['accumulate_scorm_time'];
  3195. }
  3196. // Step 2.1 : if normal mode total_time = total_time + total_sec
  3197. if ($this->type == 'sco' && $accumulateScormTime != 0) {
  3198. if ($debug) {
  3199. error_log("accumulateScormTime is on. total_time modified: $total_time + $total_sec");
  3200. }
  3201. $total_time += $total_sec;
  3202. } else {
  3203. // Step 2.2 : if not cumulative mode total_time = total_time - last_update + total_sec
  3204. $total_sec = $this->fixAbusiveTime($total_sec);
  3205. if ($debug) {
  3206. error_log("after fix abusive: $total_sec");
  3207. error_log("total_time: $total_time");
  3208. error_log("this->last_scorm_session_time: ".$this->last_scorm_session_time);
  3209. }
  3210. $total_time = $total_time - $this->last_scorm_session_time + $total_sec;
  3211. $this->last_scorm_session_time = $total_sec;
  3212. if ($total_time < 0) {
  3213. $total_time = $total_sec;
  3214. }
  3215. }
  3216. if ($debug) {
  3217. error_log("accumulate_scorm_time: $accumulateScormTime");
  3218. error_log("total_time modified: $total_time");
  3219. }
  3220. // Step 3 update db only if status != completed, passed, browsed or seriousgamemode not activated
  3221. // @todo complete
  3222. $case_completed = [
  3223. 'completed',
  3224. 'passed',
  3225. 'browsed',
  3226. 'failed',
  3227. ];
  3228. if ($this->seriousgame_mode != 1 ||
  3229. !in_array($row['status'], $case_completed)
  3230. ) {
  3231. $sql = "UPDATE $item_view_table
  3232. SET total_time = '$total_time'
  3233. WHERE
  3234. c_id = $course_id AND
  3235. lp_item_id = {$this->db_id} AND
  3236. lp_view_id = {$this->view_id} AND
  3237. view_count = {$this->get_attempt_id()}";
  3238. if ($debug) {
  3239. error_log('-------------total_time updated ------------------------');
  3240. error_log($sql);
  3241. error_log('-------------------------------------');
  3242. }
  3243. Database::query($sql);
  3244. }
  3245. }
  3246. /**
  3247. * Set the total_time to 0 into db.
  3248. */
  3249. public function scorm_init_time()
  3250. {
  3251. $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3252. $course_id = api_get_course_int_id();
  3253. $sql = 'UPDATE '.$table.'
  3254. SET total_time = 0,
  3255. start_time = '.time().'
  3256. WHERE
  3257. c_id = '.$course_id.' AND
  3258. lp_item_id = "'.$this->db_id.'" AND
  3259. lp_view_id = "'.$this->view_id.'" AND
  3260. view_count = "'.$this->attempt_id.'"';
  3261. Database::query($sql);
  3262. }
  3263. /**
  3264. * Write objectives to DB. This method is separate from write_to_db() because otherwise
  3265. * objectives are lost as a side effect to AJAX and session concurrent access.
  3266. *
  3267. * @return bool True or false on error
  3268. */
  3269. public function write_objectives_to_db()
  3270. {
  3271. if (self::DEBUG > 0) {
  3272. error_log('learnpathItem::write_objectives_to_db()', 0);
  3273. }
  3274. if (api_is_invitee()) {
  3275. // If the user is an invitee, we don't write anything to DB
  3276. return true;
  3277. }
  3278. $course_id = api_get_course_int_id();
  3279. if (is_array($this->objectives) && count($this->objectives) > 0) {
  3280. // Save objectives.
  3281. $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3282. $sql = "SELECT iid
  3283. FROM $tbl
  3284. WHERE
  3285. c_id = $course_id AND
  3286. lp_item_id = ".$this->db_id." AND
  3287. lp_view_id = ".$this->view_id." AND
  3288. view_count = ".$this->attempt_id;
  3289. $res = Database::query($sql);
  3290. if (Database::num_rows($res) > 0) {
  3291. $row = Database::fetch_array($res);
  3292. $lp_iv_id = $row[0];
  3293. if (self::DEBUG > 2) {
  3294. error_log(
  3295. 'learnpathItem::write_to_db() - Got item_view_id '.
  3296. $lp_iv_id.', now checking objectives ',
  3297. 0
  3298. );
  3299. }
  3300. foreach ($this->objectives as $index => $objective) {
  3301. $iva_table = Database::get_course_table(
  3302. TABLE_LP_IV_OBJECTIVE
  3303. );
  3304. $iva_sql = "SELECT iid FROM $iva_table
  3305. WHERE
  3306. c_id = $course_id AND
  3307. lp_iv_id = $lp_iv_id AND
  3308. objective_id = '".Database::escape_string($objective[0])."'";
  3309. $iva_res = Database::query($iva_sql);
  3310. // id(0), type(1), time(2), weighting(3),
  3311. // correct_responses(4), student_response(5),
  3312. // result(6), latency(7)
  3313. if (Database::num_rows($iva_res) > 0) {
  3314. // Update (or don't).
  3315. $iva_row = Database::fetch_array($iva_res);
  3316. $iva_id = $iva_row[0];
  3317. $ivau_sql = "UPDATE $iva_table ".
  3318. "SET objective_id = '".Database::escape_string($objective[0])."',".
  3319. "status = '".Database::escape_string($objective[1])."',".
  3320. "score_raw = '".Database::escape_string($objective[2])."',".
  3321. "score_min = '".Database::escape_string($objective[4])."',".
  3322. "score_max = '".Database::escape_string($objective[3])."' ".
  3323. "WHERE c_id = $course_id AND iid = $iva_id";
  3324. Database::query($ivau_sql);
  3325. } else {
  3326. // Insert new one.
  3327. $params = [
  3328. 'c_id' => $course_id,
  3329. 'lp_iv_id' => $lp_iv_id,
  3330. 'order_id' => $index,
  3331. 'objective_id' => $objective[0],
  3332. 'status' => $objective[1],
  3333. 'score_raw' => $objective[2],
  3334. 'score_min' => $objective[4],
  3335. 'score_max' => $objective[3],
  3336. ];
  3337. $insertId = Database::insert($iva_table, $params);
  3338. if ($insertId) {
  3339. $sql = "UPDATE $iva_table SET id = iid
  3340. WHERE iid = $insertId";
  3341. Database::query($sql);
  3342. }
  3343. }
  3344. }
  3345. }
  3346. }
  3347. }
  3348. /**
  3349. * Writes the current data to the database.
  3350. *
  3351. * @return bool Query result
  3352. */
  3353. public function write_to_db()
  3354. {
  3355. $debug = self::DEBUG;
  3356. if ($debug) {
  3357. error_log('learnpathItem::write_to_db()', 0);
  3358. }
  3359. // Check the session visibility.
  3360. if (!api_is_allowed_to_session_edit()) {
  3361. if ($debug) {
  3362. error_log('return false api_is_allowed_to_session_edit');
  3363. }
  3364. return false;
  3365. }
  3366. if (api_is_invitee()) {
  3367. // If the user is an invitee, we don't write anything to DB
  3368. return true;
  3369. }
  3370. $course_id = api_get_course_int_id();
  3371. $mode = $this->get_lesson_mode();
  3372. $credit = $this->get_credit();
  3373. $total_time = ' ';
  3374. $my_status = ' ';
  3375. $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3376. $sql = 'SELECT status, total_time FROM '.$item_view_table.'
  3377. WHERE
  3378. c_id = '.$course_id.' AND
  3379. lp_item_id="'.$this->db_id.'" AND
  3380. lp_view_id="'.$this->view_id.'" AND
  3381. view_count="'.$this->get_attempt_id().'" ';
  3382. $rs_verified = Database::query($sql);
  3383. $row_verified = Database::fetch_array($rs_verified);
  3384. $my_case_completed = [
  3385. 'completed',
  3386. 'passed',
  3387. 'browsed',
  3388. 'failed',
  3389. ];
  3390. $oldTotalTime = $row_verified['total_time'];
  3391. $this->oldTotalTime = $oldTotalTime;
  3392. $save = true;
  3393. if (isset($row_verified) && isset($row_verified['status'])) {
  3394. if (in_array($row_verified['status'], $my_case_completed)) {
  3395. $save = false;
  3396. }
  3397. }
  3398. if ((($save === false && $this->type == 'sco') ||
  3399. ($this->type == 'sco' && ($credit == 'no-credit' || $mode == 'review' || $mode == 'browse'))) &&
  3400. ($this->seriousgame_mode != 1 && $this->type == 'sco')
  3401. ) {
  3402. if ($debug) {
  3403. error_log(
  3404. "This info shouldn't be saved as the credit or lesson mode info prevent it"
  3405. );
  3406. error_log(
  3407. 'learnpathItem::write_to_db() - credit('.$credit.') or'.
  3408. ' lesson_mode('.$mode.') prevent recording!',
  3409. 0
  3410. );
  3411. }
  3412. } else {
  3413. // Check the row exists.
  3414. $inserted = false;
  3415. // This a special case for multiple attempts and Chamilo exercises.
  3416. if ($this->type == 'quiz' &&
  3417. $this->get_prevent_reinit() == 0 &&
  3418. $this->get_status() == 'completed'
  3419. ) {
  3420. // We force the item to be restarted.
  3421. $this->restart();
  3422. $params = [
  3423. "c_id" => $course_id,
  3424. "total_time" => $this->get_total_time(),
  3425. "start_time" => $this->current_start_time,
  3426. "score" => $this->get_score(),
  3427. "status" => $this->get_status(false),
  3428. "max_score" => $this->get_max(),
  3429. "lp_item_id" => $this->db_id,
  3430. "lp_view_id" => $this->view_id,
  3431. "view_count" => $this->get_attempt_id(),
  3432. "suspend_data" => $this->current_data,
  3433. //"max_time_allowed" => ,
  3434. "lesson_location" => $this->lesson_location,
  3435. ];
  3436. if ($debug) {
  3437. error_log(
  3438. 'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
  3439. 0
  3440. );
  3441. }
  3442. $this->db_item_view_id = Database::insert($item_view_table, $params);
  3443. if ($this->db_item_view_id) {
  3444. $sql = "UPDATE $item_view_table SET id = iid
  3445. WHERE iid = ".$this->db_item_view_id;
  3446. Database::query($sql);
  3447. $inserted = true;
  3448. }
  3449. }
  3450. $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3451. $sql = "SELECT * FROM $item_view_table
  3452. WHERE
  3453. c_id = $course_id AND
  3454. lp_item_id = ".$this->db_id." AND
  3455. lp_view_id = ".$this->view_id." AND
  3456. view_count = ".$this->get_attempt_id();
  3457. if ($debug) {
  3458. error_log(
  3459. 'learnpathItem::write_to_db() - Querying item_view: '.$sql,
  3460. 0
  3461. );
  3462. }
  3463. $check_res = Database::query($sql);
  3464. // Depending on what we want (really), we'll update or insert a new row
  3465. // now save into DB.
  3466. if (!$inserted && Database::num_rows($check_res) < 1) {
  3467. $params = [
  3468. "c_id" => $course_id,
  3469. "total_time" => $this->get_total_time(),
  3470. "start_time" => $this->current_start_time,
  3471. "score" => $this->get_score(),
  3472. "status" => $this->get_status(false),
  3473. "max_score" => $this->get_max(),
  3474. "lp_item_id" => $this->db_id,
  3475. "lp_view_id" => $this->view_id,
  3476. "view_count" => $this->get_attempt_id(),
  3477. "suspend_data" => $this->current_data,
  3478. //"max_time_allowed" => ,$this->get_max_time_allowed()
  3479. "lesson_location" => $this->lesson_location,
  3480. ];
  3481. if ($debug) {
  3482. error_log(
  3483. 'learnpathItem::write_to_db() - Inserting into item_view forced: '.print_r($params, 1),
  3484. 0
  3485. );
  3486. }
  3487. $this->db_item_view_id = Database::insert($item_view_table, $params);
  3488. if ($this->db_item_view_id) {
  3489. $sql = "UPDATE $item_view_table SET id = iid
  3490. WHERE iid = ".$this->db_item_view_id;
  3491. Database::query($sql);
  3492. }
  3493. } else {
  3494. if ($this->type === 'hotpotatoes') {
  3495. $params = [
  3496. 'total_time' => $this->get_total_time(),
  3497. 'start_time' => $this->get_current_start_time(),
  3498. 'score' => $this->get_score(),
  3499. 'status' => $this->get_status(false),
  3500. 'max_score' => $this->get_max(),
  3501. 'suspend_data' => $this->current_data,
  3502. 'lesson_location' => $this->lesson_location,
  3503. ];
  3504. $where = [
  3505. 'c_id = ? AND lp_item_id = ? AND lp_view_id = ? AND view_count = ?' => [
  3506. $course_id,
  3507. $this->db_id,
  3508. $this->view_id,
  3509. $this->get_attempt_id(),
  3510. ],
  3511. ];
  3512. Database::update($item_view_table, $params, $where);
  3513. } else {
  3514. // For all other content types...
  3515. if ($this->type == 'quiz') {
  3516. if ($debug) {
  3517. error_log("item is quiz:");
  3518. }
  3519. $my_status = ' ';
  3520. $total_time = ' ';
  3521. if (!empty($_REQUEST['exeId'])) {
  3522. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  3523. $exeId = (int) $_REQUEST['exeId'];
  3524. $sql = "SELECT exe_duration
  3525. FROM $table
  3526. WHERE exe_id = $exeId";
  3527. if ($debug) {
  3528. error_log($sql);
  3529. }
  3530. $res = Database::query($sql);
  3531. $exeRow = Database::fetch_array($res);
  3532. $duration = $exeRow['exe_duration'];
  3533. $total_time = " total_time = ".$duration.", ";
  3534. if ($debug) {
  3535. error_log("quiz: $total_time");
  3536. }
  3537. }
  3538. } else {
  3539. $my_type_lp = learnpath::get_type_static($this->lp_id);
  3540. // This is a array containing values finished
  3541. $case_completed = [
  3542. 'completed',
  3543. 'passed',
  3544. 'browsed',
  3545. 'failed',
  3546. ];
  3547. // Is not multiple attempts
  3548. if ($this->seriousgame_mode == 1 && $this->type == 'sco') {
  3549. $total_time = " total_time = total_time +".$this->get_total_time().", ";
  3550. $my_status = " status = '".$this->get_status(false)."' ,";
  3551. if ($debug) {
  3552. error_log("seriousgame_mode time changed: $total_time");
  3553. }
  3554. } elseif ($this->get_prevent_reinit() == 1) {
  3555. // Process of status verified into data base.
  3556. $sql = 'SELECT status FROM '.$item_view_table.'
  3557. WHERE
  3558. c_id = '.$course_id.' AND
  3559. lp_item_id="'.$this->db_id.'" AND
  3560. lp_view_id="'.$this->view_id.'" AND
  3561. view_count="'.$this->get_attempt_id().'"
  3562. ';
  3563. $rs_verified = Database::query($sql);
  3564. $row_verified = Database::fetch_array($rs_verified);
  3565. // Get type lp: 1=lp dokeos and 2=scorm.
  3566. // If not is completed or passed or browsed and learning path is scorm.
  3567. if (!in_array($this->get_status(false), $case_completed) &&
  3568. $my_type_lp == 2
  3569. ) {
  3570. $total_time = " total_time = total_time +".$this->get_total_time().", ";
  3571. $my_status = " status = '".$this->get_status(false)."' ,";
  3572. if ($debug) {
  3573. error_log("get_prevent_reinit = 1 time changed: $total_time");
  3574. }
  3575. } else {
  3576. // Verified into database.
  3577. if (!in_array($row_verified['status'], $case_completed) &&
  3578. $my_type_lp == 2
  3579. ) {
  3580. $total_time = " total_time = total_time +".$this->get_total_time().", ";
  3581. $my_status = " status = '".$this->get_status(false)."' ,";
  3582. if ($debug) {
  3583. error_log("total_time time changed case 1: $total_time");
  3584. }
  3585. } elseif (in_array($row_verified['status'], $case_completed) &&
  3586. $my_type_lp == 2 && $this->type != 'sco'
  3587. ) {
  3588. $total_time = " total_time = total_time +".$this->get_total_time().", ";
  3589. $my_status = " status = '".$this->get_status(false)."' ,";
  3590. if ($debug) {
  3591. error_log("total_time time changed case 2: $total_time");
  3592. }
  3593. } else {
  3594. if (($my_type_lp == 3 && $this->type == 'au') ||
  3595. ($my_type_lp == 1 && $this->type != 'dir')) {
  3596. // Is AICC or Chamilo LP
  3597. $total_time = " total_time = total_time + ".$this->get_total_time().", ";
  3598. $my_status = " status = '".$this->get_status(false)."' ,";
  3599. if ($debug) {
  3600. error_log("total_time time changed case 3: $total_time");
  3601. }
  3602. }
  3603. }
  3604. }
  3605. } else {
  3606. // Multiple attempts are allowed.
  3607. if (in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
  3608. // Reset zero new attempt ?
  3609. $my_status = " status = '".$this->get_status(false)."' ,";
  3610. if ($debug) {
  3611. error_log("total_time time changed Multiple attempt case 1: $total_time");
  3612. }
  3613. } elseif (!in_array($this->get_status(false), $case_completed) && $my_type_lp == 2) {
  3614. $total_time = " total_time = ".$this->get_total_time().", ";
  3615. $my_status = " status = '".$this->get_status(false)."' ,";
  3616. if ($debug) {
  3617. error_log("total_time time changed Multiple attempt case 2: $total_time");
  3618. }
  3619. } else {
  3620. // It is chamilo LP.
  3621. $total_time = " total_time = total_time +".$this->get_total_time().", ";
  3622. $my_status = " status = '".$this->get_status(false)."' ,";
  3623. if ($debug) {
  3624. error_log("total_time time changed Multiple attempt case 3: $total_time");
  3625. }
  3626. }
  3627. // This code line fixes the problem of wrong status.
  3628. if ($my_type_lp == 2) {
  3629. // Verify current status in multiples attempts.
  3630. $sql = 'SELECT status FROM '.$item_view_table.'
  3631. WHERE
  3632. c_id = '.$course_id.' AND
  3633. lp_item_id="'.$this->db_id.'" AND
  3634. lp_view_id="'.$this->view_id.'" AND
  3635. view_count="'.$this->get_attempt_id().'" ';
  3636. $rs_status = Database::query($sql);
  3637. $current_status = Database::result(
  3638. $rs_status,
  3639. 0,
  3640. 'status'
  3641. );
  3642. if (in_array($current_status, $case_completed)) {
  3643. $my_status = '';
  3644. $total_time = '';
  3645. } else {
  3646. $total_time = " total_time = total_time + ".$this->get_total_time().", ";
  3647. }
  3648. if ($debug) {
  3649. error_log("total_time time my_type_lp: $total_time");
  3650. }
  3651. }
  3652. }
  3653. }
  3654. if ($this->type == 'sco') {
  3655. //IF scorm scorm_update_time has already updated total_time in db
  3656. //" . //start_time = ".$this->get_current_start_time().", " . //scorm_init_time does it
  3657. ////" max_time_allowed = '".$this->get_max_time_allowed()."'," .
  3658. $sql = "UPDATE $item_view_table SET
  3659. score = ".$this->get_score().",
  3660. $my_status
  3661. max_score = '".$this->get_max()."',
  3662. suspend_data = '".Database::escape_string($this->current_data)."',
  3663. lesson_location = '".$this->lesson_location."'
  3664. WHERE
  3665. c_id = $course_id AND
  3666. lp_item_id = ".$this->db_id." AND
  3667. lp_view_id = ".$this->view_id." AND
  3668. view_count = ".$this->get_attempt_id();
  3669. } else {
  3670. //" max_time_allowed = '".$this->get_max_time_allowed()."'," .
  3671. $sql = "UPDATE $item_view_table SET
  3672. $total_time
  3673. start_time = ".$this->get_current_start_time().",
  3674. score = ".$this->get_score().",
  3675. $my_status
  3676. max_score = '".$this->get_max()."',
  3677. suspend_data = '".Database::escape_string($this->current_data)."',
  3678. lesson_location = '".$this->lesson_location."'
  3679. WHERE
  3680. c_id = $course_id AND
  3681. lp_item_id = ".$this->db_id." AND
  3682. lp_view_id = ".$this->view_id." AND
  3683. view_count = ".$this->get_attempt_id();
  3684. }
  3685. $this->current_start_time = time();
  3686. }
  3687. if ($debug) {
  3688. error_log('-------------------------------------------');
  3689. error_log('learnpathItem::write_to_db() - Updating item_view:');
  3690. error_log($sql);
  3691. error_log('-------------------------------------------');
  3692. }
  3693. Database::query($sql);
  3694. }
  3695. if (is_array($this->interactions) &&
  3696. count($this->interactions) > 0
  3697. ) {
  3698. // Save interactions.
  3699. $tbl = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3700. $sql = "SELECT iid FROM $tbl
  3701. WHERE
  3702. c_id = $course_id AND
  3703. lp_item_id = ".$this->db_id." AND
  3704. lp_view_id = ".$this->view_id." AND
  3705. view_count = ".$this->get_attempt_id();
  3706. $res = Database::query($sql);
  3707. if (Database::num_rows($res) > 0) {
  3708. $row = Database::fetch_array($res);
  3709. $lp_iv_id = $row[0];
  3710. if ($debug) {
  3711. error_log(
  3712. 'learnpathItem::write_to_db() - Got item_view_id '.
  3713. $lp_iv_id.', now checking interactions ',
  3714. 0
  3715. );
  3716. }
  3717. foreach ($this->interactions as $index => $interaction) {
  3718. $correct_resp = '';
  3719. if (is_array($interaction[4]) && !empty($interaction[4][0])) {
  3720. foreach ($interaction[4] as $resp) {
  3721. $correct_resp .= $resp.',';
  3722. }
  3723. $correct_resp = substr(
  3724. $correct_resp,
  3725. 0,
  3726. strlen($correct_resp) - 1
  3727. );
  3728. }
  3729. $iva_table = Database::get_course_table(
  3730. TABLE_LP_IV_INTERACTION
  3731. );
  3732. //also check for the interaction ID as it must be unique for this SCO view
  3733. $iva_sql = "SELECT iid FROM $iva_table
  3734. WHERE
  3735. c_id = $course_id AND
  3736. lp_iv_id = $lp_iv_id AND
  3737. (
  3738. order_id = $index OR
  3739. interaction_id = '".Database::escape_string($interaction[0])."'
  3740. )
  3741. ";
  3742. $iva_res = Database::query($iva_sql);
  3743. $interaction[0] = isset($interaction[0]) ? $interaction[0] : '';
  3744. $interaction[1] = isset($interaction[1]) ? $interaction[1] : '';
  3745. $interaction[2] = isset($interaction[2]) ? $interaction[2] : '';
  3746. $interaction[3] = isset($interaction[3]) ? $interaction[3] : '';
  3747. $interaction[4] = isset($interaction[4]) ? $interaction[4] : '';
  3748. $interaction[5] = isset($interaction[5]) ? $interaction[5] : '';
  3749. $interaction[6] = isset($interaction[6]) ? $interaction[6] : '';
  3750. $interaction[7] = isset($interaction[7]) ? $interaction[7] : '';
  3751. // id(0), type(1), time(2), weighting(3), correct_responses(4), student_response(5), result(6), latency(7)
  3752. if (Database::num_rows($iva_res) > 0) {
  3753. // Update (or don't).
  3754. $iva_row = Database::fetch_array($iva_res);
  3755. $iva_id = $iva_row[0];
  3756. // Insert new one.
  3757. $params = [
  3758. 'interaction_id' => $interaction[0],
  3759. 'interaction_type' => $interaction[1],
  3760. 'weighting' => $interaction[3],
  3761. 'completion_time' => $interaction[2],
  3762. 'correct_responses' => $correct_resp,
  3763. 'student_response' => $interaction[5],
  3764. 'result' => $interaction[6],
  3765. 'latency' => $interaction[7],
  3766. ];
  3767. Database::update(
  3768. $iva_table,
  3769. $params,
  3770. [
  3771. 'c_id = ? AND iid = ?' => [
  3772. $course_id,
  3773. $iva_id,
  3774. ],
  3775. ]
  3776. );
  3777. } else {
  3778. // Insert new one.
  3779. $params = [
  3780. 'c_id' => $course_id,
  3781. 'order_id' => $index,
  3782. 'lp_iv_id' => $lp_iv_id,
  3783. 'interaction_id' => $interaction[0],
  3784. 'interaction_type' => $interaction[1],
  3785. 'weighting' => $interaction[3],
  3786. 'completion_time' => $interaction[2],
  3787. 'correct_responses' => $correct_resp,
  3788. 'student_response' => $interaction[5],
  3789. 'result' => $interaction[6],
  3790. 'latency' => $interaction[7],
  3791. ];
  3792. $insertId = Database::insert($iva_table, $params);
  3793. if ($insertId) {
  3794. $sql = "UPDATE $iva_table SET id = iid
  3795. WHERE iid = $insertId";
  3796. Database::query($sql);
  3797. }
  3798. }
  3799. }
  3800. }
  3801. }
  3802. }
  3803. if ($debug) {
  3804. error_log('End of learnpathItem::write_to_db()', 0);
  3805. }
  3806. return true;
  3807. }
  3808. /**
  3809. * Adds an audio file attached to the current item (store on disk and in db).
  3810. *
  3811. * @return bool|string|null
  3812. */
  3813. public function add_audio()
  3814. {
  3815. $course_info = api_get_course_info();
  3816. $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/';
  3817. if (!is_dir($filepath.'audio')) {
  3818. mkdir(
  3819. $filepath.'audio',
  3820. api_get_permissions_for_new_directories()
  3821. );
  3822. DocumentManager::addDocument(
  3823. $course_info,
  3824. '/audio',
  3825. 'folder',
  3826. 0,
  3827. 'audio'
  3828. );
  3829. }
  3830. $key = 'file';
  3831. if (!isset($_FILES[$key]['name']) || !isset($_FILES[$key]['tmp_name'])) {
  3832. return false;
  3833. }
  3834. $result = DocumentManager::upload_document(
  3835. $_FILES,
  3836. '/audio',
  3837. null,
  3838. null,
  3839. 0,
  3840. 'rename',
  3841. false,
  3842. false
  3843. );
  3844. $file_path = null;
  3845. if ($result) {
  3846. $file_path = basename($result['path']);
  3847. // Store the mp3 file in the lp_item table.
  3848. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3849. $sql = "UPDATE $tbl_lp_item SET
  3850. audio = '".Database::escape_string($file_path)."'
  3851. WHERE iid = ".intval($this->db_id);
  3852. Database::query($sql);
  3853. }
  3854. return $file_path;
  3855. }
  3856. /**
  3857. * Adds an audio file to the current item, using a file already in documents.
  3858. *
  3859. * @param int $doc_id
  3860. *
  3861. * @return string
  3862. */
  3863. public function add_audio_from_documents($doc_id)
  3864. {
  3865. $course_info = api_get_course_info();
  3866. $document_data = DocumentManager::get_document_data_by_id(
  3867. $doc_id,
  3868. $course_info['code']
  3869. );
  3870. $file_path = '';
  3871. if (!empty($document_data)) {
  3872. $file_path = basename($document_data['path']);
  3873. // Store the mp3 file in the lp_item table.
  3874. $table = Database::get_course_table(TABLE_LP_ITEM);
  3875. $sql = "UPDATE $table SET
  3876. audio = '".Database::escape_string($file_path)."'
  3877. WHERE iid = ".intval($this->db_id);
  3878. Database::query($sql);
  3879. }
  3880. return $file_path;
  3881. }
  3882. /**
  3883. * Removes the relation between the current item and an audio file. The file
  3884. * is only removed from the lp_item table, but remains in the document table
  3885. * and directory.
  3886. *
  3887. * @return bool
  3888. */
  3889. public function remove_audio()
  3890. {
  3891. if (empty($this->db_id)) {
  3892. return false;
  3893. }
  3894. $table = Database::get_course_table(TABLE_LP_ITEM);
  3895. $sql = "UPDATE $table SET
  3896. audio = ''
  3897. WHERE iid IN (".$this->db_id.")";
  3898. Database::query($sql);
  3899. }
  3900. /**
  3901. * Transform the SCORM status to a string that can be translated by Chamilo
  3902. * in different user languages.
  3903. *
  3904. * @param $status
  3905. * @param bool $decorate
  3906. * @param string $type classic|simple
  3907. *
  3908. * @return array|string
  3909. */
  3910. public static function humanize_status($status, $decorate = true, $type = 'classic')
  3911. {
  3912. $statusList = [
  3913. 'completed' => 'ScormCompstatus',
  3914. 'incomplete' => 'ScormIncomplete',
  3915. 'failed' => 'ScormFailed',
  3916. 'passed' => 'ScormPassed',
  3917. 'browsed' => 'ScormBrowsed',
  3918. 'not attempted' => 'ScormNotAttempted',
  3919. ];
  3920. $myLessonStatus = get_lang($statusList[$status]);
  3921. switch ($status) {
  3922. case 'completed':
  3923. case 'browsed':
  3924. $classStatus = 'info';
  3925. break;
  3926. case 'incomplete':
  3927. $classStatus = 'warning';
  3928. break;
  3929. case 'passed':
  3930. $classStatus = 'success';
  3931. break;
  3932. case 'failed':
  3933. $classStatus = 'important';
  3934. break;
  3935. default:
  3936. $classStatus = 'default';
  3937. break;
  3938. }
  3939. if ($type == 'simple') {
  3940. if (in_array($status, ['failed', 'passed', 'browsed'])) {
  3941. $myLessonStatus = get_lang('Incomplete');
  3942. $classStatus = 'warning';
  3943. }
  3944. }
  3945. if ($decorate) {
  3946. return Display::label($myLessonStatus, $classStatus);
  3947. } else {
  3948. return $myLessonStatus;
  3949. }
  3950. }
  3951. /**
  3952. * @return float
  3953. */
  3954. public function getPrerequisiteMaxScore()
  3955. {
  3956. return $this->prerequisiteMaxScore;
  3957. }
  3958. /**
  3959. * @param float $prerequisiteMaxScore
  3960. */
  3961. public function setPrerequisiteMaxScore($prerequisiteMaxScore)
  3962. {
  3963. $this->prerequisiteMaxScore = $prerequisiteMaxScore;
  3964. }
  3965. /**
  3966. * @return float
  3967. */
  3968. public function getPrerequisiteMinScore()
  3969. {
  3970. return $this->prerequisiteMinScore;
  3971. }
  3972. /**
  3973. * @param float $prerequisiteMinScore
  3974. */
  3975. public function setPrerequisiteMinScore($prerequisiteMinScore)
  3976. {
  3977. $this->prerequisiteMinScore = $prerequisiteMinScore;
  3978. }
  3979. /**
  3980. * Check if this LP item has a created thread in the basis course from the forum of its LP.
  3981. *
  3982. * @param int $lpCourseId The course ID
  3983. *
  3984. * @return bool
  3985. */
  3986. public function lpItemHasThread($lpCourseId)
  3987. {
  3988. $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
  3989. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3990. $fakeFrom = "
  3991. $forumThreadTable ft
  3992. INNER JOIN $itemProperty ip
  3993. ON (ft.thread_id = ip.ref AND ft.c_id = ip.c_id)
  3994. ";
  3995. $resultData = Database::select(
  3996. 'COUNT(ft.iid) AS qty',
  3997. $fakeFrom,
  3998. [
  3999. 'where' => [
  4000. 'ip.visibility != ? AND ' => 2,
  4001. 'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
  4002. 'ft.c_id = ? AND ' => intval($lpCourseId),
  4003. '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
  4004. intval($this->db_id),
  4005. "{$this->title} - {$this->db_id}",
  4006. intval($this->db_id),
  4007. ],
  4008. ],
  4009. ],
  4010. 'first'
  4011. );
  4012. if ($resultData['qty'] > 0) {
  4013. return true;
  4014. }
  4015. return false;
  4016. }
  4017. /**
  4018. * Get the forum thread info.
  4019. *
  4020. * @param int $lpCourseId The course ID from the learning path
  4021. * @param int $lpSessionId Optional. The session ID from the learning path
  4022. *
  4023. * @return bool
  4024. */
  4025. public function getForumThread($lpCourseId, $lpSessionId = 0)
  4026. {
  4027. $lpSessionId = (int) $lpSessionId;
  4028. $lpCourseId = (int) $lpCourseId;
  4029. $forumThreadTable = Database::get_course_table(TABLE_FORUM_THREAD);
  4030. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  4031. $fakeFrom = "$forumThreadTable ft INNER JOIN $itemProperty ip ";
  4032. if ($lpSessionId == 0) {
  4033. $fakeFrom .= "
  4034. ON (
  4035. ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND (
  4036. ft.session_id = ip.session_id OR ip.session_id IS NULL
  4037. )
  4038. )
  4039. ";
  4040. } else {
  4041. $fakeFrom .= "
  4042. ON (
  4043. ft.thread_id = ip.ref AND ft.c_id = ip.c_id AND ft.session_id = ip.session_id
  4044. )
  4045. ";
  4046. }
  4047. $resultData = Database::select(
  4048. 'ft.*',
  4049. $fakeFrom,
  4050. [
  4051. 'where' => [
  4052. 'ip.visibility != ? AND ' => 2,
  4053. 'ip.tool = ? AND ' => TOOL_FORUM_THREAD,
  4054. 'ft.session_id = ? AND ' => $lpSessionId,
  4055. 'ft.c_id = ? AND ' => $lpCourseId,
  4056. '(ft.lp_item_id = ? OR (ft.thread_title = ? AND ft.lp_item_id = ?))' => [
  4057. intval($this->db_id),
  4058. "{$this->title} - {$this->db_id}",
  4059. intval($this->db_id),
  4060. ],
  4061. ],
  4062. ],
  4063. 'first'
  4064. );
  4065. if (empty($resultData)) {
  4066. return false;
  4067. }
  4068. return $resultData;
  4069. }
  4070. /**
  4071. * Create a forum thread for this learning path item.
  4072. *
  4073. * @param int $currentForumId The forum ID to add the new thread
  4074. *
  4075. * @return int The forum thread if was created. Otherwise return false
  4076. */
  4077. public function createForumThread($currentForumId)
  4078. {
  4079. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  4080. $currentForumId = (int) $currentForumId;
  4081. $em = Database::getManager();
  4082. $threadRepo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  4083. $forumThread = $threadRepo->findOneBy([
  4084. 'threadTitle' => "{$this->title} - {$this->db_id}",
  4085. 'forumId' => $currentForumId,
  4086. ]);
  4087. if (!$forumThread) {
  4088. $forumInfo = get_forum_information($currentForumId);
  4089. store_thread(
  4090. $forumInfo,
  4091. [
  4092. 'forum_id' => $currentForumId,
  4093. 'thread_id' => 0,
  4094. 'gradebook' => 0,
  4095. 'post_title' => "{$this->name} - {$this->db_id}",
  4096. 'post_text' => $this->description,
  4097. 'category_id' => 1,
  4098. 'numeric_calification' => 0,
  4099. 'calification_notebook_title' => 0,
  4100. 'weight_calification' => 0.00,
  4101. 'thread_peer_qualify' => 0,
  4102. 'lp_item_id' => $this->db_id,
  4103. ],
  4104. [],
  4105. false
  4106. );
  4107. return;
  4108. }
  4109. $forumThread->setLpItemId($this->db_id);
  4110. $em->persist($forumThread);
  4111. $em->flush();
  4112. }
  4113. /**
  4114. * Allow dissociate a forum to this LP item.
  4115. *
  4116. * @param int $threadIid The thread id
  4117. *
  4118. * @return bool
  4119. */
  4120. public function dissociateForumThread($threadIid)
  4121. {
  4122. $threadIid = (int) $threadIid;
  4123. $em = Database::getManager();
  4124. $forumThread = $em->find('ChamiloCourseBundle:CForumThread', $threadIid);
  4125. if (!$forumThread) {
  4126. return false;
  4127. }
  4128. $forumThread->setThreadTitle("{$this->get_title()} - {$this->db_id}");
  4129. $forumThread->setLpItemId(0);
  4130. $em->persist($forumThread);
  4131. $em->flush();
  4132. return true;
  4133. }
  4134. /**
  4135. * @return int
  4136. */
  4137. public function getLastScormSessionTime()
  4138. {
  4139. return $this->last_scorm_session_time;
  4140. }
  4141. /**
  4142. * @return int
  4143. */
  4144. public function getIid()
  4145. {
  4146. return $this->iId;
  4147. }
  4148. /**
  4149. * @param int $user_id
  4150. * @param string $prereqs_string
  4151. * @param array $refs_list
  4152. *
  4153. * @return bool
  4154. */
  4155. public function getStatusFromOtherSessions($user_id, $prereqs_string, $refs_list)
  4156. {
  4157. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  4158. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  4159. $course_id = api_get_course_int_id();
  4160. $user_id = (int) $user_id;
  4161. // Check results from another sessions:
  4162. $checkOtherSessions = api_get_configuration_value('validate_lp_prerequisite_from_other_session');
  4163. if ($checkOtherSessions) {
  4164. // Check items
  4165. $sql = "SELECT iid FROM $lp_view
  4166. WHERE
  4167. c_id = $course_id AND
  4168. user_id = $user_id AND
  4169. lp_id = $this->lp_id AND
  4170. session_id <> 0
  4171. ";
  4172. $result = Database::query($sql);
  4173. $resultFromOtherSessions = false;
  4174. while ($row = Database::fetch_array($result)) {
  4175. $lpIid = $row['iid'];
  4176. $sql = "SELECT status FROM $lp_item_view
  4177. WHERE
  4178. c_id = $course_id AND
  4179. lp_view_id = $lpIid AND
  4180. lp_item_id = $refs_list[$prereqs_string]
  4181. LIMIT 1";
  4182. $resultRow = Database::query($sql);
  4183. if (Database::num_rows($resultRow)) {
  4184. $statusResult = Database::fetch_array($resultRow);
  4185. $status = $statusResult['status'];
  4186. $checked = $status == $this->possible_status[2] || $status == $this->possible_status[3];
  4187. if ($checked) {
  4188. $resultFromOtherSessions = true;
  4189. break;
  4190. }
  4191. }
  4192. }
  4193. return $resultFromOtherSessions;
  4194. }
  4195. }
  4196. }