learnpathItem.class.php 186 KB

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