learnpathItem.class.php 191 KB

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